code_text
stringlengths 604
999k
| repo_name
stringlengths 4
100
| file_path
stringlengths 4
873
| language
stringclasses 23
values | license
stringclasses 15
values | size
int32 1.02k
999k
|
---|---|---|---|---|---|
/*! Widget: alignChar - updated 2/7/2015 (v2.19.0) */
!function(a){"use strict";var b=a.tablesorter;b.alignChar={init:function(c,d,e){d.$headers.filter("["+e.alignChar_charAttrib+"]").each(function(){var f=a(this),g={column:this.column,align:f.attr(e.alignChar_charAttrib),alignIndex:parseInt(f.attr(e.alignChar_indexAttrib)||0,10),adjust:parseFloat(f.attr(e.alignChar_adjustAttrib))||0};g.regex=new RegExp("\\"+g.align,"g"),"undefined"!=typeof g.align&&(e.alignChar_savedVars[this.column]=g,b.alignChar.setup(c,d,e,g))})},setup:function(b,c,d,e){if(!a.isEmptyObject(c.cache)){var f,g,h,i,j,k,l,m,n,o,p,q,r,s,t=[],u=[];for(f=0;f<c.$tbodies.length;f++)for(l=c.cache[f],o=l.normalized.length,g=0;g<o;g++){if(s=l.row?l.row[g]:l.normalized[g][c.columns].$row,m=s.find("td").eq(e.column).text().replace(/[ ]/g," "),n=(m.match(e.regex)||[]).length,n>0&&e.alignIndex>0)for(i=Math.min(e.alignIndex,n),h=0,k=0,j=0;h++<i;)j=m.indexOf(e.align,j+1),k=j<0?k:j;else k=m.indexOf(e.align);k>=0?(t.push(m.substring(0,k)||""),u.push(m.substring(k,m.length)||"")):(t.push(n>=1&&e.alignIndex>=n?"":m||""),u.push(n>=1&&e.alignIndex>=n?m||"":""))}for(p=a.extend([],t).sort(function(a,b){return b.length-a.length})[0],q=a.extend([],u).sort(function(a,b){return b.length-a.length})[0],e.width=e.width||Math.floor(p.length/(p.length+q.length)*100)+e.adjust,p="min-width:"+e.width+"%",q="min-width:"+(100-e.width)+"%",f=0;f<c.$tbodies.length;f++)for(l=c.cache[f],o=l.normalized.length,g=0;g<o;g++)r=a(d.alignChar_wrap).length?a(d.alignChar_wrap).html(e.align)[0].outerHTML:e.align,s=l.row?l.row[g]:l.normalized[g][c.columns].$row,j=u[g].slice(e.align.length),s.find("td").eq(e.column).html('<span class="ts-align-wrap"><span class="ts-align-left" style="'+p+'">'+t[g]+'</span><span class="ts-align-right" style="'+q+'">'+(j.length?r+j:"")+"</span></span>");d.alignChar_initialized=!0}},remove:function(b,c,d){if(!a.isEmptyObject(c.cache)){var e,f,g,h,i,j;for(e=0;e<c.$tbodies.length;e++)for(h=c.cache[e],g=h.normalized.length,f=0;f<g;f++)i=h.row?h.row[f]:h.normalized[f][c.columns].$row,j=i.find("td").eq(d),j.html(j.text().replace(/\s/g," "))}}},b.addWidget({id:"alignChar",priority:100,options:{alignChar_wrap:"",alignChar_charAttrib:"data-align-char",alignChar_indexAttrib:"data-align-index",alignChar_adjustAttrib:"data-align-adjust"},init:function(a,c,d,e){e.alignChar_initialized=!1,e.alignChar_savedVars=[],b.alignChar.init(a,d,e),d.$table.on("pagerEnd refreshAlign",function(){d.$headers.filter("["+e.alignChar_charAttrib+"]").each(function(){b.alignChar.remove(a,d,this.column)}),b.alignChar.init(a,d,e)})},format:function(a,b,c){c.alignChar_initialized||b.$table.triggerHandler("refreshAlign")},remove:function(a,c,d,e){e||(c.$headers.filter("["+d.alignChar_charAttrib+"]").each(function(){b.alignChar.remove(a,c,this.column)}),d.alignChar_initialized=!1)}})}(jQuery); | jdh8/cdnjs | ajax/libs/jquery.tablesorter/2.28.1/js/widgets/widget-alignChar.min.js | JavaScript | mit | 2,853 |
/**
* @author mrdoob / http://mrdoob.com/
* @author Larry Battle / http://bateru.com/news
*/
var THREE = THREE || { REVISION: '52' };
self.console = self.console || {
info: function () {},
log: function () {},
debug: function () {},
warn: function () {},
error: function () {}
};
self.Int32Array = self.Int32Array || Array;
self.Float32Array = self.Float32Array || Array;
// Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
// not sure we should have this, or at least not have it here
// http://stackoverflow.com/questions/646628/javascript-startswith
// http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
// http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
return this.slice( 0, str.length ) === str;
};
String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
var t = String( str );
var index = this.lastIndexOf( t );
return ( -1 < index && index ) === (this.length - t.length);
};
String.prototype.trim = String.prototype.trim || function () {
return this.replace( /^\s+|\s+$/g, '' );
};
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel
( function () {
var lastTime = 0;
var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
}
if ( window.requestAnimationFrame === undefined ) {
window.requestAnimationFrame = function ( callback, element ) {
var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
lastTime = currTime + timeToCall;
return id;
};
}
window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
}() );
// MATERIAL CONSTANTS
// side
THREE.FrontSide = 0;
THREE.BackSide = 1;
THREE.DoubleSide = 2;
// shading
THREE.NoShading = 0;
THREE.FlatShading = 1;
THREE.SmoothShading = 2;
// colors
THREE.NoColors = 0;
THREE.FaceColors = 1;
THREE.VertexColors = 2;
// blending modes
THREE.NoBlending = 0;
THREE.NormalBlending = 1;
THREE.AdditiveBlending = 2;
THREE.SubtractiveBlending = 3;
THREE.MultiplyBlending = 4;
THREE.CustomBlending = 5;
// custom blending equations
// (numbers start from 100 not to clash with other
// mappings to OpenGL constants defined in Texture.js)
THREE.AddEquation = 100;
THREE.SubtractEquation = 101;
THREE.ReverseSubtractEquation = 102;
// custom blending destination factors
THREE.ZeroFactor = 200;
THREE.OneFactor = 201;
THREE.SrcColorFactor = 202;
THREE.OneMinusSrcColorFactor = 203;
THREE.SrcAlphaFactor = 204;
THREE.OneMinusSrcAlphaFactor = 205;
THREE.DstAlphaFactor = 206;
THREE.OneMinusDstAlphaFactor = 207;
// custom blending source factors
//THREE.ZeroFactor = 200;
//THREE.OneFactor = 201;
//THREE.SrcAlphaFactor = 204;
//THREE.OneMinusSrcAlphaFactor = 205;
//THREE.DstAlphaFactor = 206;
//THREE.OneMinusDstAlphaFactor = 207;
THREE.DstColorFactor = 208;
THREE.OneMinusDstColorFactor = 209;
THREE.SrcAlphaSaturateFactor = 210;
// TEXTURE CONSTANTS
THREE.MultiplyOperation = 0;
THREE.MixOperation = 1;
// Mapping modes
THREE.UVMapping = function () {};
THREE.CubeReflectionMapping = function () {};
THREE.CubeRefractionMapping = function () {};
THREE.SphericalReflectionMapping = function () {};
THREE.SphericalRefractionMapping = function () {};
// Wrapping modes
THREE.RepeatWrapping = 1000;
THREE.ClampToEdgeWrapping = 1001;
THREE.MirroredRepeatWrapping = 1002;
// Filters
THREE.NearestFilter = 1003;
THREE.NearestMipMapNearestFilter = 1004;
THREE.NearestMipMapLinearFilter = 1005;
THREE.LinearFilter = 1006;
THREE.LinearMipMapNearestFilter = 1007;
THREE.LinearMipMapLinearFilter = 1008;
// Data types
THREE.UnsignedByteType = 1009;
THREE.ByteType = 1010;
THREE.ShortType = 1011;
THREE.UnsignedShortType = 1012;
THREE.IntType = 1013;
THREE.UnsignedIntType = 1014;
THREE.FloatType = 1015;
// Pixel types
//THREE.UnsignedByteType = 1009;
THREE.UnsignedShort4444Type = 1016;
THREE.UnsignedShort5551Type = 1017;
THREE.UnsignedShort565Type = 1018;
// Pixel formats
THREE.AlphaFormat = 1019;
THREE.RGBFormat = 1020;
THREE.RGBAFormat = 1021;
THREE.LuminanceFormat = 1022;
THREE.LuminanceAlphaFormat = 1023;
// Compressed texture formats
THREE.RGB_S3TC_DXT1_Format = 2001;
THREE.RGBA_S3TC_DXT1_Format = 2002;
THREE.RGBA_S3TC_DXT3_Format = 2003;
THREE.RGBA_S3TC_DXT5_Format = 2004;
/*
// Potential future PVRTC compressed texture formats
THREE.RGB_PVRTC_4BPPV1_Format = 2100;
THREE.RGB_PVRTC_2BPPV1_Format = 2101;
THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
*/
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Clock = function ( autoStart ) {
this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
this.startTime = 0;
this.oldTime = 0;
this.elapsedTime = 0;
this.running = false;
};
THREE.Clock.prototype.start = function () {
this.startTime = Date.now();
this.oldTime = this.startTime;
this.running = true;
};
THREE.Clock.prototype.stop = function () {
this.getElapsedTime();
this.running = false;
};
THREE.Clock.prototype.getElapsedTime = function () {
this.elapsedTime += this.getDelta();
return this.elapsedTime;
};
THREE.Clock.prototype.getDelta = function () {
var diff = 0;
if ( this.autoStart && ! this.running ) {
this.start();
}
if ( this.running ) {
var newTime = Date.now();
diff = 0.001 * ( newTime - this.oldTime );
this.oldTime = newTime;
this.elapsedTime += diff;
}
return diff;
};/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Color = function ( hex ) {
if ( hex !== undefined ) this.setHex( hex );
return this;
};
THREE.Color.prototype = {
constructor: THREE.Color,
r: 1, g: 1, b: 1,
copy: function ( color ) {
this.r = color.r;
this.g = color.g;
this.b = color.b;
return this;
},
copyGammaToLinear: function ( color ) {
this.r = color.r * color.r;
this.g = color.g * color.g;
this.b = color.b * color.b;
return this;
},
copyLinearToGamma: function ( color ) {
this.r = Math.sqrt( color.r );
this.g = Math.sqrt( color.g );
this.b = Math.sqrt( color.b );
return this;
},
convertGammaToLinear: function () {
var r = this.r, g = this.g, b = this.b;
this.r = r * r;
this.g = g * g;
this.b = b * b;
return this;
},
convertLinearToGamma: function () {
this.r = Math.sqrt( this.r );
this.g = Math.sqrt( this.g );
this.b = Math.sqrt( this.b );
return this;
},
setRGB: function ( r, g, b ) {
this.r = r;
this.g = g;
this.b = b;
return this;
},
setHSV: function ( h, s, v ) {
// based on MochiKit implementation by Bob Ippolito
// h,s,v ranges are < 0.0 - 1.0 >
var i, f, p, q, t;
if ( v === 0 ) {
this.r = this.g = this.b = 0;
} else {
i = Math.floor( h * 6 );
f = ( h * 6 ) - i;
p = v * ( 1 - s );
q = v * ( 1 - ( s * f ) );
t = v * ( 1 - ( s * ( 1 - f ) ) );
if ( i === 0 ) {
this.r = v;
this.g = t;
this.b = p;
} else if ( i === 1 ) {
this.r = q;
this.g = v;
this.b = p;
} else if ( i === 2 ) {
this.r = p;
this.g = v;
this.b = t;
} else if ( i === 3 ) {
this.r = p;
this.g = q;
this.b = v;
} else if ( i === 4 ) {
this.r = t;
this.g = p;
this.b = v;
} else if ( i === 5 ) {
this.r = v;
this.g = p;
this.b = q;
}
}
return this;
},
setHex: function ( hex ) {
hex = Math.floor( hex );
this.r = ( hex >> 16 & 255 ) / 255;
this.g = ( hex >> 8 & 255 ) / 255;
this.b = ( hex & 255 ) / 255;
return this;
},
lerpSelf: function ( color, alpha ) {
this.r += ( color.r - this.r ) * alpha;
this.g += ( color.g - this.g ) * alpha;
this.b += ( color.b - this.b ) * alpha;
return this;
},
getHex: function () {
return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
},
getContextStyle: function () {
return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
},
clone: function () {
return new THREE.Color().setRGB( this.r, this.g, this.b );
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author philogb / http://blog.thejit.org/
* @author egraether / http://egraether.com/
* @author zz85 / http://www.lab4games.net/zz85/blog
*/
THREE.Vector2 = function ( x, y ) {
this.x = x || 0;
this.y = y || 0;
};
THREE.Vector2.prototype = {
constructor: THREE.Vector2,
set: function ( x, y ) {
this.x = x;
this.y = y;
return this;
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
return this;
},
add: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
return this;
},
addSelf: function ( v ) {
this.x += v.x;
this.y += v.y;
return this;
},
sub: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
return this;
},
subSelf: function ( v ) {
this.x -= v.x;
this.y -= v.y;
return this;
},
multiplyScalar: function ( s ) {
this.x *= s;
this.y *= s;
return this;
},
divideScalar: function ( s ) {
if ( s ) {
this.x /= s;
this.y /= s;
} else {
this.set( 0, 0 );
}
return this;
},
negate: function() {
return this.multiplyScalar( - 1 );
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y;
},
length: function () {
return Math.sqrt( this.lengthSq() );
},
normalize: function () {
return this.divideScalar( this.length() );
},
distanceTo: function ( v ) {
return Math.sqrt( this.distanceToSquared( v ) );
},
distanceToSquared: function ( v ) {
var dx = this.x - v.x, dy = this.y - v.y;
return dx * dx + dy * dy;
},
setLength: function ( l ) {
return this.normalize().multiplyScalar( l );
},
lerpSelf: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
return this;
},
equals: function( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) );
},
isZero: function ( v ) {
return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
},
clone: function () {
return new THREE.Vector2( this.x, this.y );
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author kile / http://kile.stravaganza.org/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Vector3 = function ( x, y, z ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
};
THREE.Vector3.prototype = {
constructor: THREE.Vector3,
set: function ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setZ: function ( z ) {
this.z = z;
return this;
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
},
add: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
return this;
},
addSelf: function ( v ) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
},
addScalar: function ( s ) {
this.x += s;
this.y += s;
this.z += s;
return this;
},
sub: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
return this;
},
subSelf: function ( v ) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
},
multiply: function ( a, b ) {
this.x = a.x * b.x;
this.y = a.y * b.y;
this.z = a.z * b.z;
return this;
},
multiplySelf: function ( v ) {
this.x *= v.x;
this.y *= v.y;
this.z *= v.z;
return this;
},
multiplyScalar: function ( s ) {
this.x *= s;
this.y *= s;
this.z *= s;
return this;
},
divideSelf: function ( v ) {
this.x /= v.x;
this.y /= v.y;
this.z /= v.z;
return this;
},
divideScalar: function ( s ) {
if ( s ) {
this.x /= s;
this.y /= s;
this.z /= s;
} else {
this.x = 0;
this.y = 0;
this.z = 0;
}
return this;
},
negate: function() {
return this.multiplyScalar( - 1 );
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y + this.z * this.z;
},
length: function () {
return Math.sqrt( this.lengthSq() );
},
lengthManhattan: function () {
return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
},
normalize: function () {
return this.divideScalar( this.length() );
},
setLength: function ( l ) {
return this.normalize().multiplyScalar( l );
},
lerpSelf: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
return this;
},
cross: function ( a, b ) {
this.x = a.y * b.z - a.z * b.y;
this.y = a.z * b.x - a.x * b.z;
this.z = a.x * b.y - a.y * b.x;
return this;
},
crossSelf: function ( v ) {
var x = this.x, y = this.y, z = this.z;
this.x = y * v.z - z * v.y;
this.y = z * v.x - x * v.z;
this.z = x * v.y - y * v.x;
return this;
},
angleTo: function ( v ) {
return Math.acos( this.dot( v ) / this.length() / v.length() );
},
distanceTo: function ( v ) {
return Math.sqrt( this.distanceToSquared( v ) );
},
distanceToSquared: function ( v ) {
return new THREE.Vector3().sub( this, v ).lengthSq();
},
getPositionFromMatrix: function ( m ) {
this.x = m.elements[12];
this.y = m.elements[13];
this.z = m.elements[14];
return this;
},
setEulerFromRotationMatrix: function ( m, order ) {
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
// clamp, to handle numerical problems
function clamp( x ) {
return Math.min( Math.max( x, -1 ), 1 );
}
var te = m.elements;
var m11 = te[0], m12 = te[4], m13 = te[8];
var m21 = te[1], m22 = te[5], m23 = te[9];
var m31 = te[2], m32 = te[6], m33 = te[10];
if ( order === undefined || order === 'XYZ' ) {
this.y = Math.asin( clamp( m13 ) );
if ( Math.abs( m13 ) < 0.99999 ) {
this.x = Math.atan2( - m23, m33 );
this.z = Math.atan2( - m12, m11 );
} else {
this.x = Math.atan2( m32, m22 );
this.z = 0;
}
} else if ( order === 'YXZ' ) {
this.x = Math.asin( - clamp( m23 ) );
if ( Math.abs( m23 ) < 0.99999 ) {
this.y = Math.atan2( m13, m33 );
this.z = Math.atan2( m21, m22 );
} else {
this.y = Math.atan2( - m31, m11 );
this.z = 0;
}
} else if ( order === 'ZXY' ) {
this.x = Math.asin( clamp( m32 ) );
if ( Math.abs( m32 ) < 0.99999 ) {
this.y = Math.atan2( - m31, m33 );
this.z = Math.atan2( - m12, m22 );
} else {
this.y = 0;
this.z = Math.atan2( m21, m11 );
}
} else if ( order === 'ZYX' ) {
this.y = Math.asin( - clamp( m31 ) );
if ( Math.abs( m31 ) < 0.99999 ) {
this.x = Math.atan2( m32, m33 );
this.z = Math.atan2( m21, m11 );
} else {
this.x = 0;
this.z = Math.atan2( - m12, m22 );
}
} else if ( order === 'YZX' ) {
this.z = Math.asin( clamp( m21 ) );
if ( Math.abs( m21 ) < 0.99999 ) {
this.x = Math.atan2( - m23, m22 );
this.y = Math.atan2( - m31, m11 );
} else {
this.x = 0;
this.y = Math.atan2( m13, m33 );
}
} else if ( order === 'XZY' ) {
this.z = Math.asin( - clamp( m12 ) );
if ( Math.abs( m12 ) < 0.99999 ) {
this.x = Math.atan2( m32, m22 );
this.y = Math.atan2( m13, m11 );
} else {
this.x = Math.atan2( - m23, m33 );
this.y = 0;
}
}
return this;
},
setEulerFromQuaternion: function ( q, order ) {
// q is assumed to be normalized
// clamp, to handle numerical problems
function clamp( x ) {
return Math.min( Math.max( x, -1 ), 1 );
}
// http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
var sqx = q.x * q.x;
var sqy = q.y * q.y;
var sqz = q.z * q.z;
var sqw = q.w * q.w;
if ( order === undefined || order === 'XYZ' ) {
this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
} else if ( order === 'YXZ' ) {
this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
} else if ( order === 'ZXY' ) {
this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
} else if ( order === 'ZYX' ) {
this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
} else if ( order === 'YZX' ) {
this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
} else if ( order === 'XZY' ) {
this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
}
return this;
},
getScaleFromMatrix: function ( m ) {
var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
this.x = sx;
this.y = sy;
this.z = sz;
return this;
},
equals: function ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
},
isZero: function ( v ) {
return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
},
clone: function () {
return new THREE.Vector3( this.x, this.y, this.z );
}
};
/**
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Vector4 = function ( x, y, z, w ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = ( w !== undefined ) ? w : 1;
};
THREE.Vector4.prototype = {
constructor: THREE.Vector4,
set: function ( x, y, z, w ) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
this.w = ( v.w !== undefined ) ? v.w : 1;
return this;
},
add: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
this.w = a.w + b.w;
return this;
},
addSelf: function ( v ) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
this.w += v.w;
return this;
},
sub: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
this.w = a.w - b.w;
return this;
},
subSelf: function ( v ) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
this.w -= v.w;
return this;
},
multiplyScalar: function ( s ) {
this.x *= s;
this.y *= s;
this.z *= s;
this.w *= s;
return this;
},
divideScalar: function ( s ) {
if ( s ) {
this.x /= s;
this.y /= s;
this.z /= s;
this.w /= s;
} else {
this.x = 0;
this.y = 0;
this.z = 0;
this.w = 1;
}
return this;
},
negate: function() {
return this.multiplyScalar( -1 );
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
},
lengthSq: function () {
return this.dot( this );
},
length: function () {
return Math.sqrt( this.lengthSq() );
},
lengthManhattan: function () {
return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
},
normalize: function () {
return this.divideScalar( this.length() );
},
setLength: function ( l ) {
return this.normalize().multiplyScalar( l );
},
lerpSelf: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
this.w += ( v.w - this.w ) * alpha;
return this;
},
clone: function () {
return new THREE.Vector4( this.x, this.y, this.z, this.w );
},
setAxisAngleFromQuaternion: function ( q ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
// q is assumed to be normalized
this.w = 2 * Math.acos( q.w );
var s = Math.sqrt( 1 - q.w * q.w );
if ( s < 0.0001 ) {
this.x = 1;
this.y = 0;
this.z = 0;
} else {
this.x = q.x / s;
this.y = q.y / s;
this.z = q.z / s;
}
return this;
},
setAxisAngleFromRotationMatrix: function ( m ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var angle, x, y, z, // variables for result
epsilon = 0.01, // margin to allow for rounding errors
epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
te = m.elements,
m11 = te[0], m12 = te[4], m13 = te[8],
m21 = te[1], m22 = te[5], m23 = te[9],
m31 = te[2], m32 = te[6], m33 = te[10];
if ( ( Math.abs( m12 - m21 ) < epsilon )
&& ( Math.abs( m13 - m31 ) < epsilon )
&& ( Math.abs( m23 - m32 ) < epsilon ) ) {
// singularity found
// first check for identity matrix which must have +1 for all terms
// in leading diagonal and zero in other terms
if ( ( Math.abs( m12 + m21 ) < epsilon2 )
&& ( Math.abs( m13 + m31 ) < epsilon2 )
&& ( Math.abs( m23 + m32 ) < epsilon2 )
&& ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
// this singularity is identity matrix so angle = 0
this.set( 1, 0, 0, 0 );
return this; // zero angle, arbitrary axis
}
// otherwise this singularity is angle = 180
angle = Math.PI;
var xx = ( m11 + 1 ) / 2;
var yy = ( m22 + 1 ) / 2;
var zz = ( m33 + 1 ) / 2;
var xy = ( m12 + m21 ) / 4;
var xz = ( m13 + m31 ) / 4;
var yz = ( m23 + m32 ) / 4;
if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
if ( xx < epsilon ) {
x = 0;
y = 0.707106781;
z = 0.707106781;
} else {
x = Math.sqrt( xx );
y = xy / x;
z = xz / x;
}
} else if ( yy > zz ) { // m22 is the largest diagonal term
if ( yy < epsilon ) {
x = 0.707106781;
y = 0;
z = 0.707106781;
} else {
y = Math.sqrt( yy );
x = xy / y;
z = yz / y;
}
} else { // m33 is the largest diagonal term so base result on this
if ( zz < epsilon ) {
x = 0.707106781;
y = 0.707106781;
z = 0;
} else {
z = Math.sqrt( zz );
x = xz / z;
y = yz / z;
}
}
this.set( x, y, z, angle );
return this; // return 180 deg rotation
}
// as we have reached here there are no singularities so we can handle normally
var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
+ ( m13 - m31 ) * ( m13 - m31 )
+ ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
if ( Math.abs( s ) < 0.001 ) s = 1;
// prevent divide by zero, should not happen if matrix is orthogonal and should be
// caught by singularity test above, but I've left it in just in case
this.x = ( m32 - m23 ) / s;
this.y = ( m13 - m31 ) / s;
this.z = ( m21 - m12 ) / s;
this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
return this;
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Matrix3 = function () {
this.elements = new Float32Array(9);
};
THREE.Matrix3.prototype = {
constructor: THREE.Matrix3,
getInverse: function ( matrix ) {
// input: THREE.Matrix4
// ( based on http://code.google.com/p/webgl-mjs/ )
var me = matrix.elements;
var a11 = me[10] * me[5] - me[6] * me[9];
var a21 = - me[10] * me[1] + me[2] * me[9];
var a31 = me[6] * me[1] - me[2] * me[5];
var a12 = - me[10] * me[4] + me[6] * me[8];
var a22 = me[10] * me[0] - me[2] * me[8];
var a32 = - me[6] * me[0] + me[2] * me[4];
var a13 = me[9] * me[4] - me[5] * me[8];
var a23 = - me[9] * me[0] + me[1] * me[8];
var a33 = me[5] * me[0] - me[1] * me[4];
var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
// no inverse
if ( det === 0 ) {
console.warn( "Matrix3.getInverse(): determinant == 0" );
}
var idet = 1.0 / det;
var m = this.elements;
m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
return this;
},
transpose: function () {
var tmp, m = this.elements;
tmp = m[1]; m[1] = m[3]; m[3] = tmp;
tmp = m[2]; m[2] = m[6]; m[6] = tmp;
tmp = m[5]; m[5] = m[7]; m[7] = tmp;
return this;
},
transposeIntoArray: function ( r ) {
var m = this.m;
r[ 0 ] = m[ 0 ];
r[ 1 ] = m[ 3 ];
r[ 2 ] = m[ 6 ];
r[ 3 ] = m[ 1 ];
r[ 4 ] = m[ 4 ];
r[ 5 ] = m[ 7 ];
r[ 6 ] = m[ 2 ];
r[ 7 ] = m[ 5 ];
r[ 8 ] = m[ 8 ];
return this;
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author philogb / http://blog.thejit.org/
* @author jordi_ros / http://plattsoft.com
* @author D1plo1d / http://github.com/D1plo1d
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author timknip / http://www.floorplanner.com/
*/
THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
this.elements = new Float32Array( 16 );
this.set(
( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
);
};
THREE.Matrix4.prototype = {
constructor: THREE.Matrix4,
set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
var te = this.elements;
te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
return this;
},
identity: function () {
this.set(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
return this;
},
copy: function ( m ) {
var me = m.elements;
this.set(
me[0], me[4], me[8], me[12],
me[1], me[5], me[9], me[13],
me[2], me[6], me[10], me[14],
me[3], me[7], me[11], me[15]
);
return this;
},
lookAt: function ( eye, target, up ) {
var te = this.elements;
var x = THREE.Matrix4.__v1;
var y = THREE.Matrix4.__v2;
var z = THREE.Matrix4.__v3;
z.sub( eye, target ).normalize();
if ( z.length() === 0 ) {
z.z = 1;
}
x.cross( up, z ).normalize();
if ( x.length() === 0 ) {
z.x += 0.0001;
x.cross( up, z ).normalize();
}
y.cross( z, x );
te[0] = x.x; te[4] = y.x; te[8] = z.x;
te[1] = x.y; te[5] = y.y; te[9] = z.y;
te[2] = x.z; te[6] = y.z; te[10] = z.z;
return this;
},
multiply: function ( a, b ) {
var ae = a.elements;
var be = b.elements;
var te = this.elements;
var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
return this;
},
multiplySelf: function ( m ) {
return this.multiply( this, m );
},
multiplyToArray: function ( a, b, r ) {
var te = this.elements;
this.multiply( a, b );
r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
return this;
},
multiplyScalar: function ( s ) {
var te = this.elements;
te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
return this;
},
multiplyVector3: function ( v ) {
var te = this.elements;
var vx = v.x, vy = v.y, vz = v.z;
var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
return v;
},
multiplyVector4: function ( v ) {
var te = this.elements;
var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
return v;
},
multiplyVector3Array: function ( a ) {
var tmp = THREE.Matrix4.__v1;
for ( var i = 0, il = a.length; i < il; i += 3 ) {
tmp.x = a[ i ];
tmp.y = a[ i + 1 ];
tmp.z = a[ i + 2 ];
this.multiplyVector3( tmp );
a[ i ] = tmp.x;
a[ i + 1 ] = tmp.y;
a[ i + 2 ] = tmp.z;
}
return a;
},
rotateAxis: function ( v ) {
var te = this.elements;
var vx = v.x, vy = v.y, vz = v.z;
v.x = vx * te[0] + vy * te[4] + vz * te[8];
v.y = vx * te[1] + vy * te[5] + vz * te[9];
v.z = vx * te[2] + vy * te[6] + vz * te[10];
v.normalize();
return v;
},
crossVector: function ( a ) {
var te = this.elements;
var v = new THREE.Vector4();
v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
return v;
},
determinant: function () {
var te = this.elements;
var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
//TODO: make this more efficient
//( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
return (
n14 * n23 * n32 * n41-
n13 * n24 * n32 * n41-
n14 * n22 * n33 * n41+
n12 * n24 * n33 * n41+
n13 * n22 * n34 * n41-
n12 * n23 * n34 * n41-
n14 * n23 * n31 * n42+
n13 * n24 * n31 * n42+
n14 * n21 * n33 * n42-
n11 * n24 * n33 * n42-
n13 * n21 * n34 * n42+
n11 * n23 * n34 * n42+
n14 * n22 * n31 * n43-
n12 * n24 * n31 * n43-
n14 * n21 * n32 * n43+
n11 * n24 * n32 * n43+
n12 * n21 * n34 * n43-
n11 * n22 * n34 * n43-
n13 * n22 * n31 * n44+
n12 * n23 * n31 * n44+
n13 * n21 * n32 * n44-
n11 * n23 * n32 * n44-
n12 * n21 * n33 * n44+
n11 * n22 * n33 * n44
);
},
transpose: function () {
var te = this.elements;
var tmp;
tmp = te[1]; te[1] = te[4]; te[4] = tmp;
tmp = te[2]; te[2] = te[8]; te[8] = tmp;
tmp = te[6]; te[6] = te[9]; te[9] = tmp;
tmp = te[3]; te[3] = te[12]; te[12] = tmp;
tmp = te[7]; te[7] = te[13]; te[13] = tmp;
tmp = te[11]; te[11] = te[14]; te[14] = tmp;
return this;
},
flattenToArray: function ( flat ) {
var te = this.elements;
flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
return flat;
},
flattenToArrayOffset: function( flat, offset ) {
var te = this.elements;
flat[ offset ] = te[0];
flat[ offset + 1 ] = te[1];
flat[ offset + 2 ] = te[2];
flat[ offset + 3 ] = te[3];
flat[ offset + 4 ] = te[4];
flat[ offset + 5 ] = te[5];
flat[ offset + 6 ] = te[6];
flat[ offset + 7 ] = te[7];
flat[ offset + 8 ] = te[8];
flat[ offset + 9 ] = te[9];
flat[ offset + 10 ] = te[10];
flat[ offset + 11 ] = te[11];
flat[ offset + 12 ] = te[12];
flat[ offset + 13 ] = te[13];
flat[ offset + 14 ] = te[14];
flat[ offset + 15 ] = te[15];
return flat;
},
getPosition: function () {
var te = this.elements;
return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
},
setPosition: function ( v ) {
var te = this.elements;
te[12] = v.x;
te[13] = v.y;
te[14] = v.z;
return this;
},
getColumnX: function () {
var te = this.elements;
return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
},
getColumnY: function () {
var te = this.elements;
return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
},
getColumnZ: function() {
var te = this.elements;
return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
},
getInverse: function ( m ) {
// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
var te = this.elements;
var me = m.elements;
var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
this.multiplyScalar( 1 / m.determinant() );
return this;
},
setRotationFromEuler: function ( v, order ) {
var te = this.elements;
var x = v.x, y = v.y, z = v.z;
var a = Math.cos( x ), b = Math.sin( x );
var c = Math.cos( y ), d = Math.sin( y );
var e = Math.cos( z ), f = Math.sin( z );
if ( order === undefined || order === 'XYZ' ) {
var ae = a * e, af = a * f, be = b * e, bf = b * f;
te[0] = c * e;
te[4] = - c * f;
te[8] = d;
te[1] = af + be * d;
te[5] = ae - bf * d;
te[9] = - b * c;
te[2] = bf - ae * d;
te[6] = be + af * d;
te[10] = a * c;
} else if ( order === 'YXZ' ) {
var ce = c * e, cf = c * f, de = d * e, df = d * f;
te[0] = ce + df * b;
te[4] = de * b - cf;
te[8] = a * d;
te[1] = a * f;
te[5] = a * e;
te[9] = - b;
te[2] = cf * b - de;
te[6] = df + ce * b;
te[10] = a * c;
} else if ( order === 'ZXY' ) {
var ce = c * e, cf = c * f, de = d * e, df = d * f;
te[0] = ce - df * b;
te[4] = - a * f;
te[8] = de + cf * b;
te[1] = cf + de * b;
te[5] = a * e;
te[9] = df - ce * b;
te[2] = - a * d;
te[6] = b;
te[10] = a * c;
} else if ( order === 'ZYX' ) {
var ae = a * e, af = a * f, be = b * e, bf = b * f;
te[0] = c * e;
te[4] = be * d - af;
te[8] = ae * d + bf;
te[1] = c * f;
te[5] = bf * d + ae;
te[9] = af * d - be;
te[2] = - d;
te[6] = b * c;
te[10] = a * c;
} else if ( order === 'YZX' ) {
var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
te[0] = c * e;
te[4] = bd - ac * f;
te[8] = bc * f + ad;
te[1] = f;
te[5] = a * e;
te[9] = - b * e;
te[2] = - d * e;
te[6] = ad * f + bc;
te[10] = ac - bd * f;
} else if ( order === 'XZY' ) {
var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
te[0] = c * e;
te[4] = - f;
te[8] = d * e;
te[1] = ac * f + bd;
te[5] = a * e;
te[9] = ad * f - bc;
te[2] = bc * f - ad;
te[6] = b * e;
te[10] = bd * f + ac;
}
return this;
},
setRotationFromQuaternion: function ( q ) {
var te = this.elements;
var x = q.x, y = q.y, z = q.z, w = q.w;
var x2 = x + x, y2 = y + y, z2 = z + z;
var xx = x * x2, xy = x * y2, xz = x * z2;
var yy = y * y2, yz = y * z2, zz = z * z2;
var wx = w * x2, wy = w * y2, wz = w * z2;
te[0] = 1 - ( yy + zz );
te[4] = xy - wz;
te[8] = xz + wy;
te[1] = xy + wz;
te[5] = 1 - ( xx + zz );
te[9] = yz - wx;
te[2] = xz - wy;
te[6] = yz + wx;
te[10] = 1 - ( xx + yy );
return this;
},
compose: function ( translation, rotation, scale ) {
var te = this.elements;
var mRotation = THREE.Matrix4.__m1;
var mScale = THREE.Matrix4.__m2;
mRotation.identity();
mRotation.setRotationFromQuaternion( rotation );
mScale.makeScale( scale.x, scale.y, scale.z );
this.multiply( mRotation, mScale );
te[12] = translation.x;
te[13] = translation.y;
te[14] = translation.z;
return this;
},
decompose: function ( translation, rotation, scale ) {
var te = this.elements;
// grab the axis vectors
var x = THREE.Matrix4.__v1;
var y = THREE.Matrix4.__v2;
var z = THREE.Matrix4.__v3;
x.set( te[0], te[1], te[2] );
y.set( te[4], te[5], te[6] );
z.set( te[8], te[9], te[10] );
translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
scale.x = x.length();
scale.y = y.length();
scale.z = z.length();
translation.x = te[12];
translation.y = te[13];
translation.z = te[14];
// scale the rotation part
var matrix = THREE.Matrix4.__m1;
matrix.copy( this );
matrix.elements[0] /= scale.x;
matrix.elements[1] /= scale.x;
matrix.elements[2] /= scale.x;
matrix.elements[4] /= scale.y;
matrix.elements[5] /= scale.y;
matrix.elements[6] /= scale.y;
matrix.elements[8] /= scale.z;
matrix.elements[9] /= scale.z;
matrix.elements[10] /= scale.z;
rotation.setFromRotationMatrix( matrix );
return [ translation, rotation, scale ];
},
extractPosition: function ( m ) {
var te = this.elements;
var me = m.elements;
te[12] = me[12];
te[13] = me[13];
te[14] = me[14];
return this;
},
extractRotation: function ( m ) {
var te = this.elements;
var me = m.elements;
var vector = THREE.Matrix4.__v1;
var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
te[0] = me[0] * scaleX;
te[1] = me[1] * scaleX;
te[2] = me[2] * scaleX;
te[4] = me[4] * scaleY;
te[5] = me[5] * scaleY;
te[6] = me[6] * scaleY;
te[8] = me[8] * scaleZ;
te[9] = me[9] * scaleZ;
te[10] = me[10] * scaleZ;
return this;
},
//
translate: function ( v ) {
var te = this.elements;
var x = v.x, y = v.y, z = v.z;
te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
return this;
},
rotateX: function ( angle ) {
var te = this.elements;
var m12 = te[4];
var m22 = te[5];
var m32 = te[6];
var m42 = te[7];
var m13 = te[8];
var m23 = te[9];
var m33 = te[10];
var m43 = te[11];
var c = Math.cos( angle );
var s = Math.sin( angle );
te[4] = c * m12 + s * m13;
te[5] = c * m22 + s * m23;
te[6] = c * m32 + s * m33;
te[7] = c * m42 + s * m43;
te[8] = c * m13 - s * m12;
te[9] = c * m23 - s * m22;
te[10] = c * m33 - s * m32;
te[11] = c * m43 - s * m42;
return this;
},
rotateY: function ( angle ) {
var te = this.elements;
var m11 = te[0];
var m21 = te[1];
var m31 = te[2];
var m41 = te[3];
var m13 = te[8];
var m23 = te[9];
var m33 = te[10];
var m43 = te[11];
var c = Math.cos( angle );
var s = Math.sin( angle );
te[0] = c * m11 - s * m13;
te[1] = c * m21 - s * m23;
te[2] = c * m31 - s * m33;
te[3] = c * m41 - s * m43;
te[8] = c * m13 + s * m11;
te[9] = c * m23 + s * m21;
te[10] = c * m33 + s * m31;
te[11] = c * m43 + s * m41;
return this;
},
rotateZ: function ( angle ) {
var te = this.elements;
var m11 = te[0];
var m21 = te[1];
var m31 = te[2];
var m41 = te[3];
var m12 = te[4];
var m22 = te[5];
var m32 = te[6];
var m42 = te[7];
var c = Math.cos( angle );
var s = Math.sin( angle );
te[0] = c * m11 + s * m12;
te[1] = c * m21 + s * m22;
te[2] = c * m31 + s * m32;
te[3] = c * m41 + s * m42;
te[4] = c * m12 - s * m11;
te[5] = c * m22 - s * m21;
te[6] = c * m32 - s * m31;
te[7] = c * m42 - s * m41;
return this;
},
rotateByAxis: function ( axis, angle ) {
var te = this.elements;
// optimize by checking axis
if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
return this.rotateX( angle );
} else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
return this.rotateY( angle );
} else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
return this.rotateZ( angle );
}
var x = axis.x, y = axis.y, z = axis.z;
var n = Math.sqrt(x * x + y * y + z * z);
x /= n;
y /= n;
z /= n;
var xx = x * x, yy = y * y, zz = z * z;
var c = Math.cos( angle );
var s = Math.sin( angle );
var oneMinusCosine = 1 - c;
var xy = x * y * oneMinusCosine;
var xz = x * z * oneMinusCosine;
var yz = y * z * oneMinusCosine;
var xs = x * s;
var ys = y * s;
var zs = z * s;
var r11 = xx + (1 - xx) * c;
var r21 = xy + zs;
var r31 = xz - ys;
var r12 = xy - zs;
var r22 = yy + (1 - yy) * c;
var r32 = yz + xs;
var r13 = xz + ys;
var r23 = yz - xs;
var r33 = zz + (1 - zz) * c;
var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
te[0] = r11 * m11 + r21 * m12 + r31 * m13;
te[1] = r11 * m21 + r21 * m22 + r31 * m23;
te[2] = r11 * m31 + r21 * m32 + r31 * m33;
te[3] = r11 * m41 + r21 * m42 + r31 * m43;
te[4] = r12 * m11 + r22 * m12 + r32 * m13;
te[5] = r12 * m21 + r22 * m22 + r32 * m23;
te[6] = r12 * m31 + r22 * m32 + r32 * m33;
te[7] = r12 * m41 + r22 * m42 + r32 * m43;
te[8] = r13 * m11 + r23 * m12 + r33 * m13;
te[9] = r13 * m21 + r23 * m22 + r33 * m23;
te[10] = r13 * m31 + r23 * m32 + r33 * m33;
te[11] = r13 * m41 + r23 * m42 + r33 * m43;
return this;
},
scale: function ( v ) {
var te = this.elements;
var x = v.x, y = v.y, z = v.z;
te[0] *= x; te[4] *= y; te[8] *= z;
te[1] *= x; te[5] *= y; te[9] *= z;
te[2] *= x; te[6] *= y; te[10] *= z;
te[3] *= x; te[7] *= y; te[11] *= z;
return this;
},
getMaxScaleOnAxis: function () {
var te = this.elements;
var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
},
//
makeTranslation: function ( x, y, z ) {
this.set(
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1
);
return this;
},
makeRotationX: function ( theta ) {
var c = Math.cos( theta ), s = Math.sin( theta );
this.set(
1, 0, 0, 0,
0, c, -s, 0,
0, s, c, 0,
0, 0, 0, 1
);
return this;
},
makeRotationY: function ( theta ) {
var c = Math.cos( theta ), s = Math.sin( theta );
this.set(
c, 0, s, 0,
0, 1, 0, 0,
-s, 0, c, 0,
0, 0, 0, 1
);
return this;
},
makeRotationZ: function ( theta ) {
var c = Math.cos( theta ), s = Math.sin( theta );
this.set(
c, -s, 0, 0,
s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
return this;
},
makeRotationAxis: function ( axis, angle ) {
// Based on http://www.gamedev.net/reference/articles/article1199.asp
var c = Math.cos( angle );
var s = Math.sin( angle );
var t = 1 - c;
var x = axis.x, y = axis.y, z = axis.z;
var tx = t * x, ty = t * y;
this.set(
tx * x + c, tx * y - s * z, tx * z + s * y, 0,
tx * y + s * z, ty * y + c, ty * z - s * x, 0,
tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
0, 0, 0, 1
);
return this;
},
makeScale: function ( x, y, z ) {
this.set(
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
0, 0, 0, 1
);
return this;
},
makeFrustum: function ( left, right, bottom, top, near, far ) {
var te = this.elements;
var x = 2 * near / ( right - left );
var y = 2 * near / ( top - bottom );
var a = ( right + left ) / ( right - left );
var b = ( top + bottom ) / ( top - bottom );
var c = - ( far + near ) / ( far - near );
var d = - 2 * far * near / ( far - near );
te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
return this;
},
makePerspective: function ( fov, aspect, near, far ) {
var ymax = near * Math.tan( fov * Math.PI / 360 );
var ymin = - ymax;
var xmin = ymin * aspect;
var xmax = ymax * aspect;
return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
},
makeOrthographic: function ( left, right, top, bottom, near, far ) {
var te = this.elements;
var w = right - left;
var h = top - bottom;
var p = far - near;
var x = ( right + left ) / w;
var y = ( top + bottom ) / h;
var z = ( far + near ) / p;
te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
return this;
},
clone: function () {
var te = this.elements;
return new THREE.Matrix4(
te[0], te[4], te[8], te[12],
te[1], te[5], te[9], te[13],
te[2], te[6], te[10], te[14],
te[3], te[7], te[11], te[15]
);
}
};
THREE.Matrix4.__v1 = new THREE.Vector3();
THREE.Matrix4.__v2 = new THREE.Vector3();
THREE.Matrix4.__v3 = new THREE.Vector3();
THREE.Matrix4.__m1 = new THREE.Matrix4();
THREE.Matrix4.__m2 = new THREE.Matrix4();
/**
* https://github.com/mrdoob/eventtarget.js/
*/
THREE.EventTarget = function () {
var listeners = {};
this.addEventListener = function ( type, listener ) {
if ( listeners[ type ] === undefined ) {
listeners[ type ] = [];
}
if ( listeners[ type ].indexOf( listener ) === - 1 ) {
listeners[ type ].push( listener );
}
};
this.dispatchEvent = function ( event ) {
for ( var listener in listeners[ event.type ] ) {
listeners[ event.type ][ listener ]( event );
}
};
this.removeEventListener = function ( type, listener ) {
var index = listeners[ type ].indexOf( listener );
if ( index !== - 1 ) {
listeners[ type ].splice( index, 1 );
}
};
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Frustum = function ( ) {
this.planes = [
new THREE.Vector4(),
new THREE.Vector4(),
new THREE.Vector4(),
new THREE.Vector4(),
new THREE.Vector4(),
new THREE.Vector4()
];
};
THREE.Frustum.prototype.setFromMatrix = function ( m ) {
var plane;
var planes = this.planes;
var me = m.elements;
var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
for ( var i = 0; i < 6; i ++ ) {
plane = planes[ i ];
plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
}
};
THREE.Frustum.prototype.contains = function ( object ) {
var distance = 0.0;
var planes = this.planes;
var matrix = object.matrixWorld;
var me = matrix.elements;
var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
for ( var i = 0; i < 6; i ++ ) {
distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
if ( distance <= radius ) return false;
}
return true;
};
THREE.Frustum.__v1 = new THREE.Vector3();
/**
* @author mrdoob / http://mrdoob.com/
*/
( function ( THREE ) {
THREE.Ray = function ( origin, direction, near, far ) {
this.origin = origin || new THREE.Vector3();
this.direction = direction || new THREE.Vector3();
this.near = near || 0;
this.far = far || Infinity;
};
var originCopy = new THREE.Vector3();
var localOriginCopy = new THREE.Vector3();
var localDirectionCopy = new THREE.Vector3();
var vector = new THREE.Vector3();
var normal = new THREE.Vector3();
var intersectPoint = new THREE.Vector3();
var inverseMatrix = new THREE.Matrix4();
var descSort = function ( a, b ) {
return a.distance - b.distance;
};
var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
var distanceFromIntersection = function ( origin, direction, position ) {
v0.sub( position, origin );
var dot = v0.dot( direction );
var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
var distance = position.distanceTo( intersect );
return distance;
};
// http://www.blackpawn.com/texts/pointinpoly/default.html
var pointInFace3 = function ( p, a, b, c ) {
v0.sub( c, a );
v1.sub( b, a );
v2.sub( p, a );
var dot00 = v0.dot( v0 );
var dot01 = v0.dot( v1 );
var dot02 = v0.dot( v2 );
var dot11 = v1.dot( v1 );
var dot12 = v1.dot( v2 );
var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
};
var intersectObject = function ( object, ray, intersects ) {
var distance,intersect;
if ( object instanceof THREE.Particle ) {
distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
if ( distance > object.scale.x ) {
return intersects;
}
intersect = {
distance: distance,
point: object.position,
face: null,
object: object
};
intersects.push( intersect );
} else if ( object instanceof THREE.Mesh ) {
// Checking boundingSphere
var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
// Checking distance to ray
distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
if ( distance > scaledRadius) {
return intersects;
}
// Checking faces
var f, fl, face, dot, scalar,
geometry = object.geometry,
vertices = geometry.vertices,
objMatrix, geometryMaterials,
isFaceMaterial, material, side, point;
geometryMaterials = object.geometry.materials;
isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
side = object.material.side;
var a, b, c, d;
var precision = ray.precision;
object.matrixRotationWorld.extractRotation( object.matrixWorld );
originCopy.copy( ray.origin );
objMatrix = object.matrixWorld;
inverseMatrix.getInverse( objMatrix );
localOriginCopy.copy( originCopy );
inverseMatrix.multiplyVector3( localOriginCopy );
localDirectionCopy.copy( ray.direction );
inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
face = geometry.faces[ f ];
material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
if ( material === undefined ) continue;
side = material.side;
vector.sub( face.centroid, localOriginCopy );
normal = face.normal;
dot = localDirectionCopy.dot( normal );
// bail if ray and plane are parallel
if ( Math.abs( dot ) < precision ) continue;
// calc distance to plane
scalar = normal.dot( vector ) / dot;
// if negative distance, then plane is behind ray
if ( scalar < 0 ) continue;
if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
if ( face instanceof THREE.Face3 ) {
a = vertices[ face.a ];
b = vertices[ face.b ];
c = vertices[ face.c ];
if ( pointInFace3( intersectPoint, a, b, c ) ) {
point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
distance = originCopy.distanceTo( point );
if ( distance < ray.near || distance > ray.far ) continue;
intersect = {
distance: distance,
point: point,
face: face,
faceIndex: f,
object: object
};
intersects.push( intersect );
}
} else if ( face instanceof THREE.Face4 ) {
a = vertices[ face.a ];
b = vertices[ face.b ];
c = vertices[ face.c ];
d = vertices[ face.d ];
if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
distance = originCopy.distanceTo( point );
if ( distance < ray.near || distance > ray.far ) continue;
intersect = {
distance: distance,
point: point,
face: face,
faceIndex: f,
object: object
};
intersects.push( intersect );
}
}
}
}
}
};
var intersectDescendants = function ( object, ray, intersects ) {
var descendants = object.getDescendants();
for ( var i = 0, l = descendants.length; i < l; i ++ ) {
intersectObject( descendants[ i ], ray, intersects );
}
};
//
THREE.Ray.prototype.precision = 0.0001;
THREE.Ray.prototype.set = function ( origin, direction ) {
this.origin = origin;
this.direction = direction;
};
THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
var intersects = [];
if ( recursive === true ) {
intersectDescendants( object, this, intersects );
}
intersectObject( object, this, intersects );
intersects.sort( descSort );
return intersects;
};
THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
var intersects = [];
for ( var i = 0, l = objects.length; i < l; i ++ ) {
intersectObject( objects[ i ], this, intersects );
if ( recursive === true ) {
intersectDescendants( objects[ i ], this, intersects );
}
}
intersects.sort( descSort );
return intersects;
};
}( THREE ) );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Rectangle = function () {
var _left = 0;
var _top = 0;
var _right = 0;
var _bottom = 0;
var _width = 0;
var _height = 0;
var _isEmpty = true;
function resize() {
_width = _right - _left;
_height = _bottom - _top;
}
this.getX = function () {
return _left;
};
this.getY = function () {
return _top;
};
this.getWidth = function () {
return _width;
};
this.getHeight = function () {
return _height;
};
this.getLeft = function() {
return _left;
};
this.getTop = function() {
return _top;
};
this.getRight = function() {
return _right;
};
this.getBottom = function() {
return _bottom;
};
this.set = function ( left, top, right, bottom ) {
_isEmpty = false;
_left = left; _top = top;
_right = right; _bottom = bottom;
resize();
};
this.addPoint = function ( x, y ) {
if ( _isEmpty === true ) {
_isEmpty = false;
_left = x; _top = y;
_right = x; _bottom = y;
resize();
} else {
_left = _left < x ? _left : x; // Math.min( _left, x );
_top = _top < y ? _top : y; // Math.min( _top, y );
_right = _right > x ? _right : x; // Math.max( _right, x );
_bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
resize();
}
};
this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
if ( _isEmpty === true ) {
_isEmpty = false;
_left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
_top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
_right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
_bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
resize();
} else {
_left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
_top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
_right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
_bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
resize();
};
};
this.addRectangle = function ( r ) {
if ( _isEmpty === true ) {
_isEmpty = false;
_left = r.getLeft(); _top = r.getTop();
_right = r.getRight(); _bottom = r.getBottom();
resize();
} else {
_left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
_top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
_right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
_bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
resize();
}
};
this.inflate = function ( v ) {
_left -= v; _top -= v;
_right += v; _bottom += v;
resize();
};
this.minSelf = function ( r ) {
_left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
_top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
_right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
_bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
resize();
};
this.intersects = function ( r ) {
// http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
if ( _right < r.getLeft() ) return false;
if ( _left > r.getRight() ) return false;
if ( _bottom < r.getTop() ) return false;
if ( _top > r.getBottom() ) return false;
return true;
};
this.empty = function () {
_isEmpty = true;
_left = 0; _top = 0;
_right = 0; _bottom = 0;
resize();
};
this.isEmpty = function () {
return _isEmpty;
};
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Math = {
// Clamp value to range <a, b>
clamp: function ( x, a, b ) {
return ( x < a ) ? a : ( ( x > b ) ? b : x );
},
// Clamp value to range <a, inf)
clampBottom: function ( x, a ) {
return x < a ? a : x;
},
// Linear mapping from range <a1, a2> to range <b1, b2>
mapLinear: function ( x, a1, a2, b1, b2 ) {
return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
},
// Random float from <0, 1> with 16 bits of randomness
// (standard Math.random() creates repetitive patterns when applied over larger space)
random16: function () {
return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
},
// Random integer from <low, high> interval
randInt: function ( low, high ) {
return low + Math.floor( Math.random() * ( high - low + 1 ) );
},
// Random float from <low, high> interval
randFloat: function ( low, high ) {
return low + Math.random() * ( high - low );
},
// Random float from <-range/2, range/2> interval
randFloatSpread: function ( range ) {
return range * ( 0.5 - Math.random() );
},
sign: function ( x ) {
return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Object3D = function () {
THREE.Object3DLibrary.push( this );
this.id = THREE.Object3DIdCount ++;
this.name = '';
this.properties = {};
this.parent = undefined;
this.children = [];
this.up = new THREE.Vector3( 0, 1, 0 );
this.position = new THREE.Vector3();
this.rotation = new THREE.Vector3();
this.eulerOrder = THREE.Object3D.defaultEulerOrder;
this.scale = new THREE.Vector3( 1, 1, 1 );
this.renderDepth = null;
this.rotationAutoUpdate = true;
this.matrix = new THREE.Matrix4();
this.matrixWorld = new THREE.Matrix4();
this.matrixRotationWorld = new THREE.Matrix4();
this.matrixAutoUpdate = true;
this.matrixWorldNeedsUpdate = true;
this.quaternion = new THREE.Quaternion();
this.useQuaternion = false;
this.boundRadius = 0.0;
this.boundRadiusScale = 1.0;
this.visible = true;
this.castShadow = false;
this.receiveShadow = false;
this.frustumCulled = true;
this._vector = new THREE.Vector3();
};
THREE.Object3D.prototype = {
constructor: THREE.Object3D,
applyMatrix: function ( matrix ) {
this.matrix.multiply( matrix, this.matrix );
this.scale.getScaleFromMatrix( this.matrix );
var mat = new THREE.Matrix4().extractRotation( this.matrix );
this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
this.position.getPositionFromMatrix( this.matrix );
},
translate: function ( distance, axis ) {
this.matrix.rotateAxis( axis );
this.position.addSelf( axis.multiplyScalar( distance ) );
},
translateX: function ( distance ) {
this.translate( distance, this._vector.set( 1, 0, 0 ) );
},
translateY: function ( distance ) {
this.translate( distance, this._vector.set( 0, 1, 0 ) );
},
translateZ: function ( distance ) {
this.translate( distance, this._vector.set( 0, 0, 1 ) );
},
localToWorld: function ( vector ) {
return this.matrixWorld.multiplyVector3( vector );
},
worldToLocal: function ( vector ) {
return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
},
lookAt: function ( vector ) {
// TODO: Add hierarchy support.
this.matrix.lookAt( vector, this.position, this.up );
if ( this.rotationAutoUpdate ) {
this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
}
},
add: function ( object ) {
if ( object === this ) {
console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
return;
}
if ( object instanceof THREE.Object3D ) {
if ( object.parent !== undefined ) {
object.parent.remove( object );
}
object.parent = this;
this.children.push( object );
// add to scene
var scene = this;
while ( scene.parent !== undefined ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
scene.__addObject( object );
}
}
},
remove: function ( object ) {
var index = this.children.indexOf( object );
if ( index !== - 1 ) {
object.parent = undefined;
this.children.splice( index, 1 );
// remove from scene
var scene = this;
while ( scene.parent !== undefined ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
scene.__removeObject( object );
}
}
},
traverse: function ( callback ) {
callback( this );
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].traverse( callback );
}
},
getChildByName: function ( name, recursive ) {
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
if ( child.name === name ) {
return child;
}
if ( recursive === true ) {
child = child.getChildByName( name, recursive );
if ( child !== undefined ) {
return child;
}
}
}
return undefined;
},
getDescendants: function ( array ) {
if ( array === undefined ) array = [];
Array.prototype.push.apply( array, this.children );
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].getDescendants( array );
}
return array;
},
updateMatrix: function () {
this.matrix.setPosition( this.position );
if ( this.useQuaternion === false ) {
this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
} else {
this.matrix.setRotationFromQuaternion( this.quaternion );
}
if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
this.matrix.scale( this.scale );
this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
}
this.matrixWorldNeedsUpdate = true;
},
updateMatrixWorld: function ( force ) {
if ( this.matrixAutoUpdate === true ) this.updateMatrix();
if ( this.matrixWorldNeedsUpdate === true || force === true ) {
if ( this.parent === undefined ) {
this.matrixWorld.copy( this.matrix );
} else {
this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].updateMatrixWorld( force );
}
},
clone: function ( object ) {
if ( object === undefined ) object = new THREE.Object3D();
object.name = this.name;
object.up.copy( this.up );
object.position.copy( this.position );
if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
object.eulerOrder = this.eulerOrder;
object.scale.copy( this.scale );
object.renderDepth = this.renderDepth;
object.rotationAutoUpdate = this.rotationAutoUpdate;
object.matrix.copy( this.matrix );
object.matrixWorld.copy( this.matrixWorld );
object.matrixRotationWorld.copy( this.matrixRotationWorld );
object.matrixAutoUpdate = this.matrixAutoUpdate;
object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
object.quaternion.copy( this.quaternion );
object.useQuaternion = this.useQuaternion;
object.boundRadius = this.boundRadius;
object.boundRadiusScale = this.boundRadiusScale;
object.visible = this.visible;
object.castShadow = this.castShadow;
object.receiveShadow = this.receiveShadow;
object.frustumCulled = this.frustumCulled;
return object;
},
deallocate: function () {
var index = THREE.Object3DLibrary.indexOf( this );
if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
}
};
THREE.Object3D.__m1 = new THREE.Matrix4();
THREE.Object3D.defaultEulerOrder = 'XYZ',
THREE.Object3DIdCount = 0;
THREE.Object3DLibrary = [];
/**
* @author mrdoob / http://mrdoob.com/
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author julianwa / https://github.com/julianwa
*/
THREE.Projector = function() {
var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
_vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
_face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
_face4Count, _face4Pool = [], _face4PoolLength = 0,
_line, _lineCount, _linePool = [], _linePoolLength = 0,
_particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
_renderData = { objects: [], sprites: [], lights: [], elements: [] },
_vector3 = new THREE.Vector3(),
_vector4 = new THREE.Vector4(),
_viewProjectionMatrix = new THREE.Matrix4(),
_modelViewProjectionMatrix = new THREE.Matrix4(),
_frustum = new THREE.Frustum(),
_clippedVertex1PositionScreen = new THREE.Vector4(),
_clippedVertex2PositionScreen = new THREE.Vector4(),
_face3VertexNormals;
this.projectVector = function ( vector, camera ) {
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
_viewProjectionMatrix.multiplyVector3( vector );
return vector;
};
this.unprojectVector = function ( vector, camera ) {
camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
_viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
_viewProjectionMatrix.multiplyVector3( vector );
return vector;
};
this.pickingRay = function ( vector, camera ) {
var end, ray, t;
// set two vectors with opposing z values
vector.z = -1.0;
end = new THREE.Vector3( vector.x, vector.y, 1.0 );
this.unprojectVector( vector, camera );
this.unprojectVector( end, camera );
// find direction from vector to end
end.subSelf( vector ).normalize();
return new THREE.Ray( vector, end );
};
var projectGraph = function ( root, sortObjects ) {
_objectCount = 0;
_renderData.objects.length = 0;
_renderData.sprites.length = 0;
_renderData.lights.length = 0;
var projectObject = function ( parent ) {
for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
var object = parent.children[ c ];
if ( object.visible === false ) continue;
if ( object instanceof THREE.Light ) {
_renderData.lights.push( object );
} else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
_object = getNextObjectInPool();
_object.object = object;
if ( object.renderDepth !== null ) {
_object.z = object.renderDepth;
} else {
_vector3.copy( object.matrixWorld.getPosition() );
_viewProjectionMatrix.multiplyVector3( _vector3 );
_object.z = _vector3.z;
}
_renderData.objects.push( _object );
}
} else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
_object = getNextObjectInPool();
_object.object = object;
// TODO: Find an elegant and performant solution and remove this dupe code.
if ( object.renderDepth !== null ) {
_object.z = object.renderDepth;
} else {
_vector3.copy( object.matrixWorld.getPosition() );
_viewProjectionMatrix.multiplyVector3( _vector3 );
_object.z = _vector3.z;
}
_renderData.sprites.push( _object );
} else {
_object = getNextObjectInPool();
_object.object = object;
if ( object.renderDepth !== null ) {
_object.z = object.renderDepth;
} else {
_vector3.copy( object.matrixWorld.getPosition() );
_viewProjectionMatrix.multiplyVector3( _vector3 );
_object.z = _vector3.z;
}
_renderData.objects.push( _object );
}
projectObject( object );
}
};
projectObject( root );
if ( sortObjects === true ) _renderData.objects.sort( painterSort );
return _renderData;
};
this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
var near = camera.near, far = camera.far, visible = false,
o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
modelMatrix, rotationMatrix,
geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
v1, v2, v3, v4, isFaceMaterial, material, side;
_face3Count = 0;
_face4Count = 0;
_lineCount = 0;
_particleCount = 0;
_renderData.elements.length = 0;
scene.updateMatrixWorld();
if ( camera.parent === undefined ) camera.updateMatrixWorld();
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _viewProjectionMatrix );
_renderData = projectGraph( scene, sortObjects );
for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
object = _renderData.objects[ o ].object;
modelMatrix = object.matrixWorld;
_vertexCount = 0;
if ( object instanceof THREE.Mesh ) {
geometry = object.geometry;
geometryMaterials = object.geometry.materials;
vertices = geometry.vertices;
faces = geometry.faces;
faceVertexUvs = geometry.faceVertexUvs;
rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );
isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
side = object.material.side;
for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
_vertex = getNextVertexInPool();
_vertex.positionWorld.copy( vertices[ v ] );
modelMatrix.multiplyVector3( _vertex.positionWorld );
_vertex.positionScreen.copy( _vertex.positionWorld );
_viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
_vertex.positionScreen.x /= _vertex.positionScreen.w;
_vertex.positionScreen.y /= _vertex.positionScreen.w;
_vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
}
for ( f = 0, fl = faces.length; f < fl; f ++ ) {
face = faces[ f ];
material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
if ( material === undefined ) continue;
side = material.side;
if ( face instanceof THREE.Face3 ) {
v1 = _vertexPool[ face.a ];
v2 = _vertexPool[ face.b ];
v3 = _vertexPool[ face.c ];
if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
_face = getNextFace3InPool();
_face.v1.copy( v1 );
_face.v2.copy( v2 );
_face.v3.copy( v3 );
} else {
continue;
}
} else {
continue;
}
} else if ( face instanceof THREE.Face4 ) {
v1 = _vertexPool[ face.a ];
v2 = _vertexPool[ face.b ];
v3 = _vertexPool[ face.c ];
v4 = _vertexPool[ face.d ];
if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
_face = getNextFace4InPool();
_face.v1.copy( v1 );
_face.v2.copy( v2 );
_face.v3.copy( v3 );
_face.v4.copy( v4 );
} else {
continue;
}
} else {
continue;
}
}
_face.normalWorld.copy( face.normal );
if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
rotationMatrix.multiplyVector3( _face.normalWorld );
_face.centroidWorld.copy( face.centroid );
modelMatrix.multiplyVector3( _face.centroidWorld );
_face.centroidScreen.copy( _face.centroidWorld );
_viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
faceVertexNormals = face.vertexNormals;
for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
normal = _face.vertexNormalsWorld[ n ];
normal.copy( faceVertexNormals[ n ] );
if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
rotationMatrix.multiplyVector3( normal );
}
_face.vertexNormalsLength = faceVertexNormals.length;
for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
uvs = faceVertexUvs[ c ][ f ];
if ( uvs === undefined ) continue;
for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
_face.uvs[ c ][ u ] = uvs[ u ];
}
}
_face.color = face.color;
_face.material = material;
_face.z = _face.centroidScreen.z;
_renderData.elements.push( _face );
}
} else if ( object instanceof THREE.Line ) {
_modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
vertices = object.geometry.vertices;
v1 = getNextVertexInPool();
v1.positionScreen.copy( vertices[ 0 ] );
_modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
// Handle LineStrip and LinePieces
var step = object.type === THREE.LinePieces ? 2 : 1;
for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
v1 = getNextVertexInPool();
v1.positionScreen.copy( vertices[ v ] );
_modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
if ( ( v + 1 ) % step > 0 ) continue;
v2 = _vertexPool[ _vertexCount - 2 ];
_clippedVertex1PositionScreen.copy( v1.positionScreen );
_clippedVertex2PositionScreen.copy( v2.positionScreen );
if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
// Perform the perspective divide
_clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
_clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
_line = getNextLineInPool();
_line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
_line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
_line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
_line.material = object.material;
_renderData.elements.push( _line );
}
}
}
}
for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
object = _renderData.sprites[ o ].object;
modelMatrix = object.matrixWorld;
if ( object instanceof THREE.Particle ) {
_vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
_viewProjectionMatrix.multiplyVector4( _vector4 );
_vector4.z /= _vector4.w;
if ( _vector4.z > 0 && _vector4.z < 1 ) {
_particle = getNextParticleInPool();
_particle.object = object;
_particle.x = _vector4.x / _vector4.w;
_particle.y = _vector4.y / _vector4.w;
_particle.z = _vector4.z;
_particle.rotation = object.rotation.z;
_particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
_particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
_particle.material = object.material;
_renderData.elements.push( _particle );
}
}
}
if ( sortElements === true ) _renderData.elements.sort( painterSort );
return _renderData;
};
// Pools
function getNextObjectInPool() {
if ( _objectCount === _objectPoolLength ) {
var object = new THREE.RenderableObject();
_objectPool.push( object );
_objectPoolLength ++;
_objectCount ++;
return object;
}
return _objectPool[ _objectCount ++ ];
}
function getNextVertexInPool() {
if ( _vertexCount === _vertexPoolLength ) {
var vertex = new THREE.RenderableVertex();
_vertexPool.push( vertex );
_vertexPoolLength ++;
_vertexCount ++;
return vertex;
}
return _vertexPool[ _vertexCount ++ ];
}
function getNextFace3InPool() {
if ( _face3Count === _face3PoolLength ) {
var face = new THREE.RenderableFace3();
_face3Pool.push( face );
_face3PoolLength ++;
_face3Count ++;
return face;
}
return _face3Pool[ _face3Count ++ ];
}
function getNextFace4InPool() {
if ( _face4Count === _face4PoolLength ) {
var face = new THREE.RenderableFace4();
_face4Pool.push( face );
_face4PoolLength ++;
_face4Count ++;
return face;
}
return _face4Pool[ _face4Count ++ ];
}
function getNextLineInPool() {
if ( _lineCount === _linePoolLength ) {
var line = new THREE.RenderableLine();
_linePool.push( line );
_linePoolLength ++;
_lineCount ++
return line;
}
return _linePool[ _lineCount ++ ];
}
function getNextParticleInPool() {
if ( _particleCount === _particlePoolLength ) {
var particle = new THREE.RenderableParticle();
_particlePool.push( particle );
_particlePoolLength ++;
_particleCount ++
return particle;
}
return _particlePool[ _particleCount ++ ];
}
//
function painterSort( a, b ) {
return b.z - a.z;
}
function clipLine( s1, s2 ) {
var alpha1 = 0, alpha2 = 1,
// Calculate the boundary coordinate of each vertex for the near and far clip planes,
// Z = -1 and Z = +1, respectively.
bc1near = s1.z + s1.w,
bc2near = s2.z + s2.w,
bc1far = - s1.z + s1.w,
bc2far = - s2.z + s2.w;
if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
// Both vertices lie entirely within all clip planes.
return true;
} else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
// Both vertices lie entirely outside one of the clip planes.
return false;
} else {
// The line segment spans at least one clip plane.
if ( bc1near < 0 ) {
// v1 lies outside the near plane, v2 inside
alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
} else if ( bc2near < 0 ) {
// v2 lies outside the near plane, v1 inside
alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
}
if ( bc1far < 0 ) {
// v1 lies outside the far plane, v2 inside
alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
} else if ( bc2far < 0 ) {
// v2 lies outside the far plane, v2 inside
alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
}
if ( alpha2 < alpha1 ) {
// The line segment spans two boundaries, but is outside both of them.
// (This can't happen when we're only clipping against just near/far but good
// to leave the check here for future usage if other clip planes are added.)
return false;
} else {
// Update the s1 and s2 vertices to match the clipped line segment.
s1.lerpSelf( s2, alpha1 );
s2.lerpSelf( s1, 1 - alpha2 );
return true;
}
}
}
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Quaternion = function( x, y, z, w ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = ( w !== undefined ) ? w : 1;
};
THREE.Quaternion.prototype = {
constructor: THREE.Quaternion,
set: function ( x, y, z, w ) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
},
copy: function ( q ) {
this.x = q.x;
this.y = q.y;
this.z = q.z;
this.w = q.w;
return this;
},
setFromEuler: function ( v, order ) {
// http://www.mathworks.com/matlabcentral/fileexchange/
// 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
// content/SpinCalc.m
var c1 = Math.cos( v.x / 2 );
var c2 = Math.cos( v.y / 2 );
var c3 = Math.cos( v.z / 2 );
var s1 = Math.sin( v.x / 2 );
var s2 = Math.sin( v.y / 2 );
var s3 = Math.sin( v.z / 2 );
if ( order === undefined || order === 'XYZ' ) {
this.x = s1 * c2 * c3 + c1 * s2 * s3;
this.y = c1 * s2 * c3 - s1 * c2 * s3;
this.z = c1 * c2 * s3 + s1 * s2 * c3;
this.w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( order === 'YXZ' ) {
this.x = s1 * c2 * c3 + c1 * s2 * s3;
this.y = c1 * s2 * c3 - s1 * c2 * s3;
this.z = c1 * c2 * s3 - s1 * s2 * c3;
this.w = c1 * c2 * c3 + s1 * s2 * s3;
} else if ( order === 'ZXY' ) {
this.x = s1 * c2 * c3 - c1 * s2 * s3;
this.y = c1 * s2 * c3 + s1 * c2 * s3;
this.z = c1 * c2 * s3 + s1 * s2 * c3;
this.w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( order === 'ZYX' ) {
this.x = s1 * c2 * c3 - c1 * s2 * s3;
this.y = c1 * s2 * c3 + s1 * c2 * s3;
this.z = c1 * c2 * s3 - s1 * s2 * c3;
this.w = c1 * c2 * c3 + s1 * s2 * s3;
} else if ( order === 'YZX' ) {
this.x = s1 * c2 * c3 + c1 * s2 * s3;
this.y = c1 * s2 * c3 + s1 * c2 * s3;
this.z = c1 * c2 * s3 - s1 * s2 * c3;
this.w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( order === 'XZY' ) {
this.x = s1 * c2 * c3 - c1 * s2 * s3;
this.y = c1 * s2 * c3 - s1 * c2 * s3;
this.z = c1 * c2 * s3 + s1 * s2 * c3;
this.w = c1 * c2 * c3 + s1 * s2 * s3;
}
return this;
},
setFromAxisAngle: function ( axis, angle ) {
// from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
// axis have to be normalized
var halfAngle = angle / 2,
s = Math.sin( halfAngle );
this.x = axis.x * s;
this.y = axis.y * s;
this.z = axis.z * s;
this.w = Math.cos( halfAngle );
return this;
},
setFromRotationMatrix: function ( m ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements,
m11 = te[0], m12 = te[4], m13 = te[8],
m21 = te[1], m22 = te[5], m23 = te[9],
m31 = te[2], m32 = te[6], m33 = te[10],
trace = m11 + m22 + m33,
s;
if( trace > 0 ) {
s = 0.5 / Math.sqrt( trace + 1.0 );
this.w = 0.25 / s;
this.x = ( m32 - m23 ) * s;
this.y = ( m13 - m31 ) * s;
this.z = ( m21 - m12 ) * s;
} else if ( m11 > m22 && m11 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
this.w = (m32 - m23 ) / s;
this.x = 0.25 * s;
this.y = (m12 + m21 ) / s;
this.z = (m13 + m31 ) / s;
} else if (m22 > m33) {
s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
this.w = (m13 - m31 ) / s;
this.x = (m12 + m21 ) / s;
this.y = 0.25 * s;
this.z = (m23 + m32 ) / s;
} else {
s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
this.w = ( m21 - m12 ) / s;
this.x = ( m13 + m31 ) / s;
this.y = ( m23 + m32 ) / s;
this.z = 0.25 * s;
}
return this;
},
calculateW : function () {
this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
return this;
},
inverse: function () {
this.x *= -1;
this.y *= -1;
this.z *= -1;
return this;
},
length: function () {
return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
},
normalize: function () {
var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
if ( l === 0 ) {
this.x = 0;
this.y = 0;
this.z = 0;
this.w = 0;
} else {
l = 1 / l;
this.x = this.x * l;
this.y = this.y * l;
this.z = this.z * l;
this.w = this.w * l;
}
return this;
},
multiply: function ( a, b ) {
// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
return this;
},
multiplySelf: function ( b ) {
var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
return this;
},
multiplyVector3: function ( vector, dest ) {
if ( !dest ) { dest = vector; }
var x = vector.x, y = vector.y, z = vector.z,
qx = this.x, qy = this.y, qz = this.z, qw = this.w;
// calculate quat * vector
var ix = qw * x + qy * z - qz * y,
iy = qw * y + qz * x - qx * z,
iz = qw * z + qx * y - qy * x,
iw = -qx * x - qy * y - qz * z;
// calculate result * inverse quat
dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
return dest;
},
slerpSelf: function ( qb, t ) {
var x = this.x, y = this.y, z = this.z, w = this.w;
// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
if ( cosHalfTheta < 0 ) {
this.w = -qb.w;
this.x = -qb.x;
this.y = -qb.y;
this.z = -qb.z;
cosHalfTheta = -cosHalfTheta;
} else {
this.copy( qb );
}
if ( cosHalfTheta >= 1.0 ) {
this.w = w;
this.x = x;
this.y = y;
this.z = z;
return this;
}
var halfTheta = Math.acos( cosHalfTheta );
var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
if ( Math.abs( sinHalfTheta ) < 0.001 ) {
this.w = 0.5 * ( w + this.w );
this.x = 0.5 * ( x + this.x );
this.y = 0.5 * ( y + this.y );
this.z = 0.5 * ( z + this.z );
return this;
}
var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
this.w = ( w * ratioA + this.w * ratioB );
this.x = ( x * ratioA + this.x * ratioB );
this.y = ( y * ratioA + this.y * ratioB );
this.z = ( z * ratioA + this.z * ratioB );
return this;
},
clone: function () {
return new THREE.Quaternion( this.x, this.y, this.z, this.w );
}
}
THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
if ( cosHalfTheta < 0 ) {
qm.w = -qb.w;
qm.x = -qb.x;
qm.y = -qb.y;
qm.z = -qb.z;
cosHalfTheta = -cosHalfTheta;
} else {
qm.copy( qb );
}
if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
qm.w = qa.w;
qm.x = qa.x;
qm.y = qa.y;
qm.z = qa.z;
return qm;
}
var halfTheta = Math.acos( cosHalfTheta );
var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
if ( Math.abs( sinHalfTheta ) < 0.001 ) {
qm.w = 0.5 * ( qa.w + qm.w );
qm.x = 0.5 * ( qa.x + qm.x );
qm.y = 0.5 * ( qa.y + qm.y );
qm.z = 0.5 * ( qa.z + qm.z );
return qm;
}
var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
qm.w = ( qa.w * ratioA + qm.w * ratioB );
qm.x = ( qa.x * ratioA + qm.x * ratioB );
qm.y = ( qa.y * ratioA + qm.y * ratioB );
qm.z = ( qa.z * ratioA + qm.z * ratioB );
return qm;
}
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Vertex = function ( v ) {
console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
return v;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
this.a = a;
this.b = b;
this.c = c;
this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
this.vertexNormals = normal instanceof Array ? normal : [ ];
this.color = color instanceof THREE.Color ? color : new THREE.Color();
this.vertexColors = color instanceof Array ? color : [];
this.vertexTangents = [];
this.materialIndex = materialIndex;
this.centroid = new THREE.Vector3();
};
THREE.Face3.prototype = {
constructor: THREE.Face3,
clone: function () {
var face = new THREE.Face3( this.a, this.b, this.c );
face.normal.copy( this.normal );
face.color.copy( this.color );
face.centroid.copy( this.centroid );
face.materialIndex = this.materialIndex;
var i, il;
for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
return face;
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
this.vertexNormals = normal instanceof Array ? normal : [ ];
this.color = color instanceof THREE.Color ? color : new THREE.Color();
this.vertexColors = color instanceof Array ? color : [];
this.vertexTangents = [];
this.materialIndex = materialIndex;
this.centroid = new THREE.Vector3();
};
THREE.Face4.prototype = {
constructor: THREE.Face4,
clone: function () {
var face = new THREE.Face4( this.a, this.b, this.c, this.d );
face.normal.copy( this.normal );
face.color.copy( this.color );
face.centroid.copy( this.centroid );
face.materialIndex = this.materialIndex;
var i, il;
for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
return face;
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.UV = function ( u, v ) {
this.u = u || 0;
this.v = v || 0;
};
THREE.UV.prototype = {
constructor: THREE.UV,
set: function ( u, v ) {
this.u = u;
this.v = v;
return this;
},
copy: function ( uv ) {
this.u = uv.u;
this.v = uv.v;
return this;
},
lerpSelf: function ( uv, alpha ) {
this.u += ( uv.u - this.u ) * alpha;
this.v += ( uv.v - this.v ) * alpha;
return this;
},
clone: function () {
return new THREE.UV( this.u, this.v );
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author kile / http://kile.stravaganza.org/
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author zz85 / http://www.lab4games.net/zz85/blog
*/
THREE.Geometry = function () {
THREE.GeometryLibrary.push( this );
this.id = THREE.GeometryIdCount ++;
this.name = '';
this.vertices = [];
this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
this.materials = [];
this.faces = [];
this.faceUvs = [[]];
this.faceVertexUvs = [[]];
this.morphTargets = [];
this.morphColors = [];
this.morphNormals = [];
this.skinWeights = [];
this.skinIndices = [];
this.boundingBox = null;
this.boundingSphere = null;
this.hasTangents = false;
this.dynamic = true; // the intermediate typearrays will be deleted when set to false
// update flags
this.verticesNeedUpdate = false;
this.elementsNeedUpdate = false;
this.uvsNeedUpdate = false;
this.normalsNeedUpdate = false;
this.tangentsNeedUpdate = false;
this.colorsNeedUpdate = false;
};
THREE.Geometry.prototype = {
constructor : THREE.Geometry,
applyMatrix: function ( matrix ) {
var matrixRotation = new THREE.Matrix4();
matrixRotation.extractRotation( matrix );
for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
var vertex = this.vertices[ i ];
matrix.multiplyVector3( vertex );
}
for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
var face = this.faces[ i ];
matrixRotation.multiplyVector3( face.normal );
for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
}
matrix.multiplyVector3( face.centroid );
}
},
computeCentroids: function () {
var f, fl, face;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
face.centroid.set( 0, 0, 0 );
if ( face instanceof THREE.Face3 ) {
face.centroid.addSelf( this.vertices[ face.a ] );
face.centroid.addSelf( this.vertices[ face.b ] );
face.centroid.addSelf( this.vertices[ face.c ] );
face.centroid.divideScalar( 3 );
} else if ( face instanceof THREE.Face4 ) {
face.centroid.addSelf( this.vertices[ face.a ] );
face.centroid.addSelf( this.vertices[ face.b ] );
face.centroid.addSelf( this.vertices[ face.c ] );
face.centroid.addSelf( this.vertices[ face.d ] );
face.centroid.divideScalar( 4 );
}
}
},
computeFaceNormals: function () {
var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
cb = new THREE.Vector3(), ab = new THREE.Vector3();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
vA = this.vertices[ face.a ];
vB = this.vertices[ face.b ];
vC = this.vertices[ face.c ];
cb.sub( vC, vB );
ab.sub( vA, vB );
cb.crossSelf( ab );
if ( !cb.isZero() ) {
cb.normalize();
}
face.normal.copy( cb );
}
},
computeVertexNormals: function () {
var v, vl, f, fl, face, vertices;
// create internal buffers for reuse when calling this method repeatedly
// (otherwise memory allocation / deallocation every frame is big resource hog)
if ( this.__tmpVertices === undefined ) {
this.__tmpVertices = new Array( this.vertices.length );
vertices = this.__tmpVertices;
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ] = new THREE.Vector3();
}
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
if ( face instanceof THREE.Face3 ) {
face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
} else if ( face instanceof THREE.Face4 ) {
face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
}
}
} else {
vertices = this.__tmpVertices;
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ].set( 0, 0, 0 );
}
}
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
if ( face instanceof THREE.Face3 ) {
vertices[ face.a ].addSelf( face.normal );
vertices[ face.b ].addSelf( face.normal );
vertices[ face.c ].addSelf( face.normal );
} else if ( face instanceof THREE.Face4 ) {
vertices[ face.a ].addSelf( face.normal );
vertices[ face.b ].addSelf( face.normal );
vertices[ face.c ].addSelf( face.normal );
vertices[ face.d ].addSelf( face.normal );
}
}
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ].normalize();
}
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
if ( face instanceof THREE.Face3 ) {
face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
} else if ( face instanceof THREE.Face4 ) {
face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
}
}
},
computeMorphNormals: function () {
var i, il, f, fl, face;
// save original normals
// - create temp variables on first access
// otherwise just copy (for faster repeated calls)
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
if ( ! face.__originalFaceNormal ) {
face.__originalFaceNormal = face.normal.clone();
} else {
face.__originalFaceNormal.copy( face.normal );
}
if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
if ( ! face.__originalVertexNormals[ i ] ) {
face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
} else {
face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
}
}
}
// use temp geometry to compute face and vertex normals for each morph
var tmpGeo = new THREE.Geometry();
tmpGeo.faces = this.faces;
for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
// create on first access
if ( ! this.morphNormals[ i ] ) {
this.morphNormals[ i ] = {};
this.morphNormals[ i ].faceNormals = [];
this.morphNormals[ i ].vertexNormals = [];
var dstNormalsFace = this.morphNormals[ i ].faceNormals;
var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
faceNormal = new THREE.Vector3();
if ( face instanceof THREE.Face3 ) {
vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
} else {
vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
}
dstNormalsFace.push( faceNormal );
dstNormalsVertex.push( vertexNormals );
}
}
var morphNormals = this.morphNormals[ i ];
// set vertices to morph target
tmpGeo.vertices = this.morphTargets[ i ].vertices;
// compute morph normals
tmpGeo.computeFaceNormals();
tmpGeo.computeVertexNormals();
// store morph normals
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
faceNormal = morphNormals.faceNormals[ f ];
vertexNormals = morphNormals.vertexNormals[ f ];
faceNormal.copy( face.normal );
if ( face instanceof THREE.Face3 ) {
vertexNormals.a.copy( face.vertexNormals[ 0 ] );
vertexNormals.b.copy( face.vertexNormals[ 1 ] );
vertexNormals.c.copy( face.vertexNormals[ 2 ] );
} else {
vertexNormals.a.copy( face.vertexNormals[ 0 ] );
vertexNormals.b.copy( face.vertexNormals[ 1 ] );
vertexNormals.c.copy( face.vertexNormals[ 2 ] );
vertexNormals.d.copy( face.vertexNormals[ 3 ] );
}
}
}
// restore original normals
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
face.normal = face.__originalFaceNormal;
face.vertexNormals = face.__originalVertexNormals;
}
},
computeTangents: function () {
// based on http://www.terathon.com/code/tangent.html
// tangents go to vertices
var f, fl, v, vl, i, il, vertexIndex,
face, uv, vA, vB, vC, uvA, uvB, uvC,
x1, x2, y1, y2, z1, z2,
s1, s2, t1, t2, r, t, test,
tan1 = [], tan2 = [],
sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
n = new THREE.Vector3(), w;
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
tan1[ v ] = new THREE.Vector3();
tan2[ v ] = new THREE.Vector3();
}
function handleTriangle( context, a, b, c, ua, ub, uc ) {
vA = context.vertices[ a ];
vB = context.vertices[ b ];
vC = context.vertices[ c ];
uvA = uv[ ua ];
uvB = uv[ ub ];
uvC = uv[ uc ];
x1 = vB.x - vA.x;
x2 = vC.x - vA.x;
y1 = vB.y - vA.y;
y2 = vC.y - vA.y;
z1 = vB.z - vA.z;
z2 = vC.z - vA.z;
s1 = uvB.u - uvA.u;
s2 = uvC.u - uvA.u;
t1 = uvB.v - uvA.v;
t2 = uvC.v - uvA.v;
r = 1.0 / ( s1 * t2 - s2 * t1 );
sdir.set( ( t2 * x1 - t1 * x2 ) * r,
( t2 * y1 - t1 * y2 ) * r,
( t2 * z1 - t1 * z2 ) * r );
tdir.set( ( s1 * x2 - s2 * x1 ) * r,
( s1 * y2 - s2 * y1 ) * r,
( s1 * z2 - s2 * z1 ) * r );
tan1[ a ].addSelf( sdir );
tan1[ b ].addSelf( sdir );
tan1[ c ].addSelf( sdir );
tan2[ a ].addSelf( tdir );
tan2[ b ].addSelf( tdir );
tan2[ c ].addSelf( tdir );
}
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
if ( face instanceof THREE.Face3 ) {
handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
} else if ( face instanceof THREE.Face4 ) {
handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
}
}
var faceIndex = [ 'a', 'b', 'c', 'd' ];
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
for ( i = 0; i < face.vertexNormals.length; i++ ) {
n.copy( face.vertexNormals[ i ] );
vertexIndex = face[ faceIndex[ i ] ];
t = tan1[ vertexIndex ];
// Gram-Schmidt orthogonalize
tmp.copy( t );
tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
// Calculate handedness
tmp2.cross( face.vertexNormals[ i ], t );
test = tmp2.dot( tan2[ vertexIndex ] );
w = (test < 0.0) ? -1.0 : 1.0;
face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
}
}
this.hasTangents = true;
},
computeBoundingBox: function () {
if ( ! this.boundingBox ) {
this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
}
if ( this.vertices.length > 0 ) {
var position, firstPosition = this.vertices[ 0 ];
this.boundingBox.min.copy( firstPosition );
this.boundingBox.max.copy( firstPosition );
var min = this.boundingBox.min,
max = this.boundingBox.max;
for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
position = this.vertices[ v ];
if ( position.x < min.x ) {
min.x = position.x;
} else if ( position.x > max.x ) {
max.x = position.x;
}
if ( position.y < min.y ) {
min.y = position.y;
} else if ( position.y > max.y ) {
max.y = position.y;
}
if ( position.z < min.z ) {
min.z = position.z;
} else if ( position.z > max.z ) {
max.z = position.z;
}
}
} else {
this.boundingBox.min.set( 0, 0, 0 );
this.boundingBox.max.set( 0, 0, 0 );
}
},
computeBoundingSphere: function () {
var maxRadiusSq = 0;
if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
var radiusSq = this.vertices[ i ].lengthSq();
if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
}
this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
},
/*
* Checks for duplicate vertices with hashmap.
* Duplicated vertices are removed
* and faces' vertices are updated.
*/
mergeVertices: function () {
var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
var unique = [], changes = [];
var v, key;
var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
var precision = Math.pow( 10, precisionPoints );
var i,il, face;
var abcd = 'abcd', o, k, j, jl, u;
for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
v = this.vertices[ i ];
key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
if ( verticesMap[ key ] === undefined ) {
verticesMap[ key ] = i;
unique.push( this.vertices[ i ] );
changes[ i ] = unique.length - 1;
} else {
//console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
changes[ i ] = changes[ verticesMap[ key ] ];
}
};
// Start to patch face indices
for( i = 0, il = this.faces.length; i < il; i ++ ) {
face = this.faces[ i ];
if ( face instanceof THREE.Face3 ) {
face.a = changes[ face.a ];
face.b = changes[ face.b ];
face.c = changes[ face.c ];
} else if ( face instanceof THREE.Face4 ) {
face.a = changes[ face.a ];
face.b = changes[ face.b ];
face.c = changes[ face.c ];
face.d = changes[ face.d ];
// check dups in (a, b, c, d) and convert to -> face3
o = [ face.a, face.b, face.c, face.d ];
for ( k = 3; k > 0; k -- ) {
if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
// console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
o.splice( k, 1 );
this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
u = this.faceVertexUvs[ j ][ i ];
if ( u ) u.splice( k, 1 );
}
this.faces[ i ].vertexColors = face.vertexColors;
break;
}
}
}
}
// Use unique set of vertices
var diff = this.vertices.length - unique.length;
this.vertices = unique;
return diff;
},
clone: function () {
// TODO
},
deallocate: function () {
var index = THREE.GeometryLibrary.indexOf( this );
if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
}
};
THREE.GeometryIdCount = 0;
THREE.GeometryLibrary = [];
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.BufferGeometry = function () {
THREE.GeometryLibrary.push( this );
this.id = THREE.GeometryIdCount ++;
// attributes
this.attributes = {};
// attributes typed arrays are kept only if dynamic flag is set
this.dynamic = false;
// boundings
this.boundingBox = null;
this.boundingSphere = null;
this.hasTangents = false;
// for compatibility
this.morphTargets = [];
};
THREE.BufferGeometry.prototype = {
constructor : THREE.BufferGeometry,
applyMatrix: function ( matrix ) {
var positionArray;
var normalArray;
if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
if ( positionArray !== undefined ) {
matrix.multiplyVector3Array( positionArray );
this.verticesNeedUpdate = true;
}
if ( normalArray !== undefined ) {
var matrixRotation = new THREE.Matrix4();
matrixRotation.extractRotation( matrix );
matrixRotation.multiplyVector3Array( normalArray );
this.normalsNeedUpdate = true;
}
},
computeBoundingBox: function () {
if ( ! this.boundingBox ) {
this.boundingBox = {
min: new THREE.Vector3( Infinity, Infinity, Infinity ),
max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
};
}
var positions = this.attributes[ "position" ].array;
if ( positions ) {
var bb = this.boundingBox;
var x, y, z;
for ( var i = 0, il = positions.length; i < il; i += 3 ) {
x = positions[ i ];
y = positions[ i + 1 ];
z = positions[ i + 2 ];
// bounding box
if ( x < bb.min.x ) {
bb.min.x = x;
} else if ( x > bb.max.x ) {
bb.max.x = x;
}
if ( y < bb.min.y ) {
bb.min.y = y;
} else if ( y > bb.max.y ) {
bb.max.y = y;
}
if ( z < bb.min.z ) {
bb.min.z = z;
} else if ( z > bb.max.z ) {
bb.max.z = z;
}
}
}
if ( positions === undefined || positions.length === 0 ) {
this.boundingBox.min.set( 0, 0, 0 );
this.boundingBox.max.set( 0, 0, 0 );
}
},
computeBoundingSphere: function () {
if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
var positions = this.attributes[ "position" ].array;
if ( positions ) {
var radiusSq, maxRadiusSq = 0;
var x, y, z;
for ( var i = 0, il = positions.length; i < il; i += 3 ) {
x = positions[ i ];
y = positions[ i + 1 ];
z = positions[ i + 2 ];
radiusSq = x * x + y * y + z * z;
if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
}
this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
}
},
computeVertexNormals: function () {
if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
var i, il;
var j, jl;
var nVertexElements = this.attributes[ "position" ].array.length;
if ( this.attributes[ "normal" ] === undefined ) {
this.attributes[ "normal" ] = {
itemSize: 3,
array: new Float32Array( nVertexElements ),
numItems: nVertexElements
};
} else {
// reset existing normals to zero
for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
this.attributes[ "normal" ].array[ i ] = 0;
}
}
var offsets = this.offsets;
var indices = this.attributes[ "index" ].array;
var positions = this.attributes[ "position" ].array;
var normals = this.attributes[ "normal" ].array;
var vA, vB, vC, x, y, z,
pA = new THREE.Vector3(),
pB = new THREE.Vector3(),
pC = new THREE.Vector3(),
cb = new THREE.Vector3(),
ab = new THREE.Vector3();
for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
var start = offsets[ j ].start;
var count = offsets[ j ].count;
var index = offsets[ j ].index;
for ( i = start, il = start + count; i < il; i += 3 ) {
vA = index + indices[ i ];
vB = index + indices[ i + 1 ];
vC = index + indices[ i + 2 ];
x = positions[ vA * 3 ];
y = positions[ vA * 3 + 1 ];
z = positions[ vA * 3 + 2 ];
pA.set( x, y, z );
x = positions[ vB * 3 ];
y = positions[ vB * 3 + 1 ];
z = positions[ vB * 3 + 2 ];
pB.set( x, y, z );
x = positions[ vC * 3 ];
y = positions[ vC * 3 + 1 ];
z = positions[ vC * 3 + 2 ];
pC.set( x, y, z );
cb.sub( pC, pB );
ab.sub( pA, pB );
cb.crossSelf( ab );
normals[ vA * 3 ] += cb.x;
normals[ vA * 3 + 1 ] += cb.y;
normals[ vA * 3 + 2 ] += cb.z;
normals[ vB * 3 ] += cb.x;
normals[ vB * 3 + 1 ] += cb.y;
normals[ vB * 3 + 2 ] += cb.z;
normals[ vC * 3 ] += cb.x;
normals[ vC * 3 + 1 ] += cb.y;
normals[ vC * 3 + 2 ] += cb.z;
}
}
// normalize normals
for ( i = 0, il = normals.length; i < il; i += 3 ) {
x = normals[ i ];
y = normals[ i + 1 ];
z = normals[ i + 2 ];
var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
normals[ i ] *= n;
normals[ i + 1 ] *= n;
normals[ i + 2 ] *= n;
}
this.normalsNeedUpdate = true;
}
},
computeTangents: function () {
// based on http://www.terathon.com/code/tangent.html
// (per vertex tangents)
if ( this.attributes[ "index" ] === undefined ||
this.attributes[ "position" ] === undefined ||
this.attributes[ "normal" ] === undefined ||
this.attributes[ "uv" ] === undefined ) {
console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
return;
}
var indices = this.attributes[ "index" ].array;
var positions = this.attributes[ "position" ].array;
var normals = this.attributes[ "normal" ].array;
var uvs = this.attributes[ "uv" ].array;
var nVertices = positions.length / 3;
if ( this.attributes[ "tangent" ] === undefined ) {
var nTangentElements = 4 * nVertices;
this.attributes[ "tangent" ] = {
itemSize: 4,
array: new Float32Array( nTangentElements ),
numItems: nTangentElements
};
}
var tangents = this.attributes[ "tangent" ].array;
var tan1 = [], tan2 = [];
for ( var k = 0; k < nVertices; k ++ ) {
tan1[ k ] = new THREE.Vector3();
tan2[ k ] = new THREE.Vector3();
}
var xA, yA, zA,
xB, yB, zB,
xC, yC, zC,
uA, vA,
uB, vB,
uC, vC,
x1, x2, y1, y2, z1, z2,
s1, s2, t1, t2, r;
var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
function handleTriangle( a, b, c ) {
xA = positions[ a * 3 ];
yA = positions[ a * 3 + 1 ];
zA = positions[ a * 3 + 2 ];
xB = positions[ b * 3 ];
yB = positions[ b * 3 + 1 ];
zB = positions[ b * 3 + 2 ];
xC = positions[ c * 3 ];
yC = positions[ c * 3 + 1 ];
zC = positions[ c * 3 + 2 ];
uA = uvs[ a * 2 ];
vA = uvs[ a * 2 + 1 ];
uB = uvs[ b * 2 ];
vB = uvs[ b * 2 + 1 ];
uC = uvs[ c * 2 ];
vC = uvs[ c * 2 + 1 ];
x1 = xB - xA;
x2 = xC - xA;
y1 = yB - yA;
y2 = yC - yA;
z1 = zB - zA;
z2 = zC - zA;
s1 = uB - uA;
s2 = uC - uA;
t1 = vB - vA;
t2 = vC - vA;
r = 1.0 / ( s1 * t2 - s2 * t1 );
sdir.set(
( t2 * x1 - t1 * x2 ) * r,
( t2 * y1 - t1 * y2 ) * r,
( t2 * z1 - t1 * z2 ) * r
);
tdir.set(
( s1 * x2 - s2 * x1 ) * r,
( s1 * y2 - s2 * y1 ) * r,
( s1 * z2 - s2 * z1 ) * r
);
tan1[ a ].addSelf( sdir );
tan1[ b ].addSelf( sdir );
tan1[ c ].addSelf( sdir );
tan2[ a ].addSelf( tdir );
tan2[ b ].addSelf( tdir );
tan2[ c ].addSelf( tdir );
}
var i, il;
var j, jl;
var iA, iB, iC;
var offsets = this.offsets;
for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
var start = offsets[ j ].start;
var count = offsets[ j ].count;
var index = offsets[ j ].index;
for ( i = start, il = start + count; i < il; i += 3 ) {
iA = index + indices[ i ];
iB = index + indices[ i + 1 ];
iC = index + indices[ i + 2 ];
handleTriangle( iA, iB, iC );
}
}
var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
var n = new THREE.Vector3(), n2 = new THREE.Vector3();
var w, t, test;
var nx, ny, nz;
function handleVertex( v ) {
n.x = normals[ v * 3 ];
n.y = normals[ v * 3 + 1 ];
n.z = normals[ v * 3 + 2 ];
n2.copy( n );
t = tan1[ v ];
// Gram-Schmidt orthogonalize
tmp.copy( t );
tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
// Calculate handedness
tmp2.cross( n2, t );
test = tmp2.dot( tan2[ v ] );
w = ( test < 0.0 ) ? -1.0 : 1.0;
tangents[ v * 4 ] = tmp.x;
tangents[ v * 4 + 1 ] = tmp.y;
tangents[ v * 4 + 2 ] = tmp.z;
tangents[ v * 4 + 3 ] = w;
}
for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
var start = offsets[ j ].start;
var count = offsets[ j ].count;
var index = offsets[ j ].index;
for ( i = start, il = start + count; i < il; i += 3 ) {
iA = index + indices[ i ];
iB = index + indices[ i + 1 ];
iC = index + indices[ i + 2 ];
handleVertex( iA );
handleVertex( iB );
handleVertex( iC );
}
}
this.hasTangents = true;
this.tangentsNeedUpdate = true;
},
deallocate: function () {
var index = THREE.GeometryLibrary.indexOf( this );
if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
}
};
/**
* Spline from Tween.js, slightly optimized (and trashed)
* http://sole.github.com/tween.js/examples/05_spline.html
*
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Spline = function ( points ) {
this.points = points;
var c = [], v3 = { x: 0, y: 0, z: 0 },
point, intPoint, weight, w2, w3,
pa, pb, pc, pd;
this.initFromArray = function( a ) {
this.points = [];
for ( var i = 0; i < a.length; i++ ) {
this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
}
};
this.getPoint = function ( k ) {
point = ( this.points.length - 1 ) * k;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
pa = this.points[ c[ 0 ] ];
pb = this.points[ c[ 1 ] ];
pc = this.points[ c[ 2 ] ];
pd = this.points[ c[ 3 ] ];
w2 = weight * weight;
w3 = weight * w2;
v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
return v3;
};
this.getControlPointsArray = function () {
var i, p, l = this.points.length,
coords = [];
for ( i = 0; i < l; i ++ ) {
p = this.points[ i ];
coords[ i ] = [ p.x, p.y, p.z ];
}
return coords;
};
// approximate length by summing linear segments
this.getLength = function ( nSubDivisions ) {
var i, index, nSamples, position,
point = 0, intPoint = 0, oldIntPoint = 0,
oldPosition = new THREE.Vector3(),
tmpVec = new THREE.Vector3(),
chunkLengths = [],
totalLength = 0;
// first point has 0 length
chunkLengths[ 0 ] = 0;
if ( !nSubDivisions ) nSubDivisions = 100;
nSamples = this.points.length * nSubDivisions;
oldPosition.copy( this.points[ 0 ] );
for ( i = 1; i < nSamples; i ++ ) {
index = i / nSamples;
position = this.getPoint( index );
tmpVec.copy( position );
totalLength += tmpVec.distanceTo( oldPosition );
oldPosition.copy( position );
point = ( this.points.length - 1 ) * index;
intPoint = Math.floor( point );
if ( intPoint != oldIntPoint ) {
chunkLengths[ intPoint ] = totalLength;
oldIntPoint = intPoint;
}
}
// last point ends with total length
chunkLengths[ chunkLengths.length ] = totalLength;
return { chunks: chunkLengths, total: totalLength };
};
this.reparametrizeByArcLength = function ( samplingCoef ) {
var i, j,
index, indexCurrent, indexNext,
linearDistance, realDistance,
sampling, position,
newpoints = [],
tmpVec = new THREE.Vector3(),
sl = this.getLength();
newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
for ( i = 1; i < this.points.length; i++ ) {
//tmpVec.copy( this.points[ i - 1 ] );
//linearDistance = tmpVec.distanceTo( this.points[ i ] );
realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
sampling = Math.ceil( samplingCoef * realDistance / sl.total );
indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
indexNext = i / ( this.points.length - 1 );
for ( j = 1; j < sampling - 1; j++ ) {
index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
position = this.getPoint( index );
newpoints.push( tmpVec.copy( position ).clone() );
}
newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
}
this.points = newpoints;
};
// Catmull-Rom
function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
var v0 = ( p2 - p0 ) * 0.5,
v1 = ( p3 - p1 ) * 0.5;
return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
};
};
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
*/
THREE.Camera = function () {
THREE.Object3D.call( this );
this.matrixWorldInverse = new THREE.Matrix4();
this.projectionMatrix = new THREE.Matrix4();
this.projectionMatrixInverse = new THREE.Matrix4();
};
THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
THREE.Camera.prototype.lookAt = function ( vector ) {
// TODO: Add hierarchy support.
this.matrix.lookAt( this.position, vector, this.up );
if ( this.rotationAutoUpdate === true ) {
this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
THREE.Camera.call( this );
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
this.near = ( near !== undefined ) ? near : 0.1;
this.far = ( far !== undefined ) ? far : 2000;
this.updateProjectionMatrix();
};
THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
};
/**
* @author mrdoob / http://mrdoob.com/
* @author greggman / http://games.greggman.com/
* @author zz85 / http://www.lab4games.net/zz85/blog
*/
THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
THREE.Camera.call( this );
this.fov = fov !== undefined ? fov : 50;
this.aspect = aspect !== undefined ? aspect : 1;
this.near = near !== undefined ? near : 0.1;
this.far = far !== undefined ? far : 2000;
this.updateProjectionMatrix();
};
THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
/**
* Uses Focal Length (in mm) to estimate and set FOV
* 35mm (fullframe) camera is used if frame size is not specified;
* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
*/
THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
if ( frameHeight === undefined ) frameHeight = 24;
this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
this.updateProjectionMatrix();
}
/**
* Sets an offset in a larger frustum. This is useful for multi-window or
* multi-monitor/multi-machine setups.
*
* For example, if you have 3x2 monitors and each monitor is 1920x1080 and
* the monitors are in grid like this
*
* +---+---+---+
* | A | B | C |
* +---+---+---+
* | D | E | F |
* +---+---+---+
*
* then for each monitor you would call it like this
*
* var w = 1920;
* var h = 1080;
* var fullWidth = w * 3;
* var fullHeight = h * 2;
*
* --A--
* camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
* --B--
* camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
* --C--
* camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
* --D--
* camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
* --E--
* camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
* --F--
* camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
*
* Note there is no reason monitors have to be the same size or in a grid.
*/
THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
this.fullWidth = fullWidth;
this.fullHeight = fullHeight;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.updateProjectionMatrix();
};
THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
if ( this.fullWidth ) {
var aspect = this.fullWidth / this.fullHeight;
var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
var bottom = -top;
var left = aspect * bottom;
var right = aspect * top;
var width = Math.abs( right - left );
var height = Math.abs( top - bottom );
this.projectionMatrix.makeFrustum(
left + this.x * width / this.fullWidth,
left + ( this.x + this.width ) * width / this.fullWidth,
top - ( this.y + this.height ) * height / this.fullHeight,
top - this.y * height / this.fullHeight,
this.near,
this.far
);
} else {
this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Light = function ( hex ) {
THREE.Object3D.call( this );
this.color = new THREE.Color( hex );
};
THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.AmbientLight = function ( hex ) {
THREE.Light.call( this, hex );
};
THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.DirectionalLight = function ( hex, intensity, distance ) {
THREE.Light.call( this, hex );
this.position = new THREE.Vector3( 0, 1, 0 );
this.target = new THREE.Object3D();
this.intensity = ( intensity !== undefined ) ? intensity : 1;
this.distance = ( distance !== undefined ) ? distance : 0;
this.castShadow = false;
this.onlyShadow = false;
//
this.shadowCameraNear = 50;
this.shadowCameraFar = 5000;
this.shadowCameraLeft = -500;
this.shadowCameraRight = 500;
this.shadowCameraTop = 500;
this.shadowCameraBottom = -500;
this.shadowCameraVisible = false;
this.shadowBias = 0;
this.shadowDarkness = 0.5;
this.shadowMapWidth = 512;
this.shadowMapHeight = 512;
//
this.shadowCascade = false;
this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
this.shadowCascadeCount = 2;
this.shadowCascadeBias = [ 0, 0, 0 ];
this.shadowCascadeWidth = [ 512, 512, 512 ];
this.shadowCascadeHeight = [ 512, 512, 512 ];
this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
this.shadowCascadeArray = [];
//
this.shadowMap = null;
this.shadowMapSize = null;
this.shadowCamera = null;
this.shadowMatrix = null;
};
THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
THREE.Light.call( this, skyColorHex );
this.groundColor = new THREE.Color( groundColorHex );
this.position = new THREE.Vector3( 0, 100, 0 );
this.intensity = ( intensity !== undefined ) ? intensity : 1;
};
THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.PointLight = function ( hex, intensity, distance ) {
THREE.Light.call( this, hex );
this.position = new THREE.Vector3( 0, 0, 0 );
this.intensity = ( intensity !== undefined ) ? intensity : 1;
this.distance = ( distance !== undefined ) ? distance : 0;
};
THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
THREE.Light.call( this, hex );
this.position = new THREE.Vector3( 0, 1, 0 );
this.target = new THREE.Object3D();
this.intensity = ( intensity !== undefined ) ? intensity : 1;
this.distance = ( distance !== undefined ) ? distance : 0;
this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
this.exponent = ( exponent !== undefined ) ? exponent : 10;
this.castShadow = false;
this.onlyShadow = false;
//
this.shadowCameraNear = 50;
this.shadowCameraFar = 5000;
this.shadowCameraFov = 50;
this.shadowCameraVisible = false;
this.shadowBias = 0;
this.shadowDarkness = 0.5;
this.shadowMapWidth = 512;
this.shadowMapHeight = 512;
//
this.shadowMap = null;
this.shadowMapSize = null;
this.shadowCamera = null;
this.shadowMatrix = null;
};
THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Loader = function ( showStatus ) {
this.showStatus = showStatus;
this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
this.onLoadStart = function () {};
this.onLoadProgress = function () {};
this.onLoadComplete = function () {};
};
THREE.Loader.prototype = {
constructor: THREE.Loader,
crossOrigin: 'anonymous',
addStatusElement: function () {
var e = document.createElement( "div" );
e.style.position = "absolute";
e.style.right = "0px";
e.style.top = "0px";
e.style.fontSize = "0.8em";
e.style.textAlign = "left";
e.style.background = "rgba(0,0,0,0.25)";
e.style.color = "#fff";
e.style.width = "120px";
e.style.padding = "0.5em 0.5em 0.5em 0.5em";
e.style.zIndex = 1000;
e.innerHTML = "Loading ...";
return e;
},
updateProgress: function ( progress ) {
var message = "Loaded ";
if ( progress.total ) {
message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
} else {
message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
}
this.statusDomElement.innerHTML = message;
},
extractUrlBase: function ( url ) {
var parts = url.split( '/' );
parts.pop();
return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
},
initMaterials: function ( scope, materials, texturePath ) {
scope.materials = [];
for ( var i = 0; i < materials.length; ++ i ) {
scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
}
},
hasNormals: function ( scope ) {
var m, i, il = scope.materials.length;
for( i = 0; i < il; i ++ ) {
m = scope.materials[ i ];
if ( m instanceof THREE.ShaderMaterial ) return true;
}
return false;
},
createMaterial: function ( m, texturePath ) {
var _this = this;
function is_pow2( n ) {
var l = Math.log( n ) / Math.LN2;
return Math.floor( l ) == l;
}
function nearest_pow2( n ) {
var l = Math.log( n ) / Math.LN2;
return Math.pow( 2, Math.round( l ) );
}
function load_image( where, url ) {
var image = new Image();
image.onload = function () {
if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
var width = nearest_pow2( this.width );
var height = nearest_pow2( this.height );
where.image.width = width;
where.image.height = height;
where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
} else {
where.image = this;
}
where.needsUpdate = true;
};
image.crossOrigin = _this.crossOrigin;
image.src = url;
}
function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
var fullPath = texturePath + "/" + sourceFile;
if ( isCompressed ) {
var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
where[ name ] = texture;
} else {
var texture = document.createElement( 'canvas' );
where[ name ] = new THREE.Texture( texture );
}
where[ name ].sourceFile = sourceFile;
if( repeat ) {
where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
}
if ( offset ) {
where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
}
if ( wrap ) {
var wrapMap = {
"repeat": THREE.RepeatWrapping,
"mirror": THREE.MirroredRepeatWrapping
}
if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
}
if ( anisotropy ) {
where[ name ].anisotropy = anisotropy;
}
if ( ! isCompressed ) {
load_image( where[ name ], fullPath );
}
}
function rgb2hex( rgb ) {
return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
}
// defaults
var mtype = "MeshLambertMaterial";
var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
// parameters from model file
if ( m.shading ) {
var shading = m.shading.toLowerCase();
if ( shading === "phong" ) mtype = "MeshPhongMaterial";
else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
}
if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
mpars.blending = THREE[ m.blending ];
}
if ( m.transparent !== undefined || m.opacity < 1.0 ) {
mpars.transparent = m.transparent;
}
if ( m.depthTest !== undefined ) {
mpars.depthTest = m.depthTest;
}
if ( m.depthWrite !== undefined ) {
mpars.depthWrite = m.depthWrite;
}
if ( m.visible !== undefined ) {
mpars.visible = m.visible;
}
if ( m.flipSided !== undefined ) {
mpars.side = THREE.BackSide;
}
if ( m.doubleSided !== undefined ) {
mpars.side = THREE.DoubleSide;
}
if ( m.wireframe !== undefined ) {
mpars.wireframe = m.wireframe;
}
if ( m.vertexColors !== undefined ) {
if ( m.vertexColors === "face" ) {
mpars.vertexColors = THREE.FaceColors;
} else if ( m.vertexColors ) {
mpars.vertexColors = THREE.VertexColors;
}
}
// colors
if ( m.colorDiffuse ) {
mpars.color = rgb2hex( m.colorDiffuse );
} else if ( m.DbgColor ) {
mpars.color = m.DbgColor;
}
if ( m.colorSpecular ) {
mpars.specular = rgb2hex( m.colorSpecular );
}
if ( m.colorAmbient ) {
mpars.ambient = rgb2hex( m.colorAmbient );
}
// modifiers
if ( m.transparency ) {
mpars.opacity = m.transparency;
}
if ( m.specularCoef ) {
mpars.shininess = m.specularCoef;
}
// textures
if ( m.mapDiffuse && texturePath ) {
create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
}
if ( m.mapLight && texturePath ) {
create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
}
if ( m.mapBump && texturePath ) {
create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
}
if ( m.mapNormal && texturePath ) {
create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
}
if ( m.mapSpecular && texturePath ) {
create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
}
//
if ( m.mapBumpScale ) {
mpars.bumpScale = m.mapBumpScale;
}
// special case for normal mapped material
if ( m.mapNormal ) {
var shader = THREE.ShaderUtils.lib[ "normal" ];
var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
uniforms[ "tNormal" ].value = mpars.normalMap;
if ( m.mapNormalFactor ) {
uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
}
if ( mpars.map ) {
uniforms[ "tDiffuse" ].value = mpars.map;
uniforms[ "enableDiffuse" ].value = true;
}
if ( mpars.specularMap ) {
uniforms[ "tSpecular" ].value = mpars.specularMap;
uniforms[ "enableSpecular" ].value = true;
}
if ( mpars.lightMap ) {
uniforms[ "tAO" ].value = mpars.lightMap;
uniforms[ "enableAO" ].value = true;
}
// for the moment don't handle displacement texture
uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
uniforms[ "uShininess" ].value = mpars.shininess;
if ( mpars.opacity !== undefined ) {
uniforms[ "uOpacity" ].value = mpars.opacity;
}
var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
var material = new THREE.ShaderMaterial( parameters );
} else {
var material = new THREE[ mtype ]( mpars );
}
if ( m.DbgName !== undefined ) material.name = m.DbgName;
return material;
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.BinaryLoader = function ( showStatus ) {
THREE.Loader.call( this, showStatus );
};
THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
// Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
// - binary models consist of two files: JS and BIN
// - parameters
// - url (required)
// - callback (required)
// - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
// - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
texturePath = texturePath ? texturePath : this.extractUrlBase( url );
binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
this.onLoadStart();
// #1 load JS part via web worker
this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
};
THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 || xhr.status == 0 ) {
var json = JSON.parse( xhr.responseText );
context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
} else {
console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
}
}
};
xhr.open( "GET", url, true );
xhr.send( null );
};
THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
var xhr = new XMLHttpRequest(),
url = binaryPath + "/" + json.buffers;
var length = 0;
xhr.onreadystatechange = function () {
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 || xhr.status == 0 ) {
var buffer = xhr.response;
if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
} else {
console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
}
} else if ( xhr.readyState == 3 ) {
if ( callbackProgress ) {
if ( length == 0 ) {
length = xhr.getResponseHeader( "Content-Length" );
}
callbackProgress( { total: length, loaded: xhr.responseText.length } );
}
} else if ( xhr.readyState == 2 ) {
length = xhr.getResponseHeader( "Content-Length" );
}
};
xhr.open( "GET", url, true );
xhr.responseType = "arraybuffer";
xhr.send( null );
};
// Binary AJAX parser
THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
var Model = function ( texturePath ) {
var scope = this,
currentOffset = 0,
md,
normals = [],
uvs = [],
start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
tri_size, quad_size,
len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
THREE.Geometry.call( this );
THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
md = parseMetaData( data, currentOffset );
currentOffset += md.header_bytes;
/*
md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
*/
// buffers sizes
tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
len_tri_flat = md.ntri_flat * ( tri_size );
len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
len_quad_flat = md.nquad_flat * ( quad_size );
len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
// read buffers
currentOffset += init_vertices( currentOffset );
currentOffset += init_normals( currentOffset );
currentOffset += handlePadding( md.nnormals * 3 );
currentOffset += init_uvs( currentOffset );
start_tri_flat = currentOffset;
start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
// have to first process faces with uvs
// so that face and uv indices match
init_triangles_flat_uv( start_tri_flat_uv );
init_triangles_smooth_uv( start_tri_smooth_uv );
init_quads_flat_uv( start_quad_flat_uv );
init_quads_smooth_uv( start_quad_smooth_uv );
// now we can process untextured faces
init_triangles_flat( start_tri_flat );
init_triangles_smooth( start_tri_smooth );
init_quads_flat( start_quad_flat );
init_quads_smooth( start_quad_smooth );
this.computeCentroids();
this.computeFaceNormals();
if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
function handlePadding( n ) {
return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
};
function parseMetaData( data, offset ) {
var metaData = {
'signature' :parseString( data, offset, 12 ),
'header_bytes' :parseUChar8( data, offset + 12 ),
'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
'normal_index_bytes' :parseUChar8( data, offset + 17 ),
'uv_index_bytes' :parseUChar8( data, offset + 18 ),
'material_index_bytes' :parseUChar8( data, offset + 19 ),
'nvertices' :parseUInt32( data, offset + 20 ),
'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
};
/*
console.log( "signature: " + metaData.signature );
console.log( "header_bytes: " + metaData.header_bytes );
console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
console.log( "material_index_bytes: " + metaData.material_index_bytes );
console.log( "nvertices: " + metaData.nvertices );
console.log( "nnormals: " + metaData.nnormals );
console.log( "nuvs: " + metaData.nuvs );
console.log( "ntri_flat: " + metaData.ntri_flat );
console.log( "ntri_smooth: " + metaData.ntri_smooth );
console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
console.log( "nquad_flat: " + metaData.nquad_flat );
console.log( "nquad_smooth: " + metaData.nquad_smooth );
console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
var total = metaData.header_bytes
+ metaData.nvertices * metaData.vertex_coordinate_bytes * 3
+ metaData.nnormals * metaData.normal_coordinate_bytes * 3
+ metaData.nuvs * metaData.uv_coordinate_bytes * 2
+ metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
+ metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
+ metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
+ metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
+ metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
+ metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
+ metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
+ metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
console.log( "total bytes: " + total );
*/
return metaData;
};
function parseString( data, offset, length ) {
var charArray = new Uint8Array( data, offset, length );
var text = "";
for ( var i = 0; i < length; i ++ ) {
text += String.fromCharCode( charArray[ offset + i ] );
}
return text;
};
function parseUChar8( data, offset ) {
var charArray = new Uint8Array( data, offset, 1 );
return charArray[ 0 ];
};
function parseUInt32( data, offset ) {
var intArray = new Uint32Array( data, offset, 1 );
return intArray[ 0 ];
};
function init_vertices( start ) {
var nElements = md.nvertices;
var coordArray = new Float32Array( data, start, nElements * 3 );
var i, x, y, z;
for( i = 0; i < nElements; i ++ ) {
x = coordArray[ i * 3 ];
y = coordArray[ i * 3 + 1 ];
z = coordArray[ i * 3 + 2 ];
vertex( scope, x, y, z );
}
return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
};
function init_normals( start ) {
var nElements = md.nnormals;
if ( nElements ) {
var normalArray = new Int8Array( data, start, nElements * 3 );
var i, x, y, z;
for( i = 0; i < nElements; i ++ ) {
x = normalArray[ i * 3 ];
y = normalArray[ i * 3 + 1 ];
z = normalArray[ i * 3 + 2 ];
normals.push( x/127, y/127, z/127 );
}
}
return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
};
function init_uvs( start ) {
var nElements = md.nuvs;
if ( nElements ) {
var uvArray = new Float32Array( data, start, nElements * 2 );
var i, u, v;
for( i = 0; i < nElements; i ++ ) {
u = uvArray[ i * 2 ];
v = uvArray[ i * 2 + 1 ];
uvs.push( u, v );
}
}
return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
};
function init_uvs3( nElements, offset ) {
var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
for( i = 0; i < nElements; i ++ ) {
uva = uvIndexBuffer[ i * 3 ];
uvb = uvIndexBuffer[ i * 3 + 1 ];
uvc = uvIndexBuffer[ i * 3 + 2 ];
u1 = uvs[ uva*2 ];
v1 = uvs[ uva*2 + 1 ];
u2 = uvs[ uvb*2 ];
v2 = uvs[ uvb*2 + 1 ];
u3 = uvs[ uvc*2 ];
v3 = uvs[ uvc*2 + 1 ];
uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
}
};
function init_uvs4( nElements, offset ) {
var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
for( i = 0; i < nElements; i ++ ) {
uva = uvIndexBuffer[ i * 4 ];
uvb = uvIndexBuffer[ i * 4 + 1 ];
uvc = uvIndexBuffer[ i * 4 + 2 ];
uvd = uvIndexBuffer[ i * 4 + 3 ];
u1 = uvs[ uva*2 ];
v1 = uvs[ uva*2 + 1 ];
u2 = uvs[ uvb*2 ];
v2 = uvs[ uvb*2 + 1 ];
u3 = uvs[ uvc*2 ];
v3 = uvs[ uvc*2 + 1 ];
u4 = uvs[ uvd*2 ];
v4 = uvs[ uvd*2 + 1 ];
uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
}
};
function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
var i, a, b, c, m;
var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
for( i = 0; i < nElements; i ++ ) {
a = vertexIndexBuffer[ i * 3 ];
b = vertexIndexBuffer[ i * 3 + 1 ];
c = vertexIndexBuffer[ i * 3 + 2 ];
m = materialIndexBuffer[ i ];
f3( scope, a, b, c, m );
}
};
function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
var i, a, b, c, d, m;
var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
for( i = 0; i < nElements; i ++ ) {
a = vertexIndexBuffer[ i * 4 ];
b = vertexIndexBuffer[ i * 4 + 1 ];
c = vertexIndexBuffer[ i * 4 + 2 ];
d = vertexIndexBuffer[ i * 4 + 3 ];
m = materialIndexBuffer[ i ];
f4( scope, a, b, c, d, m );
}
};
function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
var i, a, b, c, m;
var na, nb, nc;
var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
for( i = 0; i < nElements; i ++ ) {
a = vertexIndexBuffer[ i * 3 ];
b = vertexIndexBuffer[ i * 3 + 1 ];
c = vertexIndexBuffer[ i * 3 + 2 ];
na = normalIndexBuffer[ i * 3 ];
nb = normalIndexBuffer[ i * 3 + 1 ];
nc = normalIndexBuffer[ i * 3 + 2 ];
m = materialIndexBuffer[ i ];
f3n( scope, normals, a, b, c, m, na, nb, nc );
}
};
function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
var i, a, b, c, d, m;
var na, nb, nc, nd;
var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
for( i = 0; i < nElements; i ++ ) {
a = vertexIndexBuffer[ i * 4 ];
b = vertexIndexBuffer[ i * 4 + 1 ];
c = vertexIndexBuffer[ i * 4 + 2 ];
d = vertexIndexBuffer[ i * 4 + 3 ];
na = normalIndexBuffer[ i * 4 ];
nb = normalIndexBuffer[ i * 4 + 1 ];
nc = normalIndexBuffer[ i * 4 + 2 ];
nd = normalIndexBuffer[ i * 4 + 3 ];
m = materialIndexBuffer[ i ];
f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
}
};
function init_triangles_flat( start ) {
var nElements = md.ntri_flat;
if ( nElements ) {
var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
init_faces3_flat( nElements, start, offsetMaterials );
}
};
function init_triangles_flat_uv( start ) {
var nElements = md.ntri_flat_uv;
if ( nElements ) {
var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
init_faces3_flat( nElements, start, offsetMaterials );
init_uvs3( nElements, offsetUvs );
}
};
function init_triangles_smooth( start ) {
var nElements = md.ntri_smooth;
if ( nElements ) {
var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
}
};
function init_triangles_smooth_uv( start ) {
var nElements = md.ntri_smooth_uv;
if ( nElements ) {
var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
init_uvs3( nElements, offsetUvs );
}
};
function init_quads_flat( start ) {
var nElements = md.nquad_flat;
if ( nElements ) {
var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
init_faces4_flat( nElements, start, offsetMaterials );
}
};
function init_quads_flat_uv( start ) {
var nElements = md.nquad_flat_uv;
if ( nElements ) {
var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
init_faces4_flat( nElements, start, offsetMaterials );
init_uvs4( nElements, offsetUvs );
}
};
function init_quads_smooth( start ) {
var nElements = md.nquad_smooth;
if ( nElements ) {
var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
}
};
function init_quads_smooth_uv( start ) {
var nElements = md.nquad_smooth_uv;
if ( nElements ) {
var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
init_uvs4( nElements, offsetUvs );
}
};
};
function vertex ( scope, x, y, z ) {
scope.vertices.push( new THREE.Vector3( x, y, z ) );
};
function f3 ( scope, a, b, c, mi ) {
scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
};
function f4 ( scope, a, b, c, d, mi ) {
scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
};
function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
var nax = normals[ na*3 ],
nay = normals[ na*3 + 1 ],
naz = normals[ na*3 + 2 ],
nbx = normals[ nb*3 ],
nby = normals[ nb*3 + 1 ],
nbz = normals[ nb*3 + 2 ],
ncx = normals[ nc*3 ],
ncy = normals[ nc*3 + 1 ],
ncz = normals[ nc*3 + 2 ];
scope.faces.push( new THREE.Face3( a, b, c,
[new THREE.Vector3( nax, nay, naz ),
new THREE.Vector3( nbx, nby, nbz ),
new THREE.Vector3( ncx, ncy, ncz )],
null,
mi ) );
};
function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
var nax = normals[ na*3 ],
nay = normals[ na*3 + 1 ],
naz = normals[ na*3 + 2 ],
nbx = normals[ nb*3 ],
nby = normals[ nb*3 + 1 ],
nbz = normals[ nb*3 + 2 ],
ncx = normals[ nc*3 ],
ncy = normals[ nc*3 + 1 ],
ncz = normals[ nc*3 + 2 ],
ndx = normals[ nd*3 ],
ndy = normals[ nd*3 + 1 ],
ndz = normals[ nd*3 + 2 ];
scope.faces.push( new THREE.Face4( a, b, c, d,
[new THREE.Vector3( nax, nay, naz ),
new THREE.Vector3( nbx, nby, nbz ),
new THREE.Vector3( ncx, ncy, ncz ),
new THREE.Vector3( ndx, ndy, ndz )],
null,
mi ) );
};
function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
var uv = [];
uv.push( new THREE.UV( u1, v1 ) );
uv.push( new THREE.UV( u2, v2 ) );
uv.push( new THREE.UV( u3, v3 ) );
where.push( uv );
};
function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
var uv = [];
uv.push( new THREE.UV( u1, v1 ) );
uv.push( new THREE.UV( u2, v2 ) );
uv.push( new THREE.UV( u3, v3 ) );
uv.push( new THREE.UV( u4, v4 ) );
where.push( uv );
};
Model.prototype = Object.create( THREE.Geometry.prototype );
callback( new Model( texturePath ) );
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.ImageLoader = function () {
THREE.EventTarget.call( this );
this.crossOrigin = null;
};
THREE.ImageLoader.prototype = {
constructor: THREE.ImageLoader,
load: function ( url, image ) {
var scope = this;
if ( image === undefined ) image = new Image();
image.addEventListener( 'load', function () {
scope.dispatchEvent( { type: 'load', content: image } );
}, false );
image.addEventListener( 'error', function () {
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
}, false );
if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
image.src = url;
}
}
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.JSONLoader = function ( showStatus ) {
THREE.Loader.call( this, showStatus );
};
THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
var scope = this;
texturePath = texturePath ? texturePath : this.extractUrlBase( url );
this.onLoadStart();
this.loadAjaxJSON( this, url, callback, texturePath );
};
THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
var xhr = new XMLHttpRequest();
var length = 0;
xhr.onreadystatechange = function () {
if ( xhr.readyState === xhr.DONE ) {
if ( xhr.status === 200 || xhr.status === 0 ) {
if ( xhr.responseText ) {
var json = JSON.parse( xhr.responseText );
context.createModel( json, callback, texturePath );
} else {
console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
}
// in context of more complex asset initialization
// do not block on single failed file
// maybe should go even one more level up
context.onLoadComplete();
} else {
console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
}
} else if ( xhr.readyState === xhr.LOADING ) {
if ( callbackProgress ) {
if ( length === 0 ) {
length = xhr.getResponseHeader( "Content-Length" );
}
callbackProgress( { total: length, loaded: xhr.responseText.length } );
}
} else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
length = xhr.getResponseHeader( "Content-Length" );
}
};
xhr.open( "GET", url, true );
xhr.send( null );
};
THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
var scope = this,
geometry = new THREE.Geometry(),
scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
this.initMaterials( geometry, json.materials, texturePath );
parseModel( scale );
parseSkin();
parseMorphing( scale );
geometry.computeCentroids();
geometry.computeFaceNormals();
if ( this.hasNormals( geometry ) ) geometry.computeTangents();
function parseModel( scale ) {
function isBitSet( value, position ) {
return value & ( 1 << position );
}
var i, j, fi,
offset, zLength, nVertices,
colorIndex, normalIndex, uvIndex, materialIndex,
type,
isQuad,
hasMaterial,
hasFaceUv, hasFaceVertexUv,
hasFaceNormal, hasFaceVertexNormal,
hasFaceColor, hasFaceVertexColor,
vertex, face, color, normal,
uvLayer, uvs, u, v,
faces = json.faces,
vertices = json.vertices,
normals = json.normals,
colors = json.colors,
nUvLayers = 0;
// disregard empty arrays
for ( i = 0; i < json.uvs.length; i++ ) {
if ( json.uvs[ i ].length ) nUvLayers ++;
}
for ( i = 0; i < nUvLayers; i++ ) {
geometry.faceUvs[ i ] = [];
geometry.faceVertexUvs[ i ] = [];
}
offset = 0;
zLength = vertices.length;
while ( offset < zLength ) {
vertex = new THREE.Vector3();
vertex.x = vertices[ offset ++ ] * scale;
vertex.y = vertices[ offset ++ ] * scale;
vertex.z = vertices[ offset ++ ] * scale;
geometry.vertices.push( vertex );
}
offset = 0;
zLength = faces.length;
while ( offset < zLength ) {
type = faces[ offset ++ ];
isQuad = isBitSet( type, 0 );
hasMaterial = isBitSet( type, 1 );
hasFaceUv = isBitSet( type, 2 );
hasFaceVertexUv = isBitSet( type, 3 );
hasFaceNormal = isBitSet( type, 4 );
hasFaceVertexNormal = isBitSet( type, 5 );
hasFaceColor = isBitSet( type, 6 );
hasFaceVertexColor = isBitSet( type, 7 );
//console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
if ( isQuad ) {
face = new THREE.Face4();
face.a = faces[ offset ++ ];
face.b = faces[ offset ++ ];
face.c = faces[ offset ++ ];
face.d = faces[ offset ++ ];
nVertices = 4;
} else {
face = new THREE.Face3();
face.a = faces[ offset ++ ];
face.b = faces[ offset ++ ];
face.c = faces[ offset ++ ];
nVertices = 3;
}
if ( hasMaterial ) {
materialIndex = faces[ offset ++ ];
face.materialIndex = materialIndex;
}
// to get face <=> uv index correspondence
fi = geometry.faces.length;
if ( hasFaceUv ) {
for ( i = 0; i < nUvLayers; i++ ) {
uvLayer = json.uvs[ i ];
uvIndex = faces[ offset ++ ];
u = uvLayer[ uvIndex * 2 ];
v = uvLayer[ uvIndex * 2 + 1 ];
geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
}
}
if ( hasFaceVertexUv ) {
for ( i = 0; i < nUvLayers; i++ ) {
uvLayer = json.uvs[ i ];
uvs = [];
for ( j = 0; j < nVertices; j ++ ) {
uvIndex = faces[ offset ++ ];
u = uvLayer[ uvIndex * 2 ];
v = uvLayer[ uvIndex * 2 + 1 ];
uvs[ j ] = new THREE.UV( u, v );
}
geometry.faceVertexUvs[ i ][ fi ] = uvs;
}
}
if ( hasFaceNormal ) {
normalIndex = faces[ offset ++ ] * 3;
normal = new THREE.Vector3();
normal.x = normals[ normalIndex ++ ];
normal.y = normals[ normalIndex ++ ];
normal.z = normals[ normalIndex ];
face.normal = normal;
}
if ( hasFaceVertexNormal ) {
for ( i = 0; i < nVertices; i++ ) {
normalIndex = faces[ offset ++ ] * 3;
normal = new THREE.Vector3();
normal.x = normals[ normalIndex ++ ];
normal.y = normals[ normalIndex ++ ];
normal.z = normals[ normalIndex ];
face.vertexNormals.push( normal );
}
}
if ( hasFaceColor ) {
colorIndex = faces[ offset ++ ];
color = new THREE.Color( colors[ colorIndex ] );
face.color = color;
}
if ( hasFaceVertexColor ) {
for ( i = 0; i < nVertices; i++ ) {
colorIndex = faces[ offset ++ ];
color = new THREE.Color( colors[ colorIndex ] );
face.vertexColors.push( color );
}
}
geometry.faces.push( face );
}
};
function parseSkin() {
var i, l, x, y, z, w, a, b, c, d;
if ( json.skinWeights ) {
for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
x = json.skinWeights[ i ];
y = json.skinWeights[ i + 1 ];
z = 0;
w = 0;
geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
}
}
if ( json.skinIndices ) {
for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
a = json.skinIndices[ i ];
b = json.skinIndices[ i + 1 ];
c = 0;
d = 0;
geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
}
}
geometry.bones = json.bones;
geometry.animation = json.animation;
};
function parseMorphing( scale ) {
if ( json.morphTargets !== undefined ) {
var i, l, v, vl, dstVertices, srcVertices;
for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
geometry.morphTargets[ i ] = {};
geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
geometry.morphTargets[ i ].vertices = [];
dstVertices = geometry.morphTargets[ i ].vertices;
srcVertices = json.morphTargets [ i ].vertices;
for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
var vertex = new THREE.Vector3();
vertex.x = srcVertices[ v ] * scale;
vertex.y = srcVertices[ v + 1 ] * scale;
vertex.z = srcVertices[ v + 2 ] * scale;
dstVertices.push( vertex );
}
}
}
if ( json.morphColors !== undefined ) {
var i, l, c, cl, dstColors, srcColors, color;
for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
geometry.morphColors[ i ] = {};
geometry.morphColors[ i ].name = json.morphColors[ i ].name;
geometry.morphColors[ i ].colors = [];
dstColors = geometry.morphColors[ i ].colors;
srcColors = json.morphColors [ i ].colors;
for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
color = new THREE.Color( 0xffaa00 );
color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
dstColors.push( color );
}
}
}
};
callback( geometry );
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.LoadingMonitor = function () {
THREE.EventTarget.call( this );
var scope = this;
var loaded = 0;
var total = 0;
var onLoad = function ( event ) {
loaded ++;
scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
if ( loaded === total ) {
scope.dispatchEvent( { type: 'load' } );
}
};
this.add = function ( loader ) {
total ++;
loader.addEventListener( 'load', onLoad, false );
};
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.GeometryLoader = function () {
THREE.EventTarget.call( this );
this.crossOrigin = null;
this.path = null;
};
THREE.GeometryLoader.prototype = {
constructor: THREE.GeometryLoader,
load: function ( url ) {
var scope = this;
var geometry = null;
if ( scope.path === null ) {
var parts = url.split( '/' ); parts.pop();
scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
}
//
var xhr = new XMLHttpRequest();
xhr.addEventListener( 'load', function ( event ) {
if ( event.target.responseText ) {
geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
} else {
scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
}
}, false );
xhr.addEventListener( 'error', function () {
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
}, false );
xhr.open( 'GET', url, true );
xhr.send( null );
//
var monitor = new THREE.LoadingMonitor();
monitor.addEventListener( 'load', function ( event ) {
scope.dispatchEvent( { type: 'load', content: geometry } );
} );
monitor.add( xhr );
},
parse: function ( data, monitor ) {
var scope = this;
var geometry = new THREE.Geometry();
var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
// materials
if ( data.materials ) {
geometry.materials = [];
for ( var i = 0; i < data.materials.length; ++ i ) {
var m = data.materials[ i ];
function isPow2( n ) {
var l = Math.log( n ) / Math.LN2;
return Math.floor( l ) == l;
}
function nearestPow2( n ) {
var l = Math.log( n ) / Math.LN2;
return Math.pow( 2, Math.round( l ) );
}
function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
where[ name ] = new THREE.Texture();
where[ name ].sourceFile = sourceFile;
if ( repeat ) {
where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
}
if ( offset ) {
where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
}
if ( wrap ) {
var wrapMap = {
"repeat": THREE.RepeatWrapping,
"mirror": THREE.MirroredRepeatWrapping
}
if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
}
// load image
var texture = where[ name ];
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
var image = event.content;
if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
var width = nearestPow2( image.width );
var height = nearestPow2( image.height );
texture.image = document.createElement( 'canvas' );
texture.image.width = width;
texture.image.height = height;
texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
} else {
texture.image = image;
}
texture.needsUpdate = true;
} );
loader.crossOrigin = scope.crossOrigin;
loader.load( scope.path + '/' + sourceFile );
if ( monitor ) monitor.add( loader );
}
function rgb2hex( rgb ) {
return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
}
// defaults
var mtype = "MeshLambertMaterial";
var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
// parameters from model file
if ( m.shading ) {
var shading = m.shading.toLowerCase();
if ( shading === "phong" ) mtype = "MeshPhongMaterial";
else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
}
if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
mpars.blending = THREE[ m.blending ];
}
if ( m.transparent !== undefined || m.opacity < 1.0 ) {
mpars.transparent = m.transparent;
}
if ( m.depthTest !== undefined ) {
mpars.depthTest = m.depthTest;
}
if ( m.depthWrite !== undefined ) {
mpars.depthWrite = m.depthWrite;
}
if ( m.vertexColors !== undefined ) {
if ( m.vertexColors == "face" ) {
mpars.vertexColors = THREE.FaceColors;
} else if ( m.vertexColors ) {
mpars.vertexColors = THREE.VertexColors;
}
}
// colors
if ( m.colorDiffuse ) {
mpars.color = rgb2hex( m.colorDiffuse );
} else if ( m.DbgColor ) {
mpars.color = m.DbgColor;
}
if ( m.colorSpecular ) {
mpars.specular = rgb2hex( m.colorSpecular );
}
if ( m.colorAmbient ) {
mpars.ambient = rgb2hex( m.colorAmbient );
}
// modifiers
if ( m.transparency ) {
mpars.opacity = m.transparency;
}
if ( m.specularCoef ) {
mpars.shininess = m.specularCoef;
}
if ( m.visible !== undefined ) {
mpars.visible = m.visible;
}
if ( m.flipSided !== undefined ) {
mpars.side = THREE.BackSide;
}
if ( m.doubleSided !== undefined ) {
mpars.side = THREE.DoubleSide;
}
if ( m.wireframe !== undefined ) {
mpars.wireframe = m.wireframe;
}
// textures
if ( m.mapDiffuse ) {
createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
}
if ( m.mapLight ) {
createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
}
if ( m.mapBump ) {
createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
}
if ( m.mapNormal ) {
createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
}
if ( m.mapSpecular ) {
createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
}
// special case for normal mapped material
if ( m.mapNormal ) {
var shader = THREE.ShaderUtils.lib[ "normal" ];
var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
uniforms[ "tNormal" ].value = mpars.normalMap;
if ( m.mapNormalFactor ) {
uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
}
if ( mpars.map ) {
uniforms[ "tDiffuse" ].value = mpars.map;
uniforms[ "enableDiffuse" ].value = true;
}
if ( mpars.specularMap ) {
uniforms[ "tSpecular" ].value = mpars.specularMap;
uniforms[ "enableSpecular" ].value = true;
}
if ( mpars.lightMap ) {
uniforms[ "tAO" ].value = mpars.lightMap;
uniforms[ "enableAO" ].value = true;
}
// for the moment don't handle displacement texture
uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
uniforms[ "uShininess" ].value = mpars.shininess;
if ( mpars.opacity !== undefined ) {
uniforms[ "uOpacity" ].value = mpars.opacity;
}
var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
var material = new THREE.ShaderMaterial( parameters );
} else {
var material = new THREE[ mtype ]( mpars );
}
if ( m.DbgName !== undefined ) material.name = m.DbgName;
geometry.materials[ i ] = material;
}
}
// geometry
function isBitSet( value, position ) {
return value & ( 1 << position );
}
var faces = data.faces;
var vertices = data.vertices;
var normals = data.normals;
var colors = data.colors;
var nUvLayers = 0;
// disregard empty arrays
if ( data.uvs ) {
for ( var i = 0; i < data.uvs.length; i ++ ) {
if ( data.uvs[ i ].length ) nUvLayers ++;
}
}
for ( var i = 0; i < nUvLayers; i ++ ) {
geometry.faceUvs[ i ] = [];
geometry.faceVertexUvs[ i ] = [];
}
var offset = 0;
var zLength = vertices.length;
while ( offset < zLength ) {
var vertex = new THREE.Vector3();
vertex.x = vertices[ offset ++ ] * scale;
vertex.y = vertices[ offset ++ ] * scale;
vertex.z = vertices[ offset ++ ] * scale;
geometry.vertices.push( vertex );
}
offset = 0;
zLength = faces.length;
while ( offset < zLength ) {
var type = faces[ offset ++ ];
var isQuad = isBitSet( type, 0 );
var hasMaterial = isBitSet( type, 1 );
var hasFaceUv = isBitSet( type, 2 );
var hasFaceVertexUv = isBitSet( type, 3 );
var hasFaceNormal = isBitSet( type, 4 );
var hasFaceVertexNormal = isBitSet( type, 5 );
var hasFaceColor = isBitSet( type, 6 );
var hasFaceVertexColor = isBitSet( type, 7 );
// console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
if ( isQuad ) {
var face = new THREE.Face4();
face.a = faces[ offset ++ ];
face.b = faces[ offset ++ ];
face.c = faces[ offset ++ ];
face.d = faces[ offset ++ ];
var nVertices = 4;
} else {
var face = new THREE.Face3();
face.a = faces[ offset ++ ];
face.b = faces[ offset ++ ];
face.c = faces[ offset ++ ];
var nVertices = 3;
}
if ( hasMaterial ) {
var materialIndex = faces[ offset ++ ];
face.materialIndex = materialIndex;
}
// to get face <=> uv index correspondence
var fi = geometry.faces.length;
if ( hasFaceUv ) {
for ( var i = 0; i < nUvLayers; i ++ ) {
var uvLayer = data.uvs[ i ];
var uvIndex = faces[ offset ++ ];
var u = uvLayer[ uvIndex * 2 ];
var v = uvLayer[ uvIndex * 2 + 1 ];
geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
}
}
if ( hasFaceVertexUv ) {
for ( var i = 0; i < nUvLayers; i ++ ) {
var uvLayer = data.uvs[ i ];
var uvs = [];
for ( var j = 0; j < nVertices; j ++ ) {
var uvIndex = faces[ offset ++ ];
var u = uvLayer[ uvIndex * 2 ];
var v = uvLayer[ uvIndex * 2 + 1 ];
uvs[ j ] = new THREE.UV( u, v );
}
geometry.faceVertexUvs[ i ][ fi ] = uvs;
}
}
if ( hasFaceNormal ) {
var normalIndex = faces[ offset ++ ] * 3;
var normal = new THREE.Vector3();
normal.x = normals[ normalIndex ++ ];
normal.y = normals[ normalIndex ++ ];
normal.z = normals[ normalIndex ];
face.normal = normal;
}
if ( hasFaceVertexNormal ) {
for ( i = 0; i < nVertices; i ++ ) {
var normalIndex = faces[ offset ++ ] * 3;
var normal = new THREE.Vector3();
normal.x = normals[ normalIndex ++ ];
normal.y = normals[ normalIndex ++ ];
normal.z = normals[ normalIndex ];
face.vertexNormals.push( normal );
}
}
if ( hasFaceColor ) {
var colorIndex = faces[ offset ++ ];
face.color = new THREE.Color( colors[ colorIndex ] );
}
if ( hasFaceVertexColor ) {
for ( var i = 0; i < nVertices; i ++ ) {
var colorIndex = faces[ offset ++ ];
face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
}
}
geometry.faces.push( face );
}
// skin
if ( data.skinWeights ) {
for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
var x = data.skinWeights[ i ];
var y = data.skinWeights[ i + 1 ];
var z = 0;
var w = 0;
geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
}
}
if ( data.skinIndices ) {
for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
var a = data.skinIndices[ i ];
var b = data.skinIndices[ i + 1 ];
var c = 0;
var d = 0;
geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
}
}
geometry.bones = data.bones;
geometry.animation = data.animation;
// morphing
if ( data.morphTargets ) {
for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
geometry.morphTargets[ i ] = {};
geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
geometry.morphTargets[ i ].vertices = [];
var dstVertices = geometry.morphTargets[ i ].vertices;
var srcVertices = data.morphTargets [ i ].vertices;
for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
var vertex = new THREE.Vector3();
vertex.x = srcVertices[ v ] * scale;
vertex.y = srcVertices[ v + 1 ] * scale;
vertex.z = srcVertices[ v + 2 ] * scale;
dstVertices.push( vertex );
}
}
}
if ( data.morphColors ) {
for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
geometry.morphColors[ i ] = {};
geometry.morphColors[ i ].name = data.morphColors[ i ].name;
geometry.morphColors[ i ].colors = [];
var dstColors = geometry.morphColors[ i ].colors;
var srcColors = data.morphColors [ i ].colors;
for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
var color = new THREE.Color( 0xffaa00 );
color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
dstColors.push( color );
}
}
}
geometry.computeCentroids();
geometry.computeFaceNormals();
return geometry;
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.SceneLoader = function () {
this.onLoadStart = function () {};
this.onLoadProgress = function() {};
this.onLoadComplete = function () {};
this.callbackSync = function () {};
this.callbackProgress = function () {};
this.geometryHandlerMap = {};
this.addGeometryHandler( "ascii", THREE.JSONLoader );
this.addGeometryHandler( "binary", THREE.BinaryLoader );
};
THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
var scope = this;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if ( xhr.readyState === 4 ) {
if ( xhr.status === 200 || xhr.status === 0 ) {
var json = JSON.parse( xhr.responseText );
scope.parse( json, callbackFinished, url );
} else {
console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
}
}
};
xhr.open( "GET", url, true );
xhr.send( null );
};
THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
};
THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
var scope = this;
var urlBase = THREE.Loader.prototype.extractUrlBase( url );
var dg, dm, dl, dc, df, dt,
g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
geometry, material, camera, fog,
texture, images,
light,
counter_models, counter_textures,
total_models, total_textures,
result;
var data = json;
// async geometry loaders
for ( var typeID in this.geometryHandlerMap ) {
var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
}
counter_models = 0;
counter_textures = 0;
result = {
scene: new THREE.Scene(),
geometries: {},
materials: {},
textures: {},
objects: {},
cameras: {},
lights: {},
fogs: {},
empties: {}
};
if ( data.transform ) {
var position = data.transform.position,
rotation = data.transform.rotation,
scale = data.transform.scale;
if ( position )
result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
if ( rotation )
result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
if ( scale )
result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
if ( position || rotation || scale ) {
result.scene.updateMatrix();
result.scene.updateMatrixWorld();
}
}
function get_url( source_url, url_type ) {
if ( url_type == "relativeToHTML" ) {
return source_url;
} else {
return urlBase + "/" + source_url;
}
};
// toplevel loader function, delegates to handle_children
function handle_objects() {
handle_children( result.scene, data.objects );
}
// handle all the children from the loaded json and attach them to given parent
function handle_children( parent, children ) {
for ( var dd in children ) {
// check by id if child has already been handled,
// if not, create new object
if ( result.objects[ dd ] === undefined ) {
var o = children[ dd ];
var object = null;
if ( o.geometry !== undefined ) {
geometry = result.geometries[ o.geometry ];
// geometry already loaded
if ( geometry ) {
var hasNormals = false;
// not anymore support for multiple materials
// shouldn't really be array
material = result.materials[ o.materials[ 0 ] ];
hasNormals = material instanceof THREE.ShaderMaterial;
if ( hasNormals ) {
geometry.computeTangents();
}
p = o.position;
r = o.rotation;
q = o.quaternion;
s = o.scale;
m = o.matrix;
// turn off quaternions, for the moment
q = 0;
if ( o.materials.length === 0 ) {
material = new THREE.MeshFaceMaterial();
}
// dirty hack to handle meshes with multiple materials
// just use face materials defined in model
if ( o.materials.length > 1 ) {
material = new THREE.MeshFaceMaterial();
}
if ( o.morph ) {
object = new THREE.MorphAnimMesh( geometry, material );
if ( o.duration !== undefined ) {
object.duration = o.duration;
}
if ( o.time !== undefined ) {
object.time = o.time;
}
if ( o.mirroredLoop !== undefined ) {
object.mirroredLoop = o.mirroredLoop;
}
if ( material.morphNormals ) {
geometry.computeMorphNormals();
}
} else {
object = new THREE.Mesh( geometry, material );
}
object.name = dd;
if ( m ) {
object.matrixAutoUpdate = false;
object.matrix.set(
m[0], m[1], m[2], m[3],
m[4], m[5], m[6], m[7],
m[8], m[9], m[10], m[11],
m[12], m[13], m[14], m[15]
);
} else {
object.position.set( p[0], p[1], p[2] );
if ( q ) {
object.quaternion.set( q[0], q[1], q[2], q[3] );
object.useQuaternion = true;
} else {
object.rotation.set( r[0], r[1], r[2] );
}
object.scale.set( s[0], s[1], s[2] );
}
object.visible = o.visible;
object.castShadow = o.castShadow;
object.receiveShadow = o.receiveShadow;
parent.add( object );
result.objects[ dd ] = object;
}
// pure Object3D
} else {
p = o.position;
r = o.rotation;
q = o.quaternion;
s = o.scale;
// turn off quaternions, for the moment
q = 0;
object = new THREE.Object3D();
object.name = dd;
object.position.set( p[0], p[1], p[2] );
if ( q ) {
object.quaternion.set( q[0], q[1], q[2], q[3] );
object.useQuaternion = true;
} else {
object.rotation.set( r[0], r[1], r[2] );
}
object.scale.set( s[0], s[1], s[2] );
object.visible = ( o.visible !== undefined ) ? o.visible : false;
parent.add( object );
result.objects[ dd ] = object;
result.empties[ dd ] = object;
}
if ( object ) {
if ( o.properties !== undefined ) {
for ( var key in o.properties ) {
var value = o.properties[ key ];
object.properties[ key ] = value;
}
}
if ( o.children !== undefined ) {
handle_children( object, o.children );
}
}
}
}
};
function handle_mesh( geo, id ) {
result.geometries[ id ] = geo;
handle_objects();
};
function create_callback( id ) {
return function( geo ) {
handle_mesh( geo, id );
counter_models -= 1;
scope.onLoadComplete();
async_callback_gate();
}
};
function create_callback_embed( id ) {
return function( geo ) {
result.geometries[ id ] = geo;
}
};
function async_callback_gate() {
var progress = {
totalModels : total_models,
totalTextures : total_textures,
loadedModels : total_models - counter_models,
loadedTextures : total_textures - counter_textures
};
scope.callbackProgress( progress, result );
scope.onLoadProgress();
if ( counter_models === 0 && counter_textures === 0 ) {
callbackFinished( result );
}
};
var callbackTexture = function ( count ) {
counter_textures -= count;
async_callback_gate();
scope.onLoadComplete();
};
// must use this instead of just directly calling callbackTexture
// because of closure in the calling context loop
var generateTextureCallback = function ( count ) {
return function() {
callbackTexture( count );
};
};
// first go synchronous elements
// cameras
for( dc in data.cameras ) {
c = data.cameras[ dc ];
if ( c.type === "perspective" ) {
camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
} else if ( c.type === "ortho" ) {
camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
}
p = c.position;
t = c.target;
u = c.up;
camera.position.set( p[0], p[1], p[2] );
camera.target = new THREE.Vector3( t[0], t[1], t[2] );
if ( u ) camera.up.set( u[0], u[1], u[2] );
result.cameras[ dc ] = camera;
}
// lights
var hex, intensity;
for ( dl in data.lights ) {
l = data.lights[ dl ];
hex = ( l.color !== undefined ) ? l.color : 0xffffff;
intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
if ( l.type === "directional" ) {
p = l.direction;
light = new THREE.DirectionalLight( hex, intensity );
light.position.set( p[0], p[1], p[2] );
light.position.normalize();
} else if ( l.type === "point" ) {
p = l.position;
d = l.distance;
light = new THREE.PointLight( hex, intensity, d );
light.position.set( p[0], p[1], p[2] );
} else if ( l.type === "ambient" ) {
light = new THREE.AmbientLight( hex );
}
result.scene.add( light );
result.lights[ dl ] = light;
}
// fogs
for( df in data.fogs ) {
f = data.fogs[ df ];
if ( f.type === "linear" ) {
fog = new THREE.Fog( 0x000000, f.near, f.far );
} else if ( f.type === "exp2" ) {
fog = new THREE.FogExp2( 0x000000, f.density );
}
c = f.color;
fog.color.setRGB( c[0], c[1], c[2] );
result.fogs[ df ] = fog;
}
// defaults
if ( result.cameras && data.defaults.camera ) {
result.currentCamera = result.cameras[ data.defaults.camera ];
}
if ( result.fogs && data.defaults.fog ) {
result.scene.fog = result.fogs[ data.defaults.fog ];
}
c = data.defaults.bgcolor;
result.bgColor = new THREE.Color();
result.bgColor.setRGB( c[0], c[1], c[2] );
result.bgColorAlpha = data.defaults.bgalpha;
// now come potentially asynchronous elements
// geometries
// count how many models will be loaded asynchronously
for( dg in data.geometries ) {
g = data.geometries[ dg ];
if ( g.type in this.geometryHandlerMap ) {
counter_models += 1;
scope.onLoadStart();
}
}
total_models = counter_models;
for ( dg in data.geometries ) {
g = data.geometries[ dg ];
if ( g.type === "cube" ) {
geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
result.geometries[ dg ] = geometry;
} else if ( g.type === "plane" ) {
geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
result.geometries[ dg ] = geometry;
} else if ( g.type === "sphere" ) {
geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
result.geometries[ dg ] = geometry;
} else if ( g.type === "cylinder" ) {
geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
result.geometries[ dg ] = geometry;
} else if ( g.type === "torus" ) {
geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
result.geometries[ dg ] = geometry;
} else if ( g.type === "icosahedron" ) {
geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
result.geometries[ dg ] = geometry;
} else if ( g.type in this.geometryHandlerMap ) {
var loaderParameters = {};
for ( var parType in g ) {
if ( parType !== "type" && parType !== "url" ) {
loaderParameters[ parType ] = g[ parType ];
}
}
var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
loader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ), loaderParameters );
} else if ( g.type === "embedded" ) {
var modelJson = data.embeds[ g.id ],
texture_path = "";
// pass metadata along to jsonLoader so it knows the format version
modelJson.metadata = data.metadata;
if ( modelJson ) {
var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
}
}
}
// textures
// count how many textures will be loaded asynchronously
for( dt in data.textures ) {
tt = data.textures[ dt ];
if( tt.url instanceof Array ) {
counter_textures += tt.url.length;
for( var n = 0; n < tt.url.length; n ++ ) {
scope.onLoadStart();
}
} else {
counter_textures += 1;
scope.onLoadStart();
}
}
total_textures = counter_textures;
for ( dt in data.textures ) {
tt = data.textures[ dt ];
if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
tt.mapping = new THREE[ tt.mapping ]();
}
if ( tt.url instanceof Array ) {
var count = tt.url.length;
var url_array = [];
for( var i = 0; i < count; i ++ ) {
url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
}
var isCompressed = url_array[ 0 ].endsWith( ".dds" );
if ( isCompressed ) {
texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
} else {
texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
}
} else {
var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
var fullUrl = get_url( tt.url, data.urlBaseType );
var textureCallback = generateTextureCallback( 1 );
if ( isCompressed ) {
texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
} else {
texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
}
if ( THREE[ tt.minFilter ] !== undefined )
texture.minFilter = THREE[ tt.minFilter ];
if ( THREE[ tt.magFilter ] !== undefined )
texture.magFilter = THREE[ tt.magFilter ];
if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
if ( tt.repeat ) {
texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
}
if ( tt.offset ) {
texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
}
// handle wrap after repeat so that default repeat can be overriden
if ( tt.wrap ) {
var wrapMap = {
"repeat" : THREE.RepeatWrapping,
"mirror" : THREE.MirroredRepeatWrapping
}
if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
}
}
result.textures[ dt ] = texture;
}
// materials
for ( dm in data.materials ) {
m = data.materials[ dm ];
for ( pp in m.parameters ) {
if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
} else if ( pp === "shading" ) {
m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
} else if ( pp === "side" ) {
if ( m.parameters[ pp ] == "double" ) {
m.parameters[ pp ] = THREE.DoubleSide;
} else if ( m.parameters[ pp ] == "back" ) {
m.parameters[ pp ] = THREE.BackSide;
} else {
m.parameters[ pp ] = THREE.FrontSide;
}
} else if ( pp === "blending" ) {
m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
} else if ( pp === "combine" ) {
m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
} else if ( pp === "vertexColors" ) {
if ( m.parameters[ pp ] == "face" ) {
m.parameters[ pp ] = THREE.FaceColors;
// default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
} else if ( m.parameters[ pp ] ) {
m.parameters[ pp ] = THREE.VertexColors;
}
} else if ( pp === "wrapRGB" ) {
var v3 = m.parameters[ pp ];
m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
}
}
if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
m.parameters.transparent = true;
}
if ( m.parameters.normalMap ) {
var shader = THREE.ShaderUtils.lib[ "normal" ];
var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
var diffuse = m.parameters.color;
var specular = m.parameters.specular;
var ambient = m.parameters.ambient;
var shininess = m.parameters.shininess;
uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
if ( m.parameters.normalScale ) {
uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
}
if ( m.parameters.map ) {
uniforms[ "tDiffuse" ].value = m.parameters.map;
uniforms[ "enableDiffuse" ].value = true;
}
if ( m.parameters.envMap ) {
uniforms[ "tCube" ].value = m.parameters.envMap;
uniforms[ "enableReflection" ].value = true;
uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
}
if ( m.parameters.lightMap ) {
uniforms[ "tAO" ].value = m.parameters.lightMap;
uniforms[ "enableAO" ].value = true;
}
if ( m.parameters.specularMap ) {
uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
uniforms[ "enableSpecular" ].value = true;
}
if ( m.parameters.displacementMap ) {
uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
uniforms[ "enableDisplacement" ].value = true;
uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
}
uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
uniforms[ "uSpecularColor" ].value.setHex( specular );
uniforms[ "uAmbientColor" ].value.setHex( ambient );
uniforms[ "uShininess" ].value = shininess;
if ( m.parameters.opacity ) {
uniforms[ "uOpacity" ].value = m.parameters.opacity;
}
var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
material = new THREE.ShaderMaterial( parameters );
} else {
material = new THREE[ m.type ]( m.parameters );
}
result.materials[ dm ] = material;
}
// objects ( synchronous init of procedural primitives )
handle_objects();
// synchronous callback
scope.callbackSync( result );
// just in case there are no async elements
async_callback_gate();
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.TextureLoader = function () {
THREE.EventTarget.call( this );
this.crossOrigin = null;
};
THREE.TextureLoader.prototype = {
constructor: THREE.TextureLoader,
load: function ( url ) {
var scope = this;
var image = new Image();
image.addEventListener( 'load', function () {
var texture = new THREE.Texture( image );
texture.needsUpdate = true;
scope.dispatchEvent( { type: 'load', content: texture } );
}, false );
image.addEventListener( 'error', function () {
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
}, false );
if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
image.src = url;
}
}
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Material = function () {
THREE.MaterialLibrary.push( this );
this.id = THREE.MaterialIdCount ++;
this.name = '';
this.side = THREE.FrontSide;
this.opacity = 1;
this.transparent = false;
this.blending = THREE.NormalBlending;
this.blendSrc = THREE.SrcAlphaFactor;
this.blendDst = THREE.OneMinusSrcAlphaFactor;
this.blendEquation = THREE.AddEquation;
this.depthTest = true;
this.depthWrite = true;
this.polygonOffset = false;
this.polygonOffsetFactor = 0;
this.polygonOffsetUnits = 0;
this.alphaTest = 0;
this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
this.visible = true;
this.needsUpdate = true;
};
THREE.Material.prototype.setValues = function ( values ) {
if ( values === undefined ) return;
for ( var key in values ) {
var newValue = values[ key ];
if ( newValue === undefined ) {
console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
continue;
}
if ( key in this ) {
var currentValue = this[ key ];
if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
currentValue.copy( newValue );
} else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
currentValue.setHex( newValue );
} else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
currentValue.copy( newValue );
} else {
this[ key ] = newValue;
}
}
}
};
THREE.Material.prototype.clone = function ( material ) {
if ( material === undefined ) material = new THREE.Material();
material.name = this.name;
material.side = this.side;
material.opacity = this.opacity;
material.transparent = this.transparent;
material.blending = this.blending;
material.blendSrc = this.blendSrc;
material.blendDst = this.blendDst;
material.blendEquation = this.blendEquation;
material.depthTest = this.depthTest;
material.depthWrite = this.depthWrite;
material.polygonOffset = this.polygonOffset;
material.polygonOffsetFactor = this.polygonOffsetFactor;
material.polygonOffsetUnits = this.polygonOffsetUnits;
material.alphaTest = this.alphaTest;
material.overdraw = this.overdraw;
material.visible = this.visible;
return material;
};
THREE.Material.prototype.deallocate = function () {
var index = THREE.MaterialLibrary.indexOf( this );
if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
};
THREE.MaterialIdCount = 0;
THREE.MaterialLibrary = [];
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
*
* blending: THREE.NormalBlending,
* depthTest: <bool>,
*
* linewidth: <float>,
* linecap: "round",
* linejoin: "round",
*
* vertexColors: <bool>
*
* fog: <bool>
* }
*/
THREE.LineBasicMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff );
this.linewidth = 1;
this.linecap = 'round';
this.linejoin = 'round';
this.vertexColors = false;
this.fog = true;
this.setValues( parameters );
};
THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.LineBasicMaterial.prototype.clone = function () {
var material = new THREE.LineBasicMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.linewidth = this.linewidth;
material.linecap = this.linecap;
material.linejoin = this.linejoin;
material.vertexColors = this.vertexColors;
material.fog = this.fog;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
*
* specularMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
*
* skinning: <bool>,
* morphTargets: <bool>,
*
* fog: <bool>
* }
*/
THREE.MeshBasicMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff ); // emissive
this.map = null;
this.lightMap = null;
this.specularMap = null;
this.envMap = null;
this.combine = THREE.MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.fog = true;
this.shading = THREE.SmoothShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.vertexColors = THREE.NoColors;
this.skinning = false;
this.morphTargets = false;
this.setValues( parameters );
};
THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshBasicMaterial.prototype.clone = function () {
var material = new THREE.MeshBasicMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.map = this.map;
material.lightMap = this.lightMap;
material.specularMap = this.specularMap;
material.envMap = this.envMap;
material.combine = this.combine;
material.reflectivity = this.reflectivity;
material.refractionRatio = this.refractionRatio;
material.fog = this.fog;
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
material.wireframeLinecap = this.wireframeLinecap;
material.wireframeLinejoin = this.wireframeLinejoin;
material.vertexColors = this.vertexColors;
material.skinning = this.skinning;
material.morphTargets = this.morphTargets;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* ambient: <hex>,
* emissive: <hex>,
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
*
* specularMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>,
*
* fog: <bool>
* }
*/
THREE.MeshLambertMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff ); // diffuse
this.ambient = new THREE.Color( 0xffffff );
this.emissive = new THREE.Color( 0x000000 );
this.wrapAround = false;
this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
this.map = null;
this.lightMap = null;
this.specularMap = null;
this.envMap = null;
this.combine = THREE.MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.fog = true;
this.shading = THREE.SmoothShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.vertexColors = THREE.NoColors;
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
};
THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshLambertMaterial.prototype.clone = function () {
var material = new THREE.MeshLambertMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.ambient.copy( this.ambient );
material.emissive.copy( this.emissive );
material.wrapAround = this.wrapAround;
material.wrapRGB.copy( this.wrapRGB );
material.map = this.map;
material.lightMap = this.lightMap;
material.specularMap = this.specularMap;
material.envMap = this.envMap;
material.combine = this.combine;
material.reflectivity = this.reflectivity;
material.refractionRatio = this.refractionRatio;
material.fog = this.fog;
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
material.wireframeLinecap = this.wireframeLinecap;
material.wireframeLinejoin = this.wireframeLinejoin;
material.vertexColors = this.vertexColors;
material.skinning = this.skinning;
material.morphTargets = this.morphTargets;
material.morphNormals = this.morphNormals;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* ambient: <hex>,
* emissive: <hex>,
* specular: <hex>,
* shininess: <float>,
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
*
* bumpMap: new THREE.Texture( <Image> ),
* bumpScale: <float>,
*
* normalMap: new THREE.Texture( <Image> ),
* normalScale: <Vector2>,
*
* specularMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>,
*
* fog: <bool>
* }
*/
THREE.MeshPhongMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff ); // diffuse
this.ambient = new THREE.Color( 0xffffff );
this.emissive = new THREE.Color( 0x000000 );
this.specular = new THREE.Color( 0x111111 );
this.shininess = 30;
this.metal = false;
this.perPixel = false;
this.wrapAround = false;
this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
this.map = null;
this.lightMap = null;
this.bumpMap = null;
this.bumpScale = 1;
this.normalMap = null;
this.normalScale = new THREE.Vector2( 1, 1 );
this.specularMap = null;
this.envMap = null;
this.combine = THREE.MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.fog = true;
this.shading = THREE.SmoothShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.vertexColors = THREE.NoColors;
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
};
THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshPhongMaterial.prototype.clone = function () {
var material = new THREE.MeshPhongMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.ambient.copy( this.ambient );
material.emissive.copy( this.emissive );
material.specular.copy( this.specular );
material.shininess = this.shininess;
material.metal = this.metal;
material.perPixel = this.perPixel;
material.wrapAround = this.wrapAround;
material.wrapRGB.copy( this.wrapRGB );
material.map = this.map;
material.lightMap = this.lightMap;
material.bumpMap = this.bumpMap;
material.bumpScale = this.bumpScale;
material.normalMap = this.normalMap;
material.normalScale.copy( this.normalScale );
material.specularMap = this.specularMap;
material.envMap = this.envMap;
material.combine = this.combine;
material.reflectivity = this.reflectivity;
material.refractionRatio = this.refractionRatio;
material.fog = this.fog;
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
material.wireframeLinecap = this.wireframeLinecap;
material.wireframeLinejoin = this.wireframeLinejoin;
material.vertexColors = this.vertexColors;
material.skinning = this.skinning;
material.morphTargets = this.morphTargets;
material.morphNormals = this.morphNormals;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* opacity: <float>,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* wireframe: <boolean>,
* wireframeLinewidth: <float>
* }
*/
THREE.MeshDepthMaterial = function ( parameters ) {
THREE.Material.call( this );
this.wireframe = false;
this.wireframeLinewidth = 1;
this.setValues( parameters );
};
THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshDepthMaterial.prototype.clone = function () {
var material = new THREE.LineBasicMaterial();
THREE.Material.prototype.clone.call( this, material );
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
*
* parameters = {
* opacity: <float>,
* shading: THREE.FlatShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* wireframe: <boolean>,
* wireframeLinewidth: <float>
* }
*/
THREE.MeshNormalMaterial = function ( parameters ) {
THREE.Material.call( this, parameters );
this.shading = THREE.FlatShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.setValues( parameters );
};
THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshNormalMaterial.prototype.clone = function () {
var material = new THREE.MeshNormalMaterial();
THREE.Material.prototype.clone.call( this, material );
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.MeshFaceMaterial = function () {};
THREE.MeshFaceMaterial.prototype.clone = function () {
return new THREE.MeshFaceMaterial();
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
* map: new THREE.Texture( <Image> ),
*
* size: <float>,
*
* blending: THREE.NormalBlending,
* depthTest: <bool>,
*
* vertexColors: <bool>,
*
* fog: <bool>
* }
*/
THREE.ParticleBasicMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff );
this.map = null;
this.size = 1;
this.sizeAttenuation = true;
this.vertexColors = false;
this.fog = true;
this.setValues( parameters );
};
THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.ParticleBasicMaterial.prototype.clone = function () {
var material = new THREE.ParticleBasicMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.map = this.map;
material.size = this.size;
material.sizeAttenuation = this.sizeAttenuation;
material.vertexColors = this.vertexColors;
material.fog = this.fog;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
*
* parameters = {
* color: <hex>,
* program: <function>,
* opacity: <float>,
* blending: THREE.NormalBlending
* }
*/
THREE.ParticleCanvasMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff );
this.program = function ( context, color ) {};
this.setValues( parameters );
};
THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.ParticleCanvasMaterial.prototype.clone = function () {
var material = new THREE.ParticleCanvasMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.program = this.program;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.ParticleDOMMaterial = function ( element ) {
this.element = element;
};
THREE.ParticleDOMMaterial.prototype.clone = function(){
return new THREE.ParticleDOMMaterial( this.element );
};
/**
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* fragmentShader: <string>,
* vertexShader: <string>,
*
* uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
*
* defines: { "label" : "value" },
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* lights: <bool>,
*
* vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>,
*
* fog: <bool>
* }
*/
THREE.ShaderMaterial = function ( parameters ) {
THREE.Material.call( this );
this.fragmentShader = "void main() {}";
this.vertexShader = "void main() {}";
this.uniforms = {};
this.defines = {};
this.attributes = null;
this.shading = THREE.SmoothShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.fog = false; // set to use scene fog
this.lights = false; // set to use scene lights
this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
this.skinning = false; // set to use skinning attribute streams
this.morphTargets = false; // set to use morph targets
this.morphNormals = false; // set to use morph normals
this.setValues( parameters );
};
THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.ShaderMaterial.prototype.clone = function () {
var material = new THREE.ShaderMaterial();
THREE.Material.prototype.clone.call( this, material );
material.fragmentShader = this.fragmentShader;
material.vertexShader = this.vertexShader;
material.uniforms = this.uniforms;
material.attributes = this.attributes;
material.defines = this.defines;
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
material.fog = this.fog;
material.lights = this.lights;
material.vertexColors = this.vertexColors;
material.skinning = this.skinning;
material.morphTargets = this.morphTargets;
material.morphNormals = this.morphNormals;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author szimek / https://github.com/szimek/
*/
THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
THREE.TextureLibrary.push( this );
this.id = THREE.TextureIdCount ++;
this.image = image;
this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
this.format = format !== undefined ? format : THREE.RGBAFormat;
this.type = type !== undefined ? type : THREE.UnsignedByteType;
this.offset = new THREE.Vector2( 0, 0 );
this.repeat = new THREE.Vector2( 1, 1 );
this.generateMipmaps = true;
this.premultiplyAlpha = false;
this.flipY = true;
this.needsUpdate = false;
this.onUpdate = null;
};
THREE.Texture.prototype = {
constructor: THREE.Texture,
clone: function () {
var texture = new THREE.Texture();
texture.image = this.image;
texture.mapping = this.mapping;
texture.wrapS = this.wrapS;
texture.wrapT = this.wrapT;
texture.magFilter = this.magFilter;
texture.minFilter = this.minFilter;
texture.anisotropy = this.anisotropy;
texture.format = this.format;
texture.type = this.type;
texture.offset.copy( this.offset );
texture.repeat.copy( this.repeat );
texture.generateMipmaps = this.generateMipmaps;
texture.premultiplyAlpha = this.premultiplyAlpha;
texture.flipY = this.flipY;
return texture;
},
deallocate: function () {
var index = THREE.TextureLibrary.indexOf( this );
if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
}
};
THREE.TextureIdCount = 0;
THREE.TextureLibrary = [];
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
this.image = { width: width, height: height };
this.mipmaps = mipmaps;
};
THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
THREE.CompressedTexture.prototype.clone = function () {
var texture = new THREE.CompressedTexture();
texture.image = this.image;
texture.mipmaps = this.mipmaps;
texture.format = this.format;
texture.type = this.type;
texture.mapping = this.mapping;
texture.wrapS = this.wrapS;
texture.wrapT = this.wrapT;
texture.magFilter = this.magFilter;
texture.minFilter = this.minFilter;
texture.anisotropy = this.anisotropy;
texture.offset.copy( this.offset );
texture.repeat.copy( this.repeat );
return texture;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
this.image = { data: data, width: width, height: height };
};
THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
THREE.DataTexture.prototype.clone = function () {
var clonedTexture = new THREE.DataTexture( this.image.data, this.image.width, this.image.height, this.format, this.type, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter );
clonedTexture.offset.copy( this.offset );
clonedTexture.repeat.copy( this.repeat );
return clonedTexture;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Particle = function ( material ) {
THREE.Object3D.call( this );
this.material = material;
};
THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
THREE.Particle.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Particle( this.material );
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ParticleSystem = function ( geometry, material ) {
THREE.Object3D.call( this );
this.geometry = geometry;
this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
this.sortParticles = false;
if ( this.geometry ) {
// calc bound radius
if( this.geometry.boundingSphere === null ) {
this.geometry.computeBoundingSphere();
}
this.boundRadius = geometry.boundingSphere.radius;
}
this.frustumCulled = false;
};
THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
THREE.ParticleSystem.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
object.sortParticles = this.sortParticles;
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Line = function ( geometry, material, type ) {
THREE.Object3D.call( this );
this.geometry = geometry;
this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
this.type = ( type !== undefined ) ? type : THREE.LineStrip;
if ( this.geometry ) {
if ( ! this.geometry.boundingSphere ) {
this.geometry.computeBoundingSphere();
}
}
};
THREE.LineStrip = 0;
THREE.LinePieces = 1;
THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
THREE.Line.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
*/
THREE.Mesh = function ( geometry, material ) {
THREE.Object3D.call( this );
this.geometry = geometry;
this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
if ( this.geometry ) {
// calc bound radius
if ( this.geometry.boundingSphere === null ) {
this.geometry.computeBoundingSphere();
}
this.boundRadius = geometry.boundingSphere.radius;
// setup morph targets
if ( this.geometry.morphTargets.length ) {
this.morphTargetBase = -1;
this.morphTargetForcedOrder = [];
this.morphTargetInfluences = [];
this.morphTargetDictionary = {};
for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
this.morphTargetInfluences.push( 0 );
this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
}
}
}
}
THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
if ( this.morphTargetDictionary[ name ] !== undefined ) {
return this.morphTargetDictionary[ name ];
}
console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
return 0;
};
THREE.Mesh.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Bone = function( belongsToSkin ) {
THREE.Object3D.call( this );
this.skin = belongsToSkin;
this.skinMatrix = new THREE.Matrix4();
};
THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
// update local
if ( this.matrixAutoUpdate ) {
forceUpdate |= this.updateMatrix();
}
// update skin matrix
if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
if( parentSkinMatrix ) {
this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
} else {
this.skinMatrix.copy( this.matrix );
}
this.matrixWorldNeedsUpdate = false;
forceUpdate = true;
}
// update children
var child, i, l = this.children.length;
for ( i = 0; i < l; i ++ ) {
this.children[ i ].update( this.skinMatrix, forceUpdate );
}
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
THREE.Mesh.call( this, geometry, material );
//
this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
// init bones
this.identityMatrix = new THREE.Matrix4();
this.bones = [];
this.boneMatrices = [];
var b, bone, gbone, p, q, s;
if ( this.geometry.bones !== undefined ) {
for ( b = 0; b < this.geometry.bones.length; b ++ ) {
gbone = this.geometry.bones[ b ];
p = gbone.pos;
q = gbone.rotq;
s = gbone.scl;
bone = this.addBone();
bone.name = gbone.name;
bone.position.set( p[0], p[1], p[2] );
bone.quaternion.set( q[0], q[1], q[2], q[3] );
bone.useQuaternion = true;
if ( s !== undefined ) {
bone.scale.set( s[0], s[1], s[2] );
} else {
bone.scale.set( 1, 1, 1 );
}
}
for ( b = 0; b < this.bones.length; b ++ ) {
gbone = this.geometry.bones[ b ];
bone = this.bones[ b ];
if ( gbone.parent === -1 ) {
this.add( bone );
} else {
this.bones[ gbone.parent ].add( bone );
}
}
//
var nBones = this.bones.length;
if ( this.useVertexTexture ) {
// layout (1 matrix = 4 pixels)
// RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
// with 8x8 pixel texture max 16 bones (8 * 8 / 4)
// 16x16 pixel texture max 64 bones (16 * 16 / 4)
// 32x32 pixel texture max 256 bones (32 * 32 / 4)
// 64x64 pixel texture max 1024 bones (64 * 64 / 4)
var size;
if ( nBones > 256 )
size = 64;
else if ( nBones > 64 )
size = 32;
else if ( nBones > 16 )
size = 16;
else
size = 8;
this.boneTextureWidth = size;
this.boneTextureHeight = size;
this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
this.boneTexture.minFilter = THREE.NearestFilter;
this.boneTexture.magFilter = THREE.NearestFilter;
this.boneTexture.generateMipmaps = false;
this.boneTexture.flipY = false;
} else {
this.boneMatrices = new Float32Array( 16 * nBones );
}
this.pose();
}
};
THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.SkinnedMesh.prototype.addBone = function( bone ) {
if ( bone === undefined ) {
bone = new THREE.Bone( this );
}
this.bones.push( bone );
return bone;
};
THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
this.matrixAutoUpdate && this.updateMatrix();
// update matrixWorld
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent ) {
this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
} else {
this.matrixWorld.copy( this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
if ( child instanceof THREE.Bone ) {
child.update( this.identityMatrix, false );
} else {
child.updateMatrixWorld( true );
}
}
// make a snapshot of the bones' rest position
if ( this.boneInverses == undefined ) {
this.boneInverses = [];
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
var inverse = new THREE.Matrix4();
inverse.getInverse( this.bones[ b ].skinMatrix );
this.boneInverses.push( inverse );
}
}
// flatten bone matrices to array
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
// compute the offset between the current and the original transform;
//TODO: we could get rid of this multiplication step if the skinMatrix
// was already representing the offset; however, this requires some
// major changes to the animation system
THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
}
if ( this.useVertexTexture ) {
this.boneTexture.needsUpdate = true;
}
};
THREE.SkinnedMesh.prototype.pose = function() {
this.updateMatrixWorld( true );
for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
// normalize weights
var sw = this.geometry.skinWeights[ i ];
var scale = 1.0 / sw.lengthManhattan();
if ( scale !== Infinity ) {
sw.multiplyScalar( scale );
} else {
sw.set( 1 ); // this will be normalized by the shader anyway
}
}
};
THREE.SkinnedMesh.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
THREE.Mesh.prototype.clone.call( this, object );
return object;
};
THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MorphAnimMesh = function ( geometry, material ) {
THREE.Mesh.call( this, geometry, material );
// API
this.duration = 1000; // milliseconds
this.mirroredLoop = false;
this.time = 0;
// internals
this.lastKeyframe = 0;
this.currentKeyframe = 0;
this.direction = 1;
this.directionBackwards = false;
this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
};
THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
this.startKeyframe = start;
this.endKeyframe = end;
this.length = this.endKeyframe - this.startKeyframe + 1;
};
THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
this.direction = 1;
this.directionBackwards = false;
};
THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
this.direction = -1;
this.directionBackwards = true;
};
THREE.MorphAnimMesh.prototype.parseAnimations = function () {
var geometry = this.geometry;
if ( ! geometry.animations ) geometry.animations = {};
var firstAnimation, animations = geometry.animations;
var pattern = /([a-z]+)(\d+)/;
for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
var morph = geometry.morphTargets[ i ];
var parts = morph.name.match( pattern );
if ( parts && parts.length > 1 ) {
var label = parts[ 1 ];
var num = parts[ 2 ];
if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
var animation = animations[ label ];
if ( i < animation.start ) animation.start = i;
if ( i > animation.end ) animation.end = i;
if ( ! firstAnimation ) firstAnimation = label;
}
}
geometry.firstAnimation = firstAnimation;
};
THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
if ( ! this.geometry.animations ) this.geometry.animations = {};
this.geometry.animations[ label ] = { start: start, end: end };
};
THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
var animation = this.geometry.animations[ label ];
if ( animation ) {
this.setFrameRange( animation.start, animation.end );
this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
this.time = 0;
} else {
console.warn( "animation[" + label + "] undefined" );
}
};
THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
var frameTime = this.duration / this.length;
this.time += this.direction * delta;
if ( this.mirroredLoop ) {
if ( this.time > this.duration || this.time < 0 ) {
this.direction *= -1;
if ( this.time > this.duration ) {
this.time = this.duration;
this.directionBackwards = true;
}
if ( this.time < 0 ) {
this.time = 0;
this.directionBackwards = false;
}
}
} else {
this.time = this.time % this.duration;
if ( this.time < 0 ) this.time += this.duration;
}
var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
if ( keyframe !== this.currentKeyframe ) {
this.morphTargetInfluences[ this.lastKeyframe ] = 0;
this.morphTargetInfluences[ this.currentKeyframe ] = 1;
this.morphTargetInfluences[ keyframe ] = 0;
this.lastKeyframe = this.currentKeyframe;
this.currentKeyframe = keyframe;
}
var mix = ( this.time % frameTime ) / frameTime;
if ( this.directionBackwards ) {
mix = 1 - mix;
}
this.morphTargetInfluences[ this.currentKeyframe ] = mix;
this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
};
THREE.MorphAnimMesh.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
object.duration = this.duration;
object.mirroredLoop = this.mirroredLoop;
object.time = this.time;
object.lastKeyframe = this.lastKeyframe;
object.currentKeyframe = this.currentKeyframe;
object.direction = this.direction;
object.directionBackwards = this.directionBackwards;
THREE.Mesh.prototype.clone.call( this, object );
return object;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Ribbon = function ( geometry, material ) {
THREE.Object3D.call( this );
this.geometry = geometry;
this.material = material;
};
THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
THREE.Ribbon.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
THREE.LOD = function () {
THREE.Object3D.call( this );
this.LODs = [];
};
THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
if ( visibleAtDistance === undefined ) {
visibleAtDistance = 0;
}
visibleAtDistance = Math.abs( visibleAtDistance );
for ( var l = 0; l < this.LODs.length; l ++ ) {
if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
break;
}
}
this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
this.add( object3D );
};
THREE.LOD.prototype.update = function ( camera ) {
if ( this.LODs.length > 1 ) {
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
var inverse = camera.matrixWorldInverse;
var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
this.LODs[ 0 ].object3D.visible = true;
for ( var l = 1; l < this.LODs.length; l ++ ) {
if( distance >= this.LODs[ l ].visibleAtDistance ) {
this.LODs[ l - 1 ].object3D.visible = false;
this.LODs[ l ].object3D.visible = true;
} else {
break;
}
}
for( ; l < this.LODs.length; l ++ ) {
this.LODs[ l ].object3D.visible = false;
}
}
};
THREE.LOD.prototype.clone = function () {
// TODO
};
/**
* @author mikael emtinger / http://gomo.se/
*/
THREE.Sprite = function ( parameters ) {
THREE.Object3D.call( this );
this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
this.rotation3d = this.rotation;
this.rotation = 0;
this.opacity = 1;
this.uvOffset = new THREE.Vector2( 0, 0 );
this.uvScale = new THREE.Vector2( 1, 1 );
};
THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
/*
* Custom update matrix
*/
THREE.Sprite.prototype.updateMatrix = function () {
this.matrix.setPosition( this.position );
this.rotation3d.set( 0, 0, this.rotation );
this.matrix.setRotationFromEuler( this.rotation3d );
if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
this.matrix.scale( this.scale );
this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
}
this.matrixWorldNeedsUpdate = true;
};
THREE.Sprite.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Sprite( {} );
object.color.copy( this.color );
object.map = this.map;
object.blending = this.blending;
object.useScreenCoordinates = this.useScreenCoordinates;
object.mergeWith3D = this.mergeWith3D;
object.affectedByDistance = this.affectedByDistance;
object.scaleByViewport = this.scaleByViewport;
object.alignment = this.alignment;
object.rotation3d.copy( this.rotation3d );
object.rotation = this.rotation;
object.opacity = this.opacity;
object.uvOffset.copy( this.uvOffset );
object.uvScale.copy( this.uvScale);
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/*
* Alignment
*/
THREE.SpriteAlignment = {};
THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Scene = function () {
THREE.Object3D.call( this );
this.fog = null;
this.overrideMaterial = null;
this.matrixAutoUpdate = false;
this.__objects = [];
this.__lights = [];
this.__objectsAdded = [];
this.__objectsRemoved = [];
};
THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
THREE.Scene.prototype.__addObject = function ( object ) {
if ( object instanceof THREE.Light ) {
if ( this.__lights.indexOf( object ) === - 1 ) {
this.__lights.push( object );
}
if ( object.target && object.target.parent === undefined ) {
this.add( object.target );
}
} else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
if ( this.__objects.indexOf( object ) === - 1 ) {
this.__objects.push( object );
this.__objectsAdded.push( object );
// check if previously removed
var i = this.__objectsRemoved.indexOf( object );
if ( i !== -1 ) {
this.__objectsRemoved.splice( i, 1 );
}
}
}
for ( var c = 0; c < object.children.length; c ++ ) {
this.__addObject( object.children[ c ] );
}
};
THREE.Scene.prototype.__removeObject = function ( object ) {
if ( object instanceof THREE.Light ) {
var i = this.__lights.indexOf( object );
if ( i !== -1 ) {
this.__lights.splice( i, 1 );
}
} else if ( !( object instanceof THREE.Camera ) ) {
var i = this.__objects.indexOf( object );
if( i !== -1 ) {
this.__objects.splice( i, 1 );
this.__objectsRemoved.push( object );
// check if previously added
var ai = this.__objectsAdded.indexOf( object );
if ( ai !== -1 ) {
this.__objectsAdded.splice( ai, 1 );
}
}
}
for ( var c = 0; c < object.children.length; c ++ ) {
this.__removeObject( object.children[ c ] );
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Fog = function ( hex, near, far ) {
this.color = new THREE.Color( hex );
this.near = ( near !== undefined ) ? near : 1;
this.far = ( far !== undefined ) ? far : 1000;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.FogExp2 = function ( hex, density ) {
this.color = new THREE.Color( hex );
this.density = ( density !== undefined ) ? density : 0.00025;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.CanvasRenderer = function ( parameters ) {
console.log( 'THREE.CanvasRenderer', THREE.REVISION );
parameters = parameters || {};
var _this = this,
_renderData, _elements, _lights,
_projector = new THREE.Projector(),
_canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
_canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
_context = _canvas.getContext( '2d' ),
_clearColor = new THREE.Color( 0x000000 ),
_clearOpacity = 0,
_contextGlobalAlpha = 1,
_contextGlobalCompositeOperation = 0,
_contextStrokeStyle = null,
_contextFillStyle = null,
_contextLineWidth = null,
_contextLineCap = null,
_contextLineJoin = null,
_v1, _v2, _v3, _v4,
_v5 = new THREE.RenderableVertex(),
_v6 = new THREE.RenderableVertex(),
_v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
_v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
_color = new THREE.Color(),
_color1 = new THREE.Color(),
_color2 = new THREE.Color(),
_color3 = new THREE.Color(),
_color4 = new THREE.Color(),
_diffuseColor = new THREE.Color(),
_emissiveColor = new THREE.Color(),
_patterns = {}, _imagedatas = {},
_near, _far,
_image, _uvs,
_uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
_clipRect = new THREE.Rectangle(),
_clearRect = new THREE.Rectangle(),
_bboxRect = new THREE.Rectangle(),
_enableLighting = false,
_ambientLight = new THREE.Color(),
_directionalLights = new THREE.Color(),
_pointLights = new THREE.Color(),
_pi2 = Math.PI * 2,
_vector3 = new THREE.Vector3(), // Needed for PointLight
_pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
_gradientMap, _gradientMapContext, _gradientMapQuality = 16;
_pixelMap = document.createElement( 'canvas' );
_pixelMap.width = _pixelMap.height = 2;
_pixelMapContext = _pixelMap.getContext( '2d' );
_pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
_pixelMapContext.fillRect( 0, 0, 2, 2 );
_pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
_pixelMapData = _pixelMapImage.data;
_gradientMap = document.createElement( 'canvas' );
_gradientMap.width = _gradientMap.height = _gradientMapQuality;
_gradientMapContext = _gradientMap.getContext( '2d' );
_gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
_gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
_gradientMapQuality --; // Fix UVs
this.domElement = _canvas;
this.autoClear = true;
this.sortObjects = true;
this.sortElements = true;
this.info = {
render: {
vertices: 0,
faces: 0
}
}
this.setSize = function ( width, height ) {
_canvasWidth = width;
_canvasHeight = height;
_canvasWidthHalf = Math.floor( _canvasWidth / 2 );
_canvasHeightHalf = Math.floor( _canvasHeight / 2 );
_canvas.width = _canvasWidth;
_canvas.height = _canvasHeight;
_clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
_clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
_contextGlobalAlpha = 1;
_contextGlobalCompositeOperation = 0;
_contextStrokeStyle = null;
_contextFillStyle = null;
_contextLineWidth = null;
_contextLineCap = null;
_contextLineJoin = null;
};
this.setClearColor = function ( color, opacity ) {
_clearColor.copy( color );
_clearOpacity = opacity !== undefined ? opacity : 1;
_clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
};
this.setClearColorHex = function ( hex, opacity ) {
_clearColor.setHex( hex );
_clearOpacity = opacity !== undefined ? opacity : 1;
_clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
};
this.getMaxAnisotropy = function () {
return 0;
};
this.clear = function () {
_context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
if ( _clearRect.isEmpty() === false ) {
_clearRect.minSelf( _clipRect );
_clearRect.inflate( 2 );
if ( _clearOpacity < 1 ) {
_context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
}
if ( _clearOpacity > 0 ) {
setBlending( THREE.NormalBlending );
setOpacity( 1 );
setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
_context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
}
_clearRect.empty();
}
};
this.render = function ( scene, camera ) {
if ( camera instanceof THREE.Camera === false ) {
console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
return;
}
var e, el, element, material;
this.autoClear === true
? this.clear()
: _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
_this.info.render.vertices = 0;
_this.info.render.faces = 0;
_renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
_elements = _renderData.elements;
_lights = _renderData.lights;
/* DEBUG
_context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
_context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
*/
_enableLighting = _lights.length > 0;
if ( _enableLighting === true ) {
calculateLights();
}
for ( e = 0, el = _elements.length; e < el; e++ ) {
element = _elements[ e ];
material = element.material;
if ( material === undefined || material.visible === false ) continue;
_bboxRect.empty();
if ( element instanceof THREE.RenderableParticle ) {
_v1 = element;
_v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
renderParticle( _v1, element, material, scene );
} else if ( element instanceof THREE.RenderableLine ) {
_v1 = element.v1; _v2 = element.v2;
_v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
_v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
_bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
_bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
if ( _clipRect.intersects( _bboxRect ) === true ) {
renderLine( _v1, _v2, element, material, scene );
}
} else if ( element instanceof THREE.RenderableFace3 ) {
_v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
_v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
_v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
_v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
if ( material.overdraw === true ) {
expand( _v1.positionScreen, _v2.positionScreen );
expand( _v2.positionScreen, _v3.positionScreen );
expand( _v3.positionScreen, _v1.positionScreen );
}
_bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
_v2.positionScreen.x, _v2.positionScreen.y,
_v3.positionScreen.x, _v3.positionScreen.y );
if ( _clipRect.intersects( _bboxRect ) === true ) {
renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
}
} else if ( element instanceof THREE.RenderableFace4 ) {
_v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
_v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
_v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
_v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
_v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
_v5.positionScreen.copy( _v2.positionScreen );
_v6.positionScreen.copy( _v4.positionScreen );
if ( material.overdraw === true ) {
expand( _v1.positionScreen, _v2.positionScreen );
expand( _v2.positionScreen, _v4.positionScreen );
expand( _v4.positionScreen, _v1.positionScreen );
expand( _v3.positionScreen, _v5.positionScreen );
expand( _v3.positionScreen, _v6.positionScreen );
}
_bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
_bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
_bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
_bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
if ( _clipRect.intersects( _bboxRect ) === true ) {
renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
}
}
/* DEBUG
_context.lineWidth = 1;
_context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
_context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
*/
_clearRect.addRectangle( _bboxRect );
}
/* DEBUG
_context.lineWidth = 1;
_context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
_context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
*/
_context.setTransform( 1, 0, 0, 1, 0, 0 );
//
function calculateLights() {
_ambientLight.setRGB( 0, 0, 0 );
_directionalLights.setRGB( 0, 0, 0 );
_pointLights.setRGB( 0, 0, 0 );
for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
var light = _lights[ l ];
var lightColor = light.color;
if ( light instanceof THREE.AmbientLight ) {
_ambientLight.r += lightColor.r;
_ambientLight.g += lightColor.g;
_ambientLight.b += lightColor.b;
} else if ( light instanceof THREE.DirectionalLight ) {
// for particles
_directionalLights.r += lightColor.r;
_directionalLights.g += lightColor.g;
_directionalLights.b += lightColor.b;
} else if ( light instanceof THREE.PointLight ) {
// for particles
_pointLights.r += lightColor.r;
_pointLights.g += lightColor.g;
_pointLights.b += lightColor.b;
}
}
}
function calculateLight( position, normal, color ) {
for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
var light = _lights[ l ];
var lightColor = light.color;
if ( light instanceof THREE.DirectionalLight ) {
var lightPosition = light.matrixWorld.getPosition().normalize();
var amount = normal.dot( lightPosition );
if ( amount <= 0 ) continue;
amount *= light.intensity;
color.r += lightColor.r * amount;
color.g += lightColor.g * amount;
color.b += lightColor.b * amount;
} else if ( light instanceof THREE.PointLight ) {
var lightPosition = light.matrixWorld.getPosition();
var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
if ( amount <= 0 ) continue;
amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
if ( amount == 0 ) continue;
amount *= light.intensity;
color.r += lightColor.r * amount;
color.g += lightColor.g * amount;
color.b += lightColor.b * amount;
}
}
}
function renderParticle( v1, element, material, scene ) {
setOpacity( material.opacity );
setBlending( material.blending );
var width, height, scaleX, scaleY,
bitmap, bitmapWidth, bitmapHeight;
if ( material instanceof THREE.ParticleBasicMaterial ) {
if ( material.map === null ) {
scaleX = element.object.scale.x;
scaleY = element.object.scale.y;
// TODO: Be able to disable this
scaleX *= element.scale.x * _canvasWidthHalf;
scaleY *= element.scale.y * _canvasHeightHalf;
_bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
if ( _clipRect.intersects( _bboxRect ) === false ) {
return;
}
setFillStyle( material.color.getContextStyle() );
_context.save();
_context.translate( v1.x, v1.y );
_context.rotate( - element.rotation );
_context.scale( scaleX, scaleY );
_context.fillRect( -1, -1, 2, 2 );
_context.restore();
} else {
bitmap = material.map.image;
bitmapWidth = bitmap.width >> 1;
bitmapHeight = bitmap.height >> 1;
scaleX = element.scale.x * _canvasWidthHalf;
scaleY = element.scale.y * _canvasHeightHalf;
width = scaleX * bitmapWidth;
height = scaleY * bitmapHeight;
// TODO: Rotations break this...
_bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
if ( _clipRect.intersects( _bboxRect ) === false ) {
return;
}
_context.save();
_context.translate( v1.x, v1.y );
_context.rotate( - element.rotation );
_context.scale( scaleX, - scaleY );
_context.translate( - bitmapWidth, - bitmapHeight );
_context.drawImage( bitmap, 0, 0 );
_context.restore();
}
/* DEBUG
setStrokeStyle( 'rgb(255,255,0)' );
_context.beginPath();
_context.moveTo( v1.x - 10, v1.y );
_context.lineTo( v1.x + 10, v1.y );
_context.moveTo( v1.x, v1.y - 10 );
_context.lineTo( v1.x, v1.y + 10 );
_context.stroke();
*/
} else if ( material instanceof THREE.ParticleCanvasMaterial ) {
width = element.scale.x * _canvasWidthHalf;
height = element.scale.y * _canvasHeightHalf;
_bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
if ( _clipRect.intersects( _bboxRect ) === false ) {
return;
}
setStrokeStyle( material.color.getContextStyle() );
setFillStyle( material.color.getContextStyle() );
_context.save();
_context.translate( v1.x, v1.y );
_context.rotate( - element.rotation );
_context.scale( width, height );
material.program( _context );
_context.restore();
}
}
function renderLine( v1, v2, element, material, scene ) {
setOpacity( material.opacity );
setBlending( material.blending );
_context.beginPath();
_context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
_context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
if ( material instanceof THREE.LineBasicMaterial ) {
setLineWidth( material.linewidth );
setLineCap( material.linecap );
setLineJoin( material.linejoin );
setStrokeStyle( material.color.getContextStyle() );
_context.stroke();
_bboxRect.inflate( material.linewidth * 2 );
}
}
function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
_this.info.render.vertices += 3;
_this.info.render.faces ++;
setOpacity( material.opacity );
setBlending( material.blending );
_v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
_v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
_v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
_diffuseColor.copy( material.color );
_emissiveColor.copy( material.emissive );
if ( material.vertexColors === THREE.FaceColors ) {
_diffuseColor.r *= element.color.r;
_diffuseColor.g *= element.color.g;
_diffuseColor.b *= element.color.b;
}
if ( _enableLighting === true ) {
if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
_color1.r = _color2.r = _color3.r = _ambientLight.r;
_color1.g = _color2.g = _color3.g = _ambientLight.g;
_color1.b = _color2.b = _color3.b = _ambientLight.b;
calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
_color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
_color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
_color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
_color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
_color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
_color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
_color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
_color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
_color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
_color4.r = ( _color2.r + _color3.r ) * 0.5;
_color4.g = ( _color2.g + _color3.g ) * 0.5;
_color4.b = ( _color2.b + _color3.b ) * 0.5;
_image = getGradientTexture( _color1, _color2, _color3, _color4 );
clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
} else {
_color.r = _ambientLight.r;
_color.g = _ambientLight.g;
_color.b = _ambientLight.b;
calculateLight( element.centroidWorld, element.normalWorld, _color );
_color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
_color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
_color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
}
} else {
material.wireframe === true
? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( material.color );
}
} else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
if ( material.map !== null ) {
if ( material.map.mapping instanceof THREE.UVMapping ) {
_uvs = element.uvs[ 0 ];
patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].u, _uvs[ uv1 ].v, _uvs[ uv2 ].u, _uvs[ uv2 ].v, _uvs[ uv3 ].u, _uvs[ uv3 ].v, material.map );
}
} else if ( material.envMap !== null ) {
if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
var cameraMatrix = camera.matrixWorldInverse;
_vector3.copy( element.vertexNormalsWorld[ uv1 ] );
_uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
_uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
_vector3.copy( element.vertexNormalsWorld[ uv2 ] );
_uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
_uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
_vector3.copy( element.vertexNormalsWorld[ uv3 ] );
_uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
_uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
}/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
}*/
} else {
_color.copy( material.color );
if ( material.vertexColors === THREE.FaceColors ) {
_color.r *= element.color.r;
_color.g *= element.color.g;
_color.b *= element.color.b;
}
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
}
} else if ( material instanceof THREE.MeshDepthMaterial ) {
_near = camera.near;
_far = camera.far;
_color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
_color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
_color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
_color4.r = ( _color2.r + _color3.r ) * 0.5;
_color4.g = ( _color2.g + _color3.g ) * 0.5;
_color4.b = ( _color2.b + _color3.b ) * 0.5;
_image = getGradientTexture( _color1, _color2, _color3, _color4 );
clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
} else if ( material instanceof THREE.MeshNormalMaterial ) {
_color.r = normalToComponent( element.normalWorld.x );
_color.g = normalToComponent( element.normalWorld.y );
_color.b = normalToComponent( element.normalWorld.z );
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
}
}
function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
_this.info.render.vertices += 4;
_this.info.render.faces ++;
setOpacity( material.opacity );
setBlending( material.blending );
if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
// Let renderFace3() handle this
renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
return;
}
_v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
_v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
_v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
_v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
_v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
_v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
_diffuseColor.copy( material.color );
_emissiveColor.copy( material.emissive );
if ( material.vertexColors === THREE.FaceColors ) {
_diffuseColor.r *= element.color.r;
_diffuseColor.g *= element.color.g;
_diffuseColor.b *= element.color.b;
}
if ( _enableLighting === true ) {
if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
_color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
_color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
_color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
_color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
_color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
_color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
_color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
_color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
_color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
_color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
_color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
_color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
_color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
_color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
_color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
_image = getGradientTexture( _color1, _color2, _color3, _color4 );
// TODO: UVs are incorrect, v4->v3?
drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
} else {
_color.r = _ambientLight.r;
_color.g = _ambientLight.g;
_color.b = _ambientLight.b;
calculateLight( element.centroidWorld, element.normalWorld, _color );
_color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
_color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
_color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
}
} else {
_color.r = _diffuseColor.r + _emissiveColor.r;
_color.g = _diffuseColor.g + _emissiveColor.g;
_color.b = _diffuseColor.b + _emissiveColor.b;
drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
}
} else if ( material instanceof THREE.MeshBasicMaterial ) {
_color.copy( material.color );
if ( material.vertexColors === THREE.FaceColors ) {
_color.r *= element.color.r;
_color.g *= element.color.g;
_color.b *= element.color.b;
}
drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
} else if ( material instanceof THREE.MeshNormalMaterial ) {
_color.r = normalToComponent( element.normalWorld.x );
_color.g = normalToComponent( element.normalWorld.y );
_color.b = normalToComponent( element.normalWorld.z );
drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
} else if ( material instanceof THREE.MeshDepthMaterial ) {
_near = camera.near;
_far = camera.far;
_color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
_color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
_color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
_color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
_image = getGradientTexture( _color1, _color2, _color3, _color4 );
// TODO: UVs are incorrect, v4->v3?
drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
}
}
//
function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
_context.beginPath();
_context.moveTo( x0, y0 );
_context.lineTo( x1, y1 );
_context.lineTo( x2, y2 );
_context.closePath();
}
function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
_context.beginPath();
_context.moveTo( x0, y0 );
_context.lineTo( x1, y1 );
_context.lineTo( x2, y2 );
_context.lineTo( x3, y3 );
_context.closePath();
}
function strokePath( color, linewidth, linecap, linejoin ) {
setLineWidth( linewidth );
setLineCap( linecap );
setLineJoin( linejoin );
setStrokeStyle( color.getContextStyle() );
_context.stroke();
_bboxRect.inflate( linewidth * 2 );
}
function fillPath( color ) {
setFillStyle( color.getContextStyle() );
_context.fill();
}
function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
if ( texture.needsUpdate === true ) {
var repeatX = texture.wrapS == THREE.RepeatWrapping;
var repeatY = texture.wrapT == THREE.RepeatWrapping;
_patterns[ texture.id ] = _context.createPattern(
texture.image, repeatX === true && repeatY === true
? 'repeat'
: repeatX === true && repeatY === false
? 'repeat-x'
: repeatX === false && repeatY === true
? 'repeat-y'
: 'no-repeat'
);
texture.needsUpdate = false;
}
_patterns[ texture.id ] === undefined
? setFillStyle( 'rgba(0,0,0,1)' )
: setFillStyle( _patterns[ texture.id ] );
// http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
var a, b, c, d, e, f, det, idet,
offsetX = texture.offset.x / texture.repeat.x,
offsetY = texture.offset.y / texture.repeat.y,
width = texture.image.width * texture.repeat.x,
height = texture.image.height * texture.repeat.y;
u0 = ( u0 + offsetX ) * width;
v0 = ( 1.0 - v0 + offsetY ) * height;
u1 = ( u1 + offsetX ) * width;
v1 = ( 1.0 - v1 + offsetY ) * height;
u2 = ( u2 + offsetX ) * width;
v2 = ( 1.0 - v2 + offsetY ) * height;
x1 -= x0; y1 -= y0;
x2 -= x0; y2 -= y0;
u1 -= u0; v1 -= v0;
u2 -= u0; v2 -= v0;
det = u1 * v2 - u2 * v1;
if ( det === 0 ) {
if ( _imagedatas[ texture.id ] === undefined ) {
var canvas = document.createElement( 'canvas' )
canvas.width = texture.image.width;
canvas.height = texture.image.height;
var context = canvas.getContext( '2d' );
context.drawImage( texture.image, 0, 0 );
_imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
}
var data = _imagedatas[ texture.id ];
var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
_color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
fillPath( _color );
return;
}
idet = 1 / det;
a = ( v2 * x1 - v1 * x2 ) * idet;
b = ( v2 * y1 - v1 * y2 ) * idet;
c = ( u1 * x2 - u2 * x1 ) * idet;
d = ( u1 * y2 - u2 * y1 ) * idet;
e = x0 - a * u0 - c * v0;
f = y0 - b * u0 - d * v0;
_context.save();
_context.transform( a, b, c, d, e, f );
_context.fill();
_context.restore();
}
function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
// http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
var a, b, c, d, e, f, det, idet,
width = image.width - 1,
height = image.height - 1;
u0 *= width; v0 *= height;
u1 *= width; v1 *= height;
u2 *= width; v2 *= height;
x1 -= x0; y1 -= y0;
x2 -= x0; y2 -= y0;
u1 -= u0; v1 -= v0;
u2 -= u0; v2 -= v0;
det = u1 * v2 - u2 * v1;
idet = 1 / det;
a = ( v2 * x1 - v1 * x2 ) * idet;
b = ( v2 * y1 - v1 * y2 ) * idet;
c = ( u1 * x2 - u2 * x1 ) * idet;
d = ( u1 * y2 - u2 * y1 ) * idet;
e = x0 - a * u0 - c * v0;
f = y0 - b * u0 - d * v0;
_context.save();
_context.transform( a, b, c, d, e, f );
_context.clip();
_context.drawImage( image, 0, 0 );
_context.restore();
}
function getGradientTexture( color1, color2, color3, color4 ) {
// http://mrdoob.com/blog/post/710
_pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
_pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
_pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
_pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
_pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
_pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
_pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
_pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
_pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
_pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
_pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
_pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
_pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
_gradientMapContext.drawImage( _pixelMap, 0, 0 );
return _gradientMap;
}
function smoothstep( value, min, max ) {
var x = ( value - min ) / ( max - min );
return x * x * ( 3 - 2 * x );
}
function normalToComponent( normal ) {
var component = ( normal + 1 ) * 0.5;
return component < 0 ? 0 : ( component > 1 ? 1 : component );
}
// Hide anti-alias gaps
function expand( v1, v2 ) {
var x = v2.x - v1.x, y = v2.y - v1.y,
det = x * x + y * y, idet;
if ( det === 0 ) return;
idet = 1 / Math.sqrt( det );
x *= idet; y *= idet;
v2.x += x; v2.y += y;
v1.x -= x; v1.y -= y;
}
};
// Context cached methods.
function setOpacity( value ) {
if ( _contextGlobalAlpha !== value ) {
_context.globalAlpha = value;
_contextGlobalAlpha = value;
}
}
function setBlending( value ) {
if ( _contextGlobalCompositeOperation !== value ) {
if ( value === THREE.NormalBlending ) {
_context.globalCompositeOperation = 'source-over';
} else if ( value === THREE.AdditiveBlending ) {
_context.globalCompositeOperation = 'lighter';
} else if ( value === THREE.SubtractiveBlending ) {
_context.globalCompositeOperation = 'darker';
}
_contextGlobalCompositeOperation = value;
}
}
function setLineWidth( value ) {
if ( _contextLineWidth !== value ) {
_context.lineWidth = value;
_contextLineWidth = value;
}
}
function setLineCap( value ) {
// "butt", "round", "square"
if ( _contextLineCap !== value ) {
_context.lineCap = value;
_contextLineCap = value;
}
}
function setLineJoin( value ) {
// "round", "bevel", "miter"
if ( _contextLineJoin !== value ) {
_context.lineJoin = value;
_contextLineJoin = value;
}
}
function setStrokeStyle( value ) {
if ( _contextStrokeStyle !== value ) {
_context.strokeStyle = value;
_contextStrokeStyle = value;
}
}
function setFillStyle( value ) {
if ( _contextFillStyle !== value ) {
_context.fillStyle = value;
_contextFillStyle = value;
}
}
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
*/
THREE.ShaderChunk = {
// FOG
fog_pars_fragment: [
"#ifdef USE_FOG",
"uniform vec3 fogColor;",
"#ifdef FOG_EXP2",
"uniform float fogDensity;",
"#else",
"uniform float fogNear;",
"uniform float fogFar;",
"#endif",
"#endif"
].join("\n"),
fog_fragment: [
"#ifdef USE_FOG",
"float depth = gl_FragCoord.z / gl_FragCoord.w;",
"#ifdef FOG_EXP2",
"const float LOG2 = 1.442695;",
"float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
"fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
"#else",
"float fogFactor = smoothstep( fogNear, fogFar, depth );",
"#endif",
"gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
"#endif"
].join("\n"),
// ENVIRONMENT MAP
envmap_pars_fragment: [
"#ifdef USE_ENVMAP",
"uniform float reflectivity;",
"uniform samplerCube envMap;",
"uniform float flipEnvMap;",
"uniform int combine;",
"#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
"uniform bool useRefract;",
"uniform float refractionRatio;",
"#else",
"varying vec3 vReflect;",
"#endif",
"#endif"
].join("\n"),
envmap_fragment: [
"#ifdef USE_ENVMAP",
"vec3 reflectVec;",
"#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
"vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
"if ( useRefract ) {",
"reflectVec = refract( cameraToVertex, normal, refractionRatio );",
"} else { ",
"reflectVec = reflect( cameraToVertex, normal );",
"}",
"#else",
"reflectVec = vReflect;",
"#endif",
"#ifdef DOUBLE_SIDED",
"float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
"vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
"#else",
"vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
"#endif",
"#ifdef GAMMA_INPUT",
"cubeColor.xyz *= cubeColor.xyz;",
"#endif",
"if ( combine == 1 ) {",
"gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
"} else {",
"gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
"}",
"#endif"
].join("\n"),
envmap_pars_vertex: [
"#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
"varying vec3 vReflect;",
"uniform float refractionRatio;",
"uniform bool useRefract;",
"#endif"
].join("\n"),
worldpos_vertex : [
"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
"#ifdef USE_SKINNING",
"vec4 mPosition = modelMatrix * skinned;",
"#endif",
"#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
"vec4 mPosition = modelMatrix * vec4( morphed, 1.0 );",
"#endif",
"#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
"vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
"#endif",
"#endif"
].join("\n"),
envmap_vertex : [
"#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
"vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
"if ( useRefract ) {",
"vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
"} else {",
"vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
"}",
"#endif"
].join("\n"),
// COLOR MAP (particles)
map_particle_pars_fragment: [
"#ifdef USE_MAP",
"uniform sampler2D map;",
"#endif"
].join("\n"),
map_particle_fragment: [
"#ifdef USE_MAP",
"gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
"#endif"
].join("\n"),
// COLOR MAP (triangles)
map_pars_vertex: [
"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
"varying vec2 vUv;",
"uniform vec4 offsetRepeat;",
"#endif"
].join("\n"),
map_pars_fragment: [
"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
"varying vec2 vUv;",
"#endif",
"#ifdef USE_MAP",
"uniform sampler2D map;",
"#endif",
].join("\n"),
map_vertex: [
"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
"vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
"#endif"
].join("\n"),
map_fragment: [
"#ifdef USE_MAP",
"#ifdef GAMMA_INPUT",
"vec4 texelColor = texture2D( map, vUv );",
"texelColor.xyz *= texelColor.xyz;",
"gl_FragColor = gl_FragColor * texelColor;",
"#else",
"gl_FragColor = gl_FragColor * texture2D( map, vUv );",
"#endif",
"#endif"
].join("\n"),
// LIGHT MAP
lightmap_pars_fragment: [
"#ifdef USE_LIGHTMAP",
"varying vec2 vUv2;",
"uniform sampler2D lightMap;",
"#endif"
].join("\n"),
lightmap_pars_vertex: [
"#ifdef USE_LIGHTMAP",
"varying vec2 vUv2;",
"#endif"
].join("\n"),
lightmap_fragment: [
"#ifdef USE_LIGHTMAP",
"gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
"#endif"
].join("\n"),
lightmap_vertex: [
"#ifdef USE_LIGHTMAP",
"vUv2 = uv2;",
"#endif"
].join("\n"),
// BUMP MAP
bumpmap_pars_fragment: [
"#ifdef USE_BUMPMAP",
"uniform sampler2D bumpMap;",
"uniform float bumpScale;",
// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
"vec2 dHdxy_fwd() {",
"vec2 dSTdx = dFdx( vUv );",
"vec2 dSTdy = dFdy( vUv );",
"float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
"float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
"float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
"return vec2( dBx, dBy );",
"}",
"vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
"vec3 vSigmaX = dFdx( surf_pos );",
"vec3 vSigmaY = dFdy( surf_pos );",
"vec3 vN = surf_norm;", // normalized
"vec3 R1 = cross( vSigmaY, vN );",
"vec3 R2 = cross( vN, vSigmaX );",
"float fDet = dot( vSigmaX, R1 );",
"vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
"return normalize( abs( fDet ) * surf_norm - vGrad );",
"}",
"#endif"
].join("\n"),
// NORMAL MAP
normalmap_pars_fragment: [
"#ifdef USE_NORMALMAP",
"uniform sampler2D normalMap;",
"uniform vec2 normalScale;",
// Per-Pixel Tangent Space Normal Mapping
// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
"vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
"vec3 q0 = dFdx( eye_pos.xyz );",
"vec3 q1 = dFdy( eye_pos.xyz );",
"vec2 st0 = dFdx( vUv.st );",
"vec2 st1 = dFdy( vUv.st );",
"vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
"vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
"vec3 N = normalize( surf_norm );",
"vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
"mapN.xy = normalScale * mapN.xy;",
"mat3 tsn = mat3( S, T, N );",
"return normalize( tsn * mapN );",
"}",
"#endif"
].join("\n"),
// SPECULAR MAP
specularmap_pars_fragment: [
"#ifdef USE_SPECULARMAP",
"uniform sampler2D specularMap;",
"#endif"
].join("\n"),
specularmap_fragment: [
"float specularStrength;",
"#ifdef USE_SPECULARMAP",
"vec4 texelSpecular = texture2D( specularMap, vUv );",
"specularStrength = texelSpecular.r;",
"#else",
"specularStrength = 1.0;",
"#endif"
].join("\n"),
// LIGHTS LAMBERT
lights_lambert_pars_vertex: [
"uniform vec3 ambient;",
"uniform vec3 diffuse;",
"uniform vec3 emissive;",
"uniform vec3 ambientLightColor;",
"#if MAX_DIR_LIGHTS > 0",
"uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
"uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
"uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
"uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
"#endif",
"#ifdef WRAP_AROUND",
"uniform vec3 wrapRGB;",
"#endif"
].join("\n"),
lights_lambert_vertex: [
"vLightFront = vec3( 0.0 );",
"#ifdef DOUBLE_SIDED",
"vLightBack = vec3( 0.0 );",
"#endif",
"transformedNormal = normalize( transformedNormal );",
"#if MAX_DIR_LIGHTS > 0",
"for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
"vec3 dirVector = normalize( lDirection.xyz );",
"float dotProduct = dot( transformedNormal, dirVector );",
"vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
"#ifdef DOUBLE_SIDED",
"vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
"#ifdef WRAP_AROUND",
"vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
"#endif",
"#endif",
"#ifdef WRAP_AROUND",
"vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
"directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
"#ifdef DOUBLE_SIDED",
"directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
"#endif",
"#endif",
"vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
"#ifdef DOUBLE_SIDED",
"vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
"#endif",
"}",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz - mvPosition.xyz;",
"float lDistance = 1.0;",
"if ( pointLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
"lVector = normalize( lVector );",
"float dotProduct = dot( transformedNormal, lVector );",
"vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
"#ifdef DOUBLE_SIDED",
"vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
"#ifdef WRAP_AROUND",
"vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
"#endif",
"#endif",
"#ifdef WRAP_AROUND",
"vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
"pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
"#ifdef DOUBLE_SIDED",
"pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
"#endif",
"#endif",
"vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
"#ifdef DOUBLE_SIDED",
"vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
"#endif",
"}",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz - mvPosition.xyz;",
"lVector = normalize( lVector );",
"float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",
"if ( spotEffect > spotLightAngle[ i ] ) {",
"spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
"float lDistance = 1.0;",
"if ( spotLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
"float dotProduct = dot( transformedNormal, lVector );",
"vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
"#ifdef DOUBLE_SIDED",
"vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
"#ifdef WRAP_AROUND",
"vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
"#endif",
"#endif",
"#ifdef WRAP_AROUND",
"vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
"spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
"#ifdef DOUBLE_SIDED",
"spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
"#endif",
"#endif",
"vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
"#ifdef DOUBLE_SIDED",
"vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
"#endif",
"}",
"}",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz - mvPosition.xyz;",
"lVector = normalize( lVector );",
"float dotProduct = dot( transformedNormal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
"vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
"#ifdef DOUBLE_SIDED",
"vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
"#endif",
"}",
"#endif",
"vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
"#ifdef DOUBLE_SIDED",
"vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
"#endif"
].join("\n"),
// LIGHTS PHONG
lights_phong_pars_vertex: [
"#ifndef PHONG_PER_PIXEL",
"#if MAX_POINT_LIGHTS > 0",
"uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
"uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
"varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
"varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
"#endif",
"#endif",
"#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
"varying vec3 vWorldPosition;",
"#endif"
].join("\n"),
lights_phong_vertex: [
"#ifndef PHONG_PER_PIXEL",
"#if MAX_POINT_LIGHTS > 0",
"for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz - mvPosition.xyz;",
"float lDistance = 1.0;",
"if ( pointLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
"vPointLight[ i ] = vec4( lVector, lDistance );",
"}",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz - mvPosition.xyz;",
"float lDistance = 1.0;",
"if ( spotLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
"vSpotLight[ i ] = vec4( lVector, lDistance );",
"}",
"#endif",
"#endif",
"#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
"vWorldPosition = mPosition.xyz;",
"#endif"
].join("\n"),
lights_phong_pars_fragment: [
"uniform vec3 ambientLightColor;",
"#if MAX_DIR_LIGHTS > 0",
"uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
"uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
"#ifdef PHONG_PER_PIXEL",
"uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
"uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
"#else",
"varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
"#endif",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
"#ifdef PHONG_PER_PIXEL",
"uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
"#else",
"varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
"#endif",
"#endif",
"#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
"varying vec3 vWorldPosition;",
"#endif",
"#ifdef WRAP_AROUND",
"uniform vec3 wrapRGB;",
"#endif",
"varying vec3 vViewPosition;",
"varying vec3 vNormal;"
].join("\n"),
lights_phong_fragment: [
"vec3 normal = normalize( vNormal );",
"vec3 viewPosition = normalize( vViewPosition );",
"#ifdef DOUBLE_SIDED",
"normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
"#endif",
"#ifdef USE_NORMALMAP",
"normal = perturbNormal2Arb( -viewPosition, normal );",
"#elif defined( USE_BUMPMAP )",
"normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"vec3 pointDiffuse = vec3( 0.0 );",
"vec3 pointSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
"#ifdef PHONG_PER_PIXEL",
"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
"float lDistance = 1.0;",
"if ( pointLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
"lVector = normalize( lVector );",
"#else",
"vec3 lVector = normalize( vPointLight[ i ].xyz );",
"float lDistance = vPointLight[ i ].w;",
"#endif",
// diffuse
"float dotProduct = dot( normal, lVector );",
"#ifdef WRAP_AROUND",
"float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
"float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
"vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
"#else",
"float pointDiffuseWeight = max( dotProduct, 0.0 );",
"#endif",
"pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
// specular
"vec3 pointHalfVector = normalize( lVector + viewPosition );",
"float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
"float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
"pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
"#else",
"pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
"#endif",
"}",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"vec3 spotDiffuse = vec3( 0.0 );",
"vec3 spotSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
"#ifdef PHONG_PER_PIXEL",
"vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
"float lDistance = 1.0;",
"if ( spotLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
"lVector = normalize( lVector );",
"#else",
"vec3 lVector = normalize( vSpotLight[ i ].xyz );",
"float lDistance = vSpotLight[ i ].w;",
"#endif",
"float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
"if ( spotEffect > spotLightAngle[ i ] ) {",
"spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
// diffuse
"float dotProduct = dot( normal, lVector );",
"#ifdef WRAP_AROUND",
"float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
"float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
"vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
"#else",
"float spotDiffuseWeight = max( dotProduct, 0.0 );",
"#endif",
"spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
// specular
"vec3 spotHalfVector = normalize( lVector + viewPosition );",
"float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
"float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
"spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
"#else",
"spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
"#endif",
"}",
"}",
"#endif",
"#if MAX_DIR_LIGHTS > 0",
"vec3 dirDiffuse = vec3( 0.0 );",
"vec3 dirSpecular = vec3( 0.0 );" ,
"for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
"vec3 dirVector = normalize( lDirection.xyz );",
// diffuse
"float dotProduct = dot( normal, dirVector );",
"#ifdef WRAP_AROUND",
"float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
"float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
"vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
"#else",
"float dirDiffuseWeight = max( dotProduct, 0.0 );",
"#endif",
"dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
// specular
"vec3 dirHalfVector = normalize( dirVector + viewPosition );",
"float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
"float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
/*
// fresnel term from skin shader
"const float F0 = 0.128;",
"float base = 1.0 - dot( viewPosition, dirHalfVector );",
"float exponential = pow( base, 5.0 );",
"float fresnel = exponential + F0 * ( 1.0 - exponential );",
*/
/*
// fresnel term from fresnel shader
"const float mFresnelBias = 0.08;",
"const float mFresnelScale = 0.3;",
"const float mFresnelPower = 5.0;",
"float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
*/
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
//"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
"dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
"#else",
"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
"#endif",
"}",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"vec3 hemiDiffuse = vec3( 0.0 );",
"vec3 hemiSpecular = vec3( 0.0 );" ,
"for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
"vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",
// diffuse
"float dotProduct = dot( normal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
"hemiDiffuse += diffuse * hemiColor;",
// specular (sky light)
"vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
"float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
"float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
// specular (ground light)
"vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
"vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
"float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
"float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
"float dotProductGround = dot( normal, lVectorGround );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
"vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
"hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
"#else",
"hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
"#endif",
"}",
"#endif",
"vec3 totalDiffuse = vec3( 0.0 );",
"vec3 totalSpecular = vec3( 0.0 );",
"#if MAX_DIR_LIGHTS > 0",
"totalDiffuse += dirDiffuse;",
"totalSpecular += dirSpecular;",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"totalDiffuse += hemiDiffuse;",
"totalSpecular += hemiSpecular;",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"totalDiffuse += pointDiffuse;",
"totalSpecular += pointSpecular;",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"totalDiffuse += spotDiffuse;",
"totalSpecular += spotSpecular;",
"#endif",
"#ifdef METAL",
"gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
"#else",
"gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
"#endif"
].join("\n"),
// VERTEX COLORS
color_pars_fragment: [
"#ifdef USE_COLOR",
"varying vec3 vColor;",
"#endif"
].join("\n"),
color_fragment: [
"#ifdef USE_COLOR",
"gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
"#endif"
].join("\n"),
color_pars_vertex: [
"#ifdef USE_COLOR",
"varying vec3 vColor;",
"#endif"
].join("\n"),
color_vertex: [
"#ifdef USE_COLOR",
"#ifdef GAMMA_INPUT",
"vColor = color * color;",
"#else",
"vColor = color;",
"#endif",
"#endif"
].join("\n"),
// SKINNING
skinning_pars_vertex: [
"#ifdef USE_SKINNING",
"#ifdef BONE_TEXTURE",
"uniform sampler2D boneTexture;",
"mat4 getBoneMatrix( const in float i ) {",
"float j = i * 4.0;",
"float x = mod( j, N_BONE_PIXEL_X );",
"float y = floor( j / N_BONE_PIXEL_X );",
"const float dx = 1.0 / N_BONE_PIXEL_X;",
"const float dy = 1.0 / N_BONE_PIXEL_Y;",
"y = dy * ( y + 0.5 );",
"vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
"vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
"vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
"vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
"mat4 bone = mat4( v1, v2, v3, v4 );",
"return bone;",
"}",
"#else",
"uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
"mat4 getBoneMatrix( const in float i ) {",
"mat4 bone = boneGlobalMatrices[ int(i) ];",
"return bone;",
"}",
"#endif",
"#endif"
].join("\n"),
skinbase_vertex: [
"#ifdef USE_SKINNING",
"mat4 boneMatX = getBoneMatrix( skinIndex.x );",
"mat4 boneMatY = getBoneMatrix( skinIndex.y );",
"#endif"
].join("\n"),
skinning_vertex: [
"#ifdef USE_SKINNING",
"#ifdef USE_MORPHTARGETS",
"vec4 skinVertex = vec4( morphed, 1.0 );",
"#else",
"vec4 skinVertex = vec4( position, 1.0 );",
"#endif",
"vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
"skinned += boneMatY * skinVertex * skinWeight.y;",
"#endif"
].join("\n"),
// MORPHING
morphtarget_pars_vertex: [
"#ifdef USE_MORPHTARGETS",
"#ifndef USE_MORPHNORMALS",
"uniform float morphTargetInfluences[ 8 ];",
"#else",
"uniform float morphTargetInfluences[ 4 ];",
"#endif",
"#endif"
].join("\n"),
morphtarget_vertex: [
"#ifdef USE_MORPHTARGETS",
"vec3 morphed = vec3( 0.0 );",
"morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
"morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
"morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
"morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
"#ifndef USE_MORPHNORMALS",
"morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
"morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
"morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
"morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
"#endif",
"morphed += position;",
"#endif"
].join("\n"),
default_vertex : [
"vec4 mvPosition;",
"#ifdef USE_SKINNING",
"mvPosition = modelViewMatrix * skinned;",
"#endif",
"#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
"mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
"#endif",
"#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
"mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"#endif",
"gl_Position = projectionMatrix * mvPosition;",
].join("\n"),
morphnormal_vertex: [
"#ifdef USE_MORPHNORMALS",
"vec3 morphedNormal = vec3( 0.0 );",
"morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
"morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
"morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
"morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
"morphedNormal += normal;",
"#endif"
].join("\n"),
skinnormal_vertex: [
"#ifdef USE_SKINNING",
"mat4 skinMatrix = skinWeight.x * boneMatX;",
"skinMatrix += skinWeight.y * boneMatY;",
"#ifdef USE_MORPHNORMALS",
"vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
"#else",
"vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
"#endif",
"#endif"
].join("\n"),
defaultnormal_vertex: [
"vec3 objectNormal;",
"#ifdef USE_SKINNING",
"objectNormal = skinnedNormal.xyz;",
"#endif",
"#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
"objectNormal = morphedNormal;",
"#endif",
"#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
"objectNormal = normal;",
"#endif",
"#ifdef FLIP_SIDED",
"objectNormal = -objectNormal;",
"#endif",
"vec3 transformedNormal = normalMatrix * objectNormal;",
].join("\n"),
// SHADOW MAP
// based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
// http://spidergl.org/example.php?id=6
// http://fabiensanglard.net/shadowmapping
shadowmap_pars_fragment: [
"#ifdef USE_SHADOWMAP",
"uniform sampler2D shadowMap[ MAX_SHADOWS ];",
"uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
"uniform float shadowDarkness[ MAX_SHADOWS ];",
"uniform float shadowBias[ MAX_SHADOWS ];",
"varying vec4 vShadowCoord[ MAX_SHADOWS ];",
"float unpackDepth( const in vec4 rgba_depth ) {",
"const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
"float depth = dot( rgba_depth, bit_shift );",
"return depth;",
"}",
"#endif"
].join("\n"),
shadowmap_fragment: [
"#ifdef USE_SHADOWMAP",
"#ifdef SHADOWMAP_DEBUG",
"vec3 frustumColors[3];",
"frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
"frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
"frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
"#endif",
"#ifdef SHADOWMAP_CASCADE",
"int inFrustumCount = 0;",
"#endif",
"float fDepth;",
"vec3 shadowColor = vec3( 1.0 );",
"for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
"vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
// "if ( something && something )" breaks ATI OpenGL shader compiler
// "if ( all( something, something ) )" using this instead
"bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
"bool inFrustum = all( inFrustumVec );",
// don't shadow pixels outside of light frustum
// use just first frustum (for cascades)
// don't shadow pixels behind far plane of light frustum
"#ifdef SHADOWMAP_CASCADE",
"inFrustumCount += int( inFrustum );",
"bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
"#else",
"bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
"#endif",
"bool frustumTest = all( frustumTestVec );",
"if ( frustumTest ) {",
"shadowCoord.z += shadowBias[ i ];",
"#ifdef SHADOWMAP_SOFT",
// Percentage-close filtering
// (9 pixel kernel)
// http://fabiensanglard.net/shadowmappingPCF/
"float shadow = 0.0;",
/*
// nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
// must enroll loop manually
"for ( float y = -1.25; y <= 1.25; y += 1.25 )",
"for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
"vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
// doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
//"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
"float fDepth = unpackDepth( rgbaDepth );",
"if ( fDepth < shadowCoord.z )",
"shadow += 1.0;",
"}",
"shadow /= 9.0;",
*/
"const float shadowDelta = 1.0 / 9.0;",
"float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
"float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
"float dx0 = -1.25 * xPixelOffset;",
"float dy0 = -1.25 * yPixelOffset;",
"float dx1 = 1.25 * xPixelOffset;",
"float dy1 = 1.25 * yPixelOffset;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
"#else",
"vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
"float fDepth = unpackDepth( rgbaDepth );",
"if ( fDepth < shadowCoord.z )",
// spot with multiple shadows is darker
"shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
// spot with multiple shadows has the same color as single shadow spot
//"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
"#endif",
"}",
"#ifdef SHADOWMAP_DEBUG",
"#ifdef SHADOWMAP_CASCADE",
"if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
"#else",
"if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
"#endif",
"#endif",
"}",
"#ifdef GAMMA_OUTPUT",
"shadowColor *= shadowColor;",
"#endif",
"gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
"#endif"
].join("\n"),
shadowmap_pars_vertex: [
"#ifdef USE_SHADOWMAP",
"varying vec4 vShadowCoord[ MAX_SHADOWS ];",
"uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
"#endif"
].join("\n"),
shadowmap_vertex: [
"#ifdef USE_SHADOWMAP",
"for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
"vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
"}",
"#endif"
].join("\n"),
// ALPHATEST
alphatest_fragment: [
"#ifdef ALPHATEST",
"if ( gl_FragColor.a < ALPHATEST ) discard;",
"#endif"
].join("\n"),
// LINEAR SPACE
linear_to_gamma_fragment: [
"#ifdef GAMMA_OUTPUT",
"gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
"#endif"
].join("\n"),
};
THREE.UniformsUtils = {
merge: function ( uniforms ) {
var u, p, tmp, merged = {};
for ( u = 0; u < uniforms.length; u ++ ) {
tmp = this.clone( uniforms[ u ] );
for ( p in tmp ) {
merged[ p ] = tmp[ p ];
}
}
return merged;
},
clone: function ( uniforms_src ) {
var u, p, parameter, parameter_src, uniforms_dst = {};
for ( u in uniforms_src ) {
uniforms_dst[ u ] = {};
for ( p in uniforms_src[ u ] ) {
parameter_src = uniforms_src[ u ][ p ];
if ( parameter_src instanceof THREE.Color ||
parameter_src instanceof THREE.Vector2 ||
parameter_src instanceof THREE.Vector3 ||
parameter_src instanceof THREE.Vector4 ||
parameter_src instanceof THREE.Matrix4 ||
parameter_src instanceof THREE.Texture ) {
uniforms_dst[ u ][ p ] = parameter_src.clone();
} else if ( parameter_src instanceof Array ) {
uniforms_dst[ u ][ p ] = parameter_src.slice();
} else {
uniforms_dst[ u ][ p ] = parameter_src;
}
}
}
return uniforms_dst;
}
};
THREE.UniformsLib = {
common: {
"diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
"opacity" : { type: "f", value: 1.0 },
"map" : { type: "t", value: null },
"offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
"lightMap" : { type: "t", value: null },
"specularMap" : { type: "t", value: null },
"envMap" : { type: "t", value: null },
"flipEnvMap" : { type: "f", value: -1 },
"useRefract" : { type: "i", value: 0 },
"reflectivity" : { type: "f", value: 1.0 },
"refractionRatio" : { type: "f", value: 0.98 },
"combine" : { type: "i", value: 0 },
"morphTargetInfluences" : { type: "f", value: 0 }
},
bump: {
"bumpMap" : { type: "t", value: null },
"bumpScale" : { type: "f", value: 1 }
},
normalmap: {
"normalMap" : { type: "t", value: null },
"normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
},
fog : {
"fogDensity" : { type: "f", value: 0.00025 },
"fogNear" : { type: "f", value: 1 },
"fogFar" : { type: "f", value: 2000 },
"fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
},
lights: {
"ambientLightColor" : { type: "fv", value: [] },
"directionalLightDirection" : { type: "fv", value: [] },
"directionalLightColor" : { type: "fv", value: [] },
"hemisphereLightPosition" : { type: "fv", value: [] },
"hemisphereLightSkyColor" : { type: "fv", value: [] },
"hemisphereLightGroundColor" : { type: "fv", value: [] },
"pointLightColor" : { type: "fv", value: [] },
"pointLightPosition" : { type: "fv", value: [] },
"pointLightDistance" : { type: "fv1", value: [] },
"spotLightColor" : { type: "fv", value: [] },
"spotLightPosition" : { type: "fv", value: [] },
"spotLightDirection" : { type: "fv", value: [] },
"spotLightDistance" : { type: "fv1", value: [] },
"spotLightAngle" : { type: "fv1", value: [] },
"spotLightExponent" : { type: "fv1", value: [] }
},
particle: {
"psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
"opacity" : { type: "f", value: 1.0 },
"size" : { type: "f", value: 1.0 },
"scale" : { type: "f", value: 1.0 },
"map" : { type: "t", value: null },
"fogDensity" : { type: "f", value: 0.00025 },
"fogNear" : { type: "f", value: 1 },
"fogFar" : { type: "f", value: 2000 },
"fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
},
shadowmap: {
"shadowMap": { type: "tv", value: [] },
"shadowMapSize": { type: "v2v", value: [] },
"shadowBias" : { type: "fv1", value: [] },
"shadowDarkness": { type: "fv1", value: [] },
"shadowMatrix" : { type: "m4v", value: [] },
}
};
THREE.ShaderLib = {
'depth': {
uniforms: {
"mNear": { type: "f", value: 1.0 },
"mFar" : { type: "f", value: 2000.0 },
"opacity" : { type: "f", value: 1.0 }
},
vertexShader: [
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform float mNear;",
"uniform float mFar;",
"uniform float opacity;",
"void main() {",
"float depth = gl_FragCoord.z / gl_FragCoord.w;",
"float color = 1.0 - smoothstep( mNear, mFar, depth );",
"gl_FragColor = vec4( vec3( color ), opacity );",
"}"
].join("\n")
},
'normal': {
uniforms: {
"opacity" : { type: "f", value: 1.0 }
},
vertexShader: [
"varying vec3 vNormal;",
"void main() {",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vNormal = normalMatrix * normal;",
"gl_Position = projectionMatrix * mvPosition;",
"}"
].join("\n"),
fragmentShader: [
"uniform float opacity;",
"varying vec3 vNormal;",
"void main() {",
"gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
"}"
].join("\n")
},
'basic': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "common" ],
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "shadowmap" ]
] ),
vertexShader: [
THREE.ShaderChunk[ "map_pars_vertex" ],
THREE.ShaderChunk[ "lightmap_pars_vertex" ],
THREE.ShaderChunk[ "envmap_pars_vertex" ],
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "map_vertex" ],
THREE.ShaderChunk[ "lightmap_vertex" ],
THREE.ShaderChunk[ "color_vertex" ],
"#ifdef USE_ENVMAP",
THREE.ShaderChunk[ "morphnormal_vertex" ],
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
THREE.ShaderChunk[ "defaultnormal_vertex" ],
"#endif",
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "envmap_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform float opacity;",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_pars_fragment" ],
THREE.ShaderChunk[ "lightmap_pars_fragment" ],
THREE.ShaderChunk[ "envmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "specularmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( diffuse, opacity );",
THREE.ShaderChunk[ "map_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "specularmap_fragment" ],
THREE.ShaderChunk[ "lightmap_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "envmap_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'lambert': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "common" ],
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
THREE.UniformsLib[ "shadowmap" ],
{
"ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
"emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
"wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
}
] ),
vertexShader: [
"#define LAMBERT",
"varying vec3 vLightFront;",
"#ifdef DOUBLE_SIDED",
"varying vec3 vLightBack;",
"#endif",
THREE.ShaderChunk[ "map_pars_vertex" ],
THREE.ShaderChunk[ "lightmap_pars_vertex" ],
THREE.ShaderChunk[ "envmap_pars_vertex" ],
THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "map_vertex" ],
THREE.ShaderChunk[ "lightmap_vertex" ],
THREE.ShaderChunk[ "color_vertex" ],
THREE.ShaderChunk[ "morphnormal_vertex" ],
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
THREE.ShaderChunk[ "defaultnormal_vertex" ],
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "envmap_vertex" ],
THREE.ShaderChunk[ "lights_lambert_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform float opacity;",
"varying vec3 vLightFront;",
"#ifdef DOUBLE_SIDED",
"varying vec3 vLightBack;",
"#endif",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_pars_fragment" ],
THREE.ShaderChunk[ "lightmap_pars_fragment" ],
THREE.ShaderChunk[ "envmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "specularmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
THREE.ShaderChunk[ "map_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "specularmap_fragment" ],
"#ifdef DOUBLE_SIDED",
//"float isFront = float( gl_FrontFacing );",
//"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
"if ( gl_FrontFacing )",
"gl_FragColor.xyz *= vLightFront;",
"else",
"gl_FragColor.xyz *= vLightBack;",
"#else",
"gl_FragColor.xyz *= vLightFront;",
"#endif",
THREE.ShaderChunk[ "lightmap_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "envmap_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'phong': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "common" ],
THREE.UniformsLib[ "bump" ],
THREE.UniformsLib[ "normalmap" ],
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
THREE.UniformsLib[ "shadowmap" ],
{
"ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
"emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
"specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
"shininess": { type: "f", value: 30 },
"wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
}
] ),
vertexShader: [
"#define PHONG",
"varying vec3 vViewPosition;",
"varying vec3 vNormal;",
THREE.ShaderChunk[ "map_pars_vertex" ],
THREE.ShaderChunk[ "lightmap_pars_vertex" ],
THREE.ShaderChunk[ "envmap_pars_vertex" ],
THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "map_vertex" ],
THREE.ShaderChunk[ "lightmap_vertex" ],
THREE.ShaderChunk[ "color_vertex" ],
THREE.ShaderChunk[ "morphnormal_vertex" ],
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
THREE.ShaderChunk[ "defaultnormal_vertex" ],
"vNormal = transformedNormal;",
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
"vViewPosition = -mvPosition.xyz;",
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "envmap_vertex" ],
THREE.ShaderChunk[ "lights_phong_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform float opacity;",
"uniform vec3 ambient;",
"uniform vec3 emissive;",
"uniform vec3 specular;",
"uniform float shininess;",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_pars_fragment" ],
THREE.ShaderChunk[ "lightmap_pars_fragment" ],
THREE.ShaderChunk[ "envmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
THREE.ShaderChunk[ "normalmap_pars_fragment" ],
THREE.ShaderChunk[ "specularmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
THREE.ShaderChunk[ "map_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "specularmap_fragment" ],
THREE.ShaderChunk[ "lights_phong_fragment" ],
THREE.ShaderChunk[ "lightmap_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "envmap_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'particle_basic': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "particle" ],
THREE.UniformsLib[ "shadowmap" ]
] ),
vertexShader: [
"uniform float size;",
"uniform float scale;",
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "color_vertex" ],
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"#ifdef USE_SIZEATTENUATION",
"gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
"#else",
"gl_PointSize = size;",
"#endif",
"gl_Position = projectionMatrix * mvPosition;",
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 psColor;",
"uniform float opacity;",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_particle_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( psColor, opacity );",
THREE.ShaderChunk[ "map_particle_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
// Depth encoding into RGBA texture
// based on SpiderGL shadow map example
// http://spidergl.org/example.php?id=6
// originally from
// http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
// see also here:
// http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
'depthRGBA': {
uniforms: {},
vertexShader: [
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"vec4 pack_depth( const in float depth ) {",
"const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
"const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
"vec4 res = fract( depth * bit_shift );",
"res -= res.xxyz * bit_mask;",
"return res;",
"}",
"void main() {",
"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
//"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
//"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
//"gl_FragData[ 0 ] = pack_depth( z );",
//"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
"}"
].join("\n")
}
};
/**
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author szimek / https://github.com/szimek/
*/
THREE.WebGLRenderer = function ( parameters ) {
console.log( 'THREE.WebGLRenderer', THREE.REVISION );
parameters = parameters || {};
var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
_precision = parameters.precision !== undefined ? parameters.precision : 'highp',
_alpha = parameters.alpha !== undefined ? parameters.alpha : true,
_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
_clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
_clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
_maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
// public properties
this.domElement = _canvas;
this.context = null;
// clearing
this.autoClear = true;
this.autoClearColor = true;
this.autoClearDepth = true;
this.autoClearStencil = true;
// scene graph
this.sortObjects = true;
this.autoUpdateObjects = true;
this.autoUpdateScene = true;
// physically based shading
this.gammaInput = false;
this.gammaOutput = false;
this.physicallyBasedShading = false;
// shadow map
this.shadowMapEnabled = false;
this.shadowMapAutoUpdate = true;
this.shadowMapSoft = true;
this.shadowMapCullFrontFaces = true;
this.shadowMapDebug = false;
this.shadowMapCascade = false;
// morphs
this.maxMorphTargets = 8;
this.maxMorphNormals = 4;
// flags
this.autoScaleCubemaps = true;
// custom render plugins
this.renderPluginsPre = [];
this.renderPluginsPost = [];
// info
this.info = {
memory: {
programs: 0,
geometries: 0,
textures: 0
},
render: {
calls: 0,
vertices: 0,
faces: 0,
points: 0
}
};
// internal properties
var _this = this,
_programs = [],
_programs_counter = 0,
// internal state cache
_currentProgram = null,
_currentFramebuffer = null,
_currentMaterialId = -1,
_currentGeometryGroupHash = null,
_currentCamera = null,
_geometryGroupCounter = 0,
_usedTextureUnits = 0,
// GL state cache
_oldDoubleSided = -1,
_oldFlipSided = -1,
_oldBlending = -1,
_oldBlendEquation = -1,
_oldBlendSrc = -1,
_oldBlendDst = -1,
_oldDepthTest = -1,
_oldDepthWrite = -1,
_oldPolygonOffset = null,
_oldPolygonOffsetFactor = null,
_oldPolygonOffsetUnits = null,
_oldLineWidth = null,
_viewportX = 0,
_viewportY = 0,
_viewportWidth = 0,
_viewportHeight = 0,
_currentWidth = 0,
_currentHeight = 0,
// frustum
_frustum = new THREE.Frustum(),
// camera matrices cache
_projScreenMatrix = new THREE.Matrix4(),
_projScreenMatrixPS = new THREE.Matrix4(),
_vector3 = new THREE.Vector4(),
// light arrays cache
_direction = new THREE.Vector3(),
_lightsNeedUpdate = true,
_lights = {
ambient: [ 0, 0, 0 ],
directional: { length: 0, colors: new Array(), positions: new Array() },
point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() },
hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
};
// initialize
var _gl;
var _glExtensionTextureFloat;
var _glExtensionStandardDerivatives;
var _glExtensionTextureFilterAnisotropic;
var _glExtensionCompressedTextureS3TC;
initGL();
setDefaultGLState();
this.context = _gl;
// GPU capabilities
var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
var _supportsVertexTextures = ( _maxVertexTextures > 0 );
var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
// API
this.getContext = function () {
return _gl;
};
this.supportsVertexTextures = function () {
return _supportsVertexTextures;
};
this.getMaxAnisotropy = function () {
return _maxAnisotropy;
};
this.setSize = function ( width, height ) {
_canvas.width = width;
_canvas.height = height;
this.setViewport( 0, 0, _canvas.width, _canvas.height );
};
this.setViewport = function ( x, y, width, height ) {
_viewportX = x !== undefined ? x : 0;
_viewportY = y !== undefined ? y : 0;
_viewportWidth = width !== undefined ? width : _canvas.width;
_viewportHeight = height !== undefined ? height : _canvas.height;
_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
};
this.setScissor = function ( x, y, width, height ) {
_gl.scissor( x, y, width, height );
};
this.enableScissorTest = function ( enable ) {
enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
};
// Clearing
this.setClearColorHex = function ( hex, alpha ) {
_clearColor.setHex( hex );
_clearAlpha = alpha;
_gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
};
this.setClearColor = function ( color, alpha ) {
_clearColor.copy( color );
_clearAlpha = alpha;
_gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
};
this.getClearColor = function () {
return _clearColor;
};
this.getClearAlpha = function () {
return _clearAlpha;
};
this.clear = function ( color, depth, stencil ) {
var bits = 0;
if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
_gl.clear( bits );
};
this.clearTarget = function ( renderTarget, color, depth, stencil ) {
this.setRenderTarget( renderTarget );
this.clear( color, depth, stencil );
};
// Plugins
this.addPostPlugin = function ( plugin ) {
plugin.init( this );
this.renderPluginsPost.push( plugin );
};
this.addPrePlugin = function ( plugin ) {
plugin.init( this );
this.renderPluginsPre.push( plugin );
};
// Deallocation
this.deallocateObject = function ( object ) {
if ( ! object.__webglInit ) return;
object.__webglInit = false;
delete object._modelViewMatrix;
delete object._normalMatrix;
delete object._normalMatrixArray;
delete object._modelViewMatrixArray;
delete object._modelMatrixArray;
if ( object instanceof THREE.Mesh ) {
for ( var g in object.geometry.geometryGroups ) {
deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
}
} else if ( object instanceof THREE.Ribbon ) {
deleteRibbonBuffers( object.geometry );
} else if ( object instanceof THREE.Line ) {
deleteLineBuffers( object.geometry );
} else if ( object instanceof THREE.ParticleSystem ) {
deleteParticleBuffers( object.geometry );
}
};
this.deallocateTexture = function ( texture ) {
if ( ! texture.__webglInit ) return;
texture.__webglInit = false;
_gl.deleteTexture( texture.__webglTexture );
_this.info.memory.textures --;
};
this.deallocateRenderTarget = function ( renderTarget ) {
if ( !renderTarget || ! renderTarget.__webglTexture ) return;
_gl.deleteTexture( renderTarget.__webglTexture );
if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
for ( var i = 0; i < 6; i ++ ) {
_gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
_gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
}
} else {
_gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
_gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
}
};
this.deallocateMaterial = function ( material ) {
var program = material.program;
if ( ! program ) return;
material.program = undefined;
// only deallocate GL program if this was the last use of shared program
// assumed there is only single copy of any program in the _programs list
// (that's how it's constructed)
var i, il, programInfo;
var deleteProgram = false;
for ( i = 0, il = _programs.length; i < il; i ++ ) {
programInfo = _programs[ i ];
if ( programInfo.program === program ) {
programInfo.usedTimes --;
if ( programInfo.usedTimes === 0 ) {
deleteProgram = true;
}
break;
}
}
if ( deleteProgram ) {
// avoid using array.splice, this is costlier than creating new array from scratch
var newPrograms = [];
for ( i = 0, il = _programs.length; i < il; i ++ ) {
programInfo = _programs[ i ];
if ( programInfo.program !== program ) {
newPrograms.push( programInfo );
}
}
_programs = newPrograms;
_gl.deleteProgram( program );
_this.info.memory.programs --;
}
};
// Rendering
this.updateShadowMap = function ( scene, camera ) {
_currentProgram = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
_oldDoubleSided = -1;
_oldFlipSided = -1;
this.shadowMapPlugin.update( scene, camera );
};
// Internal functions
// Buffer allocation
function createParticleBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
_this.info.memory.geometries ++;
};
function createLineBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
_this.info.memory.geometries ++;
};
function createRibbonBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
_this.info.memory.geometries ++;
};
function createMeshBuffers ( geometryGroup ) {
geometryGroup.__webglVertexBuffer = _gl.createBuffer();
geometryGroup.__webglNormalBuffer = _gl.createBuffer();
geometryGroup.__webglTangentBuffer = _gl.createBuffer();
geometryGroup.__webglColorBuffer = _gl.createBuffer();
geometryGroup.__webglUVBuffer = _gl.createBuffer();
geometryGroup.__webglUV2Buffer = _gl.createBuffer();
geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
geometryGroup.__webglFaceBuffer = _gl.createBuffer();
geometryGroup.__webglLineBuffer = _gl.createBuffer();
var m, ml;
if ( geometryGroup.numMorphTargets ) {
geometryGroup.__webglMorphTargetsBuffers = [];
for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
}
}
if ( geometryGroup.numMorphNormals ) {
geometryGroup.__webglMorphNormalsBuffers = [];
for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
}
}
_this.info.memory.geometries ++;
};
// Buffer deallocation
function deleteParticleBuffers ( geometry ) {
_gl.deleteBuffer( geometry.__webglVertexBuffer );
_gl.deleteBuffer( geometry.__webglColorBuffer );
_this.info.memory.geometries --;
};
function deleteLineBuffers ( geometry ) {
_gl.deleteBuffer( geometry.__webglVertexBuffer );
_gl.deleteBuffer( geometry.__webglColorBuffer );
_this.info.memory.geometries --;
};
function deleteRibbonBuffers ( geometry ) {
_gl.deleteBuffer( geometry.__webglVertexBuffer );
_gl.deleteBuffer( geometry.__webglColorBuffer );
_this.info.memory.geometries --;
};
function deleteMeshBuffers ( geometryGroup ) {
_gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
_gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
_gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
_gl.deleteBuffer( geometryGroup.__webglColorBuffer );
_gl.deleteBuffer( geometryGroup.__webglUVBuffer );
_gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
_gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
_gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
_gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
_gl.deleteBuffer( geometryGroup.__webglLineBuffer );
var m, ml;
if ( geometryGroup.numMorphTargets ) {
for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
_gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
}
}
if ( geometryGroup.numMorphNormals ) {
for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
_gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
}
}
if ( geometryGroup.__webglCustomAttributesList ) {
for ( var id in geometryGroup.__webglCustomAttributesList ) {
_gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
}
}
_this.info.memory.geometries --;
};
// Buffer initialization
function initCustomAttributes ( geometry, object ) {
var nvertices = geometry.vertices.length;
var material = object.material;
if ( material.attributes ) {
if ( geometry.__webglCustomAttributesList === undefined ) {
geometry.__webglCustomAttributesList = [];
}
for ( var a in material.attributes ) {
var attribute = material.attributes[ a ];
if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
attribute.__webglInitialized = true;
var size = 1; // "f" and "i"
if ( attribute.type === "v2" ) size = 2;
else if ( attribute.type === "v3" ) size = 3;
else if ( attribute.type === "v4" ) size = 4;
else if ( attribute.type === "c" ) size = 3;
attribute.size = size;
attribute.array = new Float32Array( nvertices * size );
attribute.buffer = _gl.createBuffer();
attribute.buffer.belongsToAttribute = a;
attribute.needsUpdate = true;
}
geometry.__webglCustomAttributesList.push( attribute );
}
}
};
function initParticleBuffers ( geometry, object ) {
var nvertices = geometry.vertices.length;
geometry.__vertexArray = new Float32Array( nvertices * 3 );
geometry.__colorArray = new Float32Array( nvertices * 3 );
geometry.__sortArray = [];
geometry.__webglParticleCount = nvertices;
initCustomAttributes ( geometry, object );
};
function initLineBuffers ( geometry, object ) {
var nvertices = geometry.vertices.length;
geometry.__vertexArray = new Float32Array( nvertices * 3 );
geometry.__colorArray = new Float32Array( nvertices * 3 );
geometry.__webglLineCount = nvertices;
initCustomAttributes ( geometry, object );
};
function initRibbonBuffers ( geometry ) {
var nvertices = geometry.vertices.length;
geometry.__vertexArray = new Float32Array( nvertices * 3 );
geometry.__colorArray = new Float32Array( nvertices * 3 );
geometry.__webglVertexCount = nvertices;
};
function initMeshBuffers ( geometryGroup, object ) {
var geometry = object.geometry,
faces3 = geometryGroup.faces3,
faces4 = geometryGroup.faces4,
nvertices = faces3.length * 3 + faces4.length * 4,
ntris = faces3.length * 1 + faces4.length * 2,
nlines = faces3.length * 3 + faces4.length * 4,
material = getBufferMaterial( object, geometryGroup ),
uvType = bufferGuessUVType( material ),
normalType = bufferGuessNormalType( material ),
vertexColorType = bufferGuessVertexColorType( material );
//console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
if ( normalType ) {
geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
}
if ( geometry.hasTangents ) {
geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
}
if ( vertexColorType ) {
geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
}
if ( uvType ) {
if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
}
if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
}
}
if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
}
geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
var m, ml;
if ( geometryGroup.numMorphTargets ) {
geometryGroup.__morphTargetsArrays = [];
for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
}
}
if ( geometryGroup.numMorphNormals ) {
geometryGroup.__morphNormalsArrays = [];
for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
}
}
geometryGroup.__webglFaceCount = ntris * 3;
geometryGroup.__webglLineCount = nlines * 2;
// custom attributes
if ( material.attributes ) {
if ( geometryGroup.__webglCustomAttributesList === undefined ) {
geometryGroup.__webglCustomAttributesList = [];
}
for ( var a in material.attributes ) {
// Do a shallow copy of the attribute object so different geometryGroup chunks use different
// attribute buffers which are correctly indexed in the setMeshBuffers function
var originalAttribute = material.attributes[ a ];
var attribute = {};
for ( var property in originalAttribute ) {
attribute[ property ] = originalAttribute[ property ];
}
if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
attribute.__webglInitialized = true;
var size = 1; // "f" and "i"
if( attribute.type === "v2" ) size = 2;
else if( attribute.type === "v3" ) size = 3;
else if( attribute.type === "v4" ) size = 4;
else if( attribute.type === "c" ) size = 3;
attribute.size = size;
attribute.array = new Float32Array( nvertices * size );
attribute.buffer = _gl.createBuffer();
attribute.buffer.belongsToAttribute = a;
originalAttribute.needsUpdate = true;
attribute.__original = originalAttribute;
}
geometryGroup.__webglCustomAttributesList.push( attribute );
}
}
geometryGroup.__inittedArrays = true;
};
function getBufferMaterial( object, geometryGroup ) {
if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
return object.material;
} else if ( geometryGroup.materialIndex >= 0 ) {
return object.geometry.materials[ geometryGroup.materialIndex ];
}
};
function materialNeedsSmoothNormals ( material ) {
return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
};
function bufferGuessNormalType ( material ) {
// only MeshBasicMaterial and MeshDepthMaterial don't need normals
if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
return false;
}
if ( materialNeedsSmoothNormals( material ) ) {
return THREE.SmoothShading;
} else {
return THREE.FlatShading;
}
};
function bufferGuessVertexColorType ( material ) {
if ( material.vertexColors ) {
return material.vertexColors;
}
return false;
};
function bufferGuessUVType ( material ) {
// material must use some texture to require uvs
if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
return true;
}
return false;
};
//
function initDirectBuffers( geometry ) {
var a, attribute, type;
for ( a in geometry.attributes ) {
if ( a === "index" ) {
type = _gl.ELEMENT_ARRAY_BUFFER;
} else {
type = _gl.ARRAY_BUFFER;
}
attribute = geometry.attributes[ a ];
attribute.buffer = _gl.createBuffer();
_gl.bindBuffer( type, attribute.buffer );
_gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
}
};
// Buffer setting
function setParticleBuffers ( geometry, hint, object ) {
var v, c, vertex, offset, index, color,
vertices = geometry.vertices,
vl = vertices.length,
colors = geometry.colors,
cl = colors.length,
vertexArray = geometry.__vertexArray,
colorArray = geometry.__colorArray,
sortArray = geometry.__sortArray,
dirtyVertices = geometry.verticesNeedUpdate,
dirtyElements = geometry.elementsNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
customAttributes = geometry.__webglCustomAttributesList,
i, il,
a, ca, cal, value,
customAttribute;
if ( object.sortParticles ) {
_projScreenMatrixPS.copy( _projScreenMatrix );
_projScreenMatrixPS.multiplySelf( object.matrixWorld );
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
_vector3.copy( vertex );
_projScreenMatrixPS.multiplyVector3( _vector3 );
sortArray[ v ] = [ _vector3.z, v ];
}
sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ sortArray[v][1] ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
for ( c = 0; c < cl; c ++ ) {
offset = c * 3;
color = colors[ sortArray[c][1] ];
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
offset = 0;
cal = customAttribute.value.length;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
customAttribute.array[ ca ] = customAttribute.value[ index ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
}
}
} else {
if ( dirtyVertices ) {
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
}
if ( dirtyColors ) {
for ( c = 0; c < cl; c ++ ) {
color = colors[ c ];
offset = c * 3;
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate &&
( customAttribute.boundTo === undefined ||
customAttribute.boundTo === "vertices") ) {
cal = customAttribute.value.length;
offset = 0;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
customAttribute.array[ ca ] = customAttribute.value[ ca ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
}
}
}
}
if ( dirtyVertices || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyColors || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
}
};
function setLineBuffers ( geometry, hint ) {
var v, c, vertex, offset, color,
vertices = geometry.vertices,
colors = geometry.colors,
vl = vertices.length,
cl = colors.length,
vertexArray = geometry.__vertexArray,
colorArray = geometry.__colorArray,
dirtyVertices = geometry.verticesNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
customAttributes = geometry.__webglCustomAttributesList,
i, il,
a, ca, cal, value,
customAttribute;
if ( dirtyVertices ) {
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyColors ) {
for ( c = 0; c < cl; c ++ ) {
color = colors[ c ];
offset = c * 3;
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate &&
( customAttribute.boundTo === undefined ||
customAttribute.boundTo === "vertices" ) ) {
offset = 0;
cal = customAttribute.value.length;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
customAttribute.array[ ca ] = customAttribute.value[ ca ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
}
};
function setRibbonBuffers ( geometry, hint ) {
var v, c, vertex, offset, color,
vertices = geometry.vertices,
colors = geometry.colors,
vl = vertices.length,
cl = colors.length,
vertexArray = geometry.__vertexArray,
colorArray = geometry.__colorArray,
dirtyVertices = geometry.verticesNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate;
if ( dirtyVertices ) {
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyColors ) {
for ( c = 0; c < cl; c ++ ) {
color = colors[ c ];
offset = c * 3;
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
};
function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
if ( ! geometryGroup.__inittedArrays ) {
// console.log( object );
return;
}
var normalType = bufferGuessNormalType( material ),
vertexColorType = bufferGuessVertexColorType( material ),
uvType = bufferGuessUVType( material ),
needsSmoothNormals = ( normalType === THREE.SmoothShading );
var f, fl, fi, face,
vertexNormals, faceNormal, normal,
vertexColors, faceColor,
vertexTangents,
uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
c1, c2, c3, c4,
sw1, sw2, sw3, sw4,
si1, si2, si3, si4,
sa1, sa2, sa3, sa4,
sb1, sb2, sb3, sb4,
m, ml, i, il,
vn, uvi, uv2i,
vk, vkl, vka,
nka, chf, faceVertexNormals,
a,
vertexIndex = 0,
offset = 0,
offset_uv = 0,
offset_uv2 = 0,
offset_face = 0,
offset_normal = 0,
offset_tangent = 0,
offset_line = 0,
offset_color = 0,
offset_skin = 0,
offset_morphTarget = 0,
offset_custom = 0,
offset_customSrc = 0,
value,
vertexArray = geometryGroup.__vertexArray,
uvArray = geometryGroup.__uvArray,
uv2Array = geometryGroup.__uv2Array,
normalArray = geometryGroup.__normalArray,
tangentArray = geometryGroup.__tangentArray,
colorArray = geometryGroup.__colorArray,
skinIndexArray = geometryGroup.__skinIndexArray,
skinWeightArray = geometryGroup.__skinWeightArray,
morphTargetsArrays = geometryGroup.__morphTargetsArrays,
morphNormalsArrays = geometryGroup.__morphNormalsArrays,
customAttributes = geometryGroup.__webglCustomAttributesList,
customAttribute,
faceArray = geometryGroup.__faceArray,
lineArray = geometryGroup.__lineArray,
geometry = object.geometry, // this is shared for all chunks
dirtyVertices = geometry.verticesNeedUpdate,
dirtyElements = geometry.elementsNeedUpdate,
dirtyUvs = geometry.uvsNeedUpdate,
dirtyNormals = geometry.normalsNeedUpdate,
dirtyTangents = geometry.tangentsNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
vertices = geometry.vertices,
chunk_faces3 = geometryGroup.faces3,
chunk_faces4 = geometryGroup.faces4,
obj_faces = geometry.faces,
obj_uvs = geometry.faceVertexUvs[ 0 ],
obj_uvs2 = geometry.faceVertexUvs[ 1 ],
obj_colors = geometry.colors,
obj_skinIndices = geometry.skinIndices,
obj_skinWeights = geometry.skinWeights,
morphTargets = geometry.morphTargets,
morphNormals = geometry.morphNormals;
if ( dirtyVertices ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = vertices[ face.a ];
v2 = vertices[ face.b ];
v3 = vertices[ face.c ];
vertexArray[ offset ] = v1.x;
vertexArray[ offset + 1 ] = v1.y;
vertexArray[ offset + 2 ] = v1.z;
vertexArray[ offset + 3 ] = v2.x;
vertexArray[ offset + 4 ] = v2.y;
vertexArray[ offset + 5 ] = v2.z;
vertexArray[ offset + 6 ] = v3.x;
vertexArray[ offset + 7 ] = v3.y;
vertexArray[ offset + 8 ] = v3.z;
offset += 9;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
v1 = vertices[ face.a ];
v2 = vertices[ face.b ];
v3 = vertices[ face.c ];
v4 = vertices[ face.d ];
vertexArray[ offset ] = v1.x;
vertexArray[ offset + 1 ] = v1.y;
vertexArray[ offset + 2 ] = v1.z;
vertexArray[ offset + 3 ] = v2.x;
vertexArray[ offset + 4 ] = v2.y;
vertexArray[ offset + 5 ] = v2.z;
vertexArray[ offset + 6 ] = v3.x;
vertexArray[ offset + 7 ] = v3.y;
vertexArray[ offset + 8 ] = v3.z;
vertexArray[ offset + 9 ] = v4.x;
vertexArray[ offset + 10 ] = v4.y;
vertexArray[ offset + 11 ] = v4.z;
offset += 12;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyMorphTargets ) {
for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
offset_morphTarget = 0;
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
chf = chunk_faces3[ f ];
face = obj_faces[ chf ];
// morph positions
v1 = morphTargets[ vk ].vertices[ face.a ];
v2 = morphTargets[ vk ].vertices[ face.b ];
v3 = morphTargets[ vk ].vertices[ face.c ];
vka = morphTargetsArrays[ vk ];
vka[ offset_morphTarget ] = v1.x;
vka[ offset_morphTarget + 1 ] = v1.y;
vka[ offset_morphTarget + 2 ] = v1.z;
vka[ offset_morphTarget + 3 ] = v2.x;
vka[ offset_morphTarget + 4 ] = v2.y;
vka[ offset_morphTarget + 5 ] = v2.z;
vka[ offset_morphTarget + 6 ] = v3.x;
vka[ offset_morphTarget + 7 ] = v3.y;
vka[ offset_morphTarget + 8 ] = v3.z;
// morph normals
if ( material.morphNormals ) {
if ( needsSmoothNormals ) {
faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
n1 = faceVertexNormals.a;
n2 = faceVertexNormals.b;
n3 = faceVertexNormals.c;
} else {
n1 = morphNormals[ vk ].faceNormals[ chf ];
n2 = n1;
n3 = n1;
}
nka = morphNormalsArrays[ vk ];
nka[ offset_morphTarget ] = n1.x;
nka[ offset_morphTarget + 1 ] = n1.y;
nka[ offset_morphTarget + 2 ] = n1.z;
nka[ offset_morphTarget + 3 ] = n2.x;
nka[ offset_morphTarget + 4 ] = n2.y;
nka[ offset_morphTarget + 5 ] = n2.z;
nka[ offset_morphTarget + 6 ] = n3.x;
nka[ offset_morphTarget + 7 ] = n3.y;
nka[ offset_morphTarget + 8 ] = n3.z;
}
//
offset_morphTarget += 9;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
chf = chunk_faces4[ f ];
face = obj_faces[ chf ];
// morph positions
v1 = morphTargets[ vk ].vertices[ face.a ];
v2 = morphTargets[ vk ].vertices[ face.b ];
v3 = morphTargets[ vk ].vertices[ face.c ];
v4 = morphTargets[ vk ].vertices[ face.d ];
vka = morphTargetsArrays[ vk ];
vka[ offset_morphTarget ] = v1.x;
vka[ offset_morphTarget + 1 ] = v1.y;
vka[ offset_morphTarget + 2 ] = v1.z;
vka[ offset_morphTarget + 3 ] = v2.x;
vka[ offset_morphTarget + 4 ] = v2.y;
vka[ offset_morphTarget + 5 ] = v2.z;
vka[ offset_morphTarget + 6 ] = v3.x;
vka[ offset_morphTarget + 7 ] = v3.y;
vka[ offset_morphTarget + 8 ] = v3.z;
vka[ offset_morphTarget + 9 ] = v4.x;
vka[ offset_morphTarget + 10 ] = v4.y;
vka[ offset_morphTarget + 11 ] = v4.z;
// morph normals
if ( material.morphNormals ) {
if ( needsSmoothNormals ) {
faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
n1 = faceVertexNormals.a;
n2 = faceVertexNormals.b;
n3 = faceVertexNormals.c;
n4 = faceVertexNormals.d;
} else {
n1 = morphNormals[ vk ].faceNormals[ chf ];
n2 = n1;
n3 = n1;
n4 = n1;
}
nka = morphNormalsArrays[ vk ];
nka[ offset_morphTarget ] = n1.x;
nka[ offset_morphTarget + 1 ] = n1.y;
nka[ offset_morphTarget + 2 ] = n1.z;
nka[ offset_morphTarget + 3 ] = n2.x;
nka[ offset_morphTarget + 4 ] = n2.y;
nka[ offset_morphTarget + 5 ] = n2.z;
nka[ offset_morphTarget + 6 ] = n3.x;
nka[ offset_morphTarget + 7 ] = n3.y;
nka[ offset_morphTarget + 8 ] = n3.z;
nka[ offset_morphTarget + 9 ] = n4.x;
nka[ offset_morphTarget + 10 ] = n4.y;
nka[ offset_morphTarget + 11 ] = n4.z;
}
//
offset_morphTarget += 12;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
_gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
if ( material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
_gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
}
}
}
if ( obj_skinWeights.length ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
// weights
sw1 = obj_skinWeights[ face.a ];
sw2 = obj_skinWeights[ face.b ];
sw3 = obj_skinWeights[ face.c ];
skinWeightArray[ offset_skin ] = sw1.x;
skinWeightArray[ offset_skin + 1 ] = sw1.y;
skinWeightArray[ offset_skin + 2 ] = sw1.z;
skinWeightArray[ offset_skin + 3 ] = sw1.w;
skinWeightArray[ offset_skin + 4 ] = sw2.x;
skinWeightArray[ offset_skin + 5 ] = sw2.y;
skinWeightArray[ offset_skin + 6 ] = sw2.z;
skinWeightArray[ offset_skin + 7 ] = sw2.w;
skinWeightArray[ offset_skin + 8 ] = sw3.x;
skinWeightArray[ offset_skin + 9 ] = sw3.y;
skinWeightArray[ offset_skin + 10 ] = sw3.z;
skinWeightArray[ offset_skin + 11 ] = sw3.w;
// indices
si1 = obj_skinIndices[ face.a ];
si2 = obj_skinIndices[ face.b ];
si3 = obj_skinIndices[ face.c ];
skinIndexArray[ offset_skin ] = si1.x;
skinIndexArray[ offset_skin + 1 ] = si1.y;
skinIndexArray[ offset_skin + 2 ] = si1.z;
skinIndexArray[ offset_skin + 3 ] = si1.w;
skinIndexArray[ offset_skin + 4 ] = si2.x;
skinIndexArray[ offset_skin + 5 ] = si2.y;
skinIndexArray[ offset_skin + 6 ] = si2.z;
skinIndexArray[ offset_skin + 7 ] = si2.w;
skinIndexArray[ offset_skin + 8 ] = si3.x;
skinIndexArray[ offset_skin + 9 ] = si3.y;
skinIndexArray[ offset_skin + 10 ] = si3.z;
skinIndexArray[ offset_skin + 11 ] = si3.w;
offset_skin += 12;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
// weights
sw1 = obj_skinWeights[ face.a ];
sw2 = obj_skinWeights[ face.b ];
sw3 = obj_skinWeights[ face.c ];
sw4 = obj_skinWeights[ face.d ];
skinWeightArray[ offset_skin ] = sw1.x;
skinWeightArray[ offset_skin + 1 ] = sw1.y;
skinWeightArray[ offset_skin + 2 ] = sw1.z;
skinWeightArray[ offset_skin + 3 ] = sw1.w;
skinWeightArray[ offset_skin + 4 ] = sw2.x;
skinWeightArray[ offset_skin + 5 ] = sw2.y;
skinWeightArray[ offset_skin + 6 ] = sw2.z;
skinWeightArray[ offset_skin + 7 ] = sw2.w;
skinWeightArray[ offset_skin + 8 ] = sw3.x;
skinWeightArray[ offset_skin + 9 ] = sw3.y;
skinWeightArray[ offset_skin + 10 ] = sw3.z;
skinWeightArray[ offset_skin + 11 ] = sw3.w;
skinWeightArray[ offset_skin + 12 ] = sw4.x;
skinWeightArray[ offset_skin + 13 ] = sw4.y;
skinWeightArray[ offset_skin + 14 ] = sw4.z;
skinWeightArray[ offset_skin + 15 ] = sw4.w;
// indices
si1 = obj_skinIndices[ face.a ];
si2 = obj_skinIndices[ face.b ];
si3 = obj_skinIndices[ face.c ];
si4 = obj_skinIndices[ face.d ];
skinIndexArray[ offset_skin ] = si1.x;
skinIndexArray[ offset_skin + 1 ] = si1.y;
skinIndexArray[ offset_skin + 2 ] = si1.z;
skinIndexArray[ offset_skin + 3 ] = si1.w;
skinIndexArray[ offset_skin + 4 ] = si2.x;
skinIndexArray[ offset_skin + 5 ] = si2.y;
skinIndexArray[ offset_skin + 6 ] = si2.z;
skinIndexArray[ offset_skin + 7 ] = si2.w;
skinIndexArray[ offset_skin + 8 ] = si3.x;
skinIndexArray[ offset_skin + 9 ] = si3.y;
skinIndexArray[ offset_skin + 10 ] = si3.z;
skinIndexArray[ offset_skin + 11 ] = si3.w;
skinIndexArray[ offset_skin + 12 ] = si4.x;
skinIndexArray[ offset_skin + 13 ] = si4.y;
skinIndexArray[ offset_skin + 14 ] = si4.z;
skinIndexArray[ offset_skin + 15 ] = si4.w;
offset_skin += 16;
}
if ( offset_skin > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
}
}
if ( dirtyColors && vertexColorType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexColors = face.vertexColors;
faceColor = face.color;
if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
c1 = vertexColors[ 0 ];
c2 = vertexColors[ 1 ];
c3 = vertexColors[ 2 ];
} else {
c1 = faceColor;
c2 = faceColor;
c3 = faceColor;
}
colorArray[ offset_color ] = c1.r;
colorArray[ offset_color + 1 ] = c1.g;
colorArray[ offset_color + 2 ] = c1.b;
colorArray[ offset_color + 3 ] = c2.r;
colorArray[ offset_color + 4 ] = c2.g;
colorArray[ offset_color + 5 ] = c2.b;
colorArray[ offset_color + 6 ] = c3.r;
colorArray[ offset_color + 7 ] = c3.g;
colorArray[ offset_color + 8 ] = c3.b;
offset_color += 9;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
vertexColors = face.vertexColors;
faceColor = face.color;
if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
c1 = vertexColors[ 0 ];
c2 = vertexColors[ 1 ];
c3 = vertexColors[ 2 ];
c4 = vertexColors[ 3 ];
} else {
c1 = faceColor;
c2 = faceColor;
c3 = faceColor;
c4 = faceColor;
}
colorArray[ offset_color ] = c1.r;
colorArray[ offset_color + 1 ] = c1.g;
colorArray[ offset_color + 2 ] = c1.b;
colorArray[ offset_color + 3 ] = c2.r;
colorArray[ offset_color + 4 ] = c2.g;
colorArray[ offset_color + 5 ] = c2.b;
colorArray[ offset_color + 6 ] = c3.r;
colorArray[ offset_color + 7 ] = c3.g;
colorArray[ offset_color + 8 ] = c3.b;
colorArray[ offset_color + 9 ] = c4.r;
colorArray[ offset_color + 10 ] = c4.g;
colorArray[ offset_color + 11 ] = c4.b;
offset_color += 12;
}
if ( offset_color > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
}
if ( dirtyTangents && geometry.hasTangents ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexTangents = face.vertexTangents;
t1 = vertexTangents[ 0 ];
t2 = vertexTangents[ 1 ];
t3 = vertexTangents[ 2 ];
tangentArray[ offset_tangent ] = t1.x;
tangentArray[ offset_tangent + 1 ] = t1.y;
tangentArray[ offset_tangent + 2 ] = t1.z;
tangentArray[ offset_tangent + 3 ] = t1.w;
tangentArray[ offset_tangent + 4 ] = t2.x;
tangentArray[ offset_tangent + 5 ] = t2.y;
tangentArray[ offset_tangent + 6 ] = t2.z;
tangentArray[ offset_tangent + 7 ] = t2.w;
tangentArray[ offset_tangent + 8 ] = t3.x;
tangentArray[ offset_tangent + 9 ] = t3.y;
tangentArray[ offset_tangent + 10 ] = t3.z;
tangentArray[ offset_tangent + 11 ] = t3.w;
offset_tangent += 12;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
vertexTangents = face.vertexTangents;
t1 = vertexTangents[ 0 ];
t2 = vertexTangents[ 1 ];
t3 = vertexTangents[ 2 ];
t4 = vertexTangents[ 3 ];
tangentArray[ offset_tangent ] = t1.x;
tangentArray[ offset_tangent + 1 ] = t1.y;
tangentArray[ offset_tangent + 2 ] = t1.z;
tangentArray[ offset_tangent + 3 ] = t1.w;
tangentArray[ offset_tangent + 4 ] = t2.x;
tangentArray[ offset_tangent + 5 ] = t2.y;
tangentArray[ offset_tangent + 6 ] = t2.z;
tangentArray[ offset_tangent + 7 ] = t2.w;
tangentArray[ offset_tangent + 8 ] = t3.x;
tangentArray[ offset_tangent + 9 ] = t3.y;
tangentArray[ offset_tangent + 10 ] = t3.z;
tangentArray[ offset_tangent + 11 ] = t3.w;
tangentArray[ offset_tangent + 12 ] = t4.x;
tangentArray[ offset_tangent + 13 ] = t4.y;
tangentArray[ offset_tangent + 14 ] = t4.z;
tangentArray[ offset_tangent + 15 ] = t4.w;
offset_tangent += 16;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
}
if ( dirtyNormals && normalType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexNormals = face.vertexNormals;
faceNormal = face.normal;
if ( vertexNormals.length === 3 && needsSmoothNormals ) {
for ( i = 0; i < 3; i ++ ) {
vn = vertexNormals[ i ];
normalArray[ offset_normal ] = vn.x;
normalArray[ offset_normal + 1 ] = vn.y;
normalArray[ offset_normal + 2 ] = vn.z;
offset_normal += 3;
}
} else {
for ( i = 0; i < 3; i ++ ) {
normalArray[ offset_normal ] = faceNormal.x;
normalArray[ offset_normal + 1 ] = faceNormal.y;
normalArray[ offset_normal + 2 ] = faceNormal.z;
offset_normal += 3;
}
}
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
vertexNormals = face.vertexNormals;
faceNormal = face.normal;
if ( vertexNormals.length === 4 && needsSmoothNormals ) {
for ( i = 0; i < 4; i ++ ) {
vn = vertexNormals[ i ];
normalArray[ offset_normal ] = vn.x;
normalArray[ offset_normal + 1 ] = vn.y;
normalArray[ offset_normal + 2 ] = vn.z;
offset_normal += 3;
}
} else {
for ( i = 0; i < 4; i ++ ) {
normalArray[ offset_normal ] = faceNormal.x;
normalArray[ offset_normal + 1 ] = faceNormal.y;
normalArray[ offset_normal + 2 ] = faceNormal.z;
offset_normal += 3;
}
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
}
if ( dirtyUvs && obj_uvs && uvType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
fi = chunk_faces3[ f ];
uv = obj_uvs[ fi ];
if ( uv === undefined ) continue;
for ( i = 0; i < 3; i ++ ) {
uvi = uv[ i ];
uvArray[ offset_uv ] = uvi.u;
uvArray[ offset_uv + 1 ] = uvi.v;
offset_uv += 2;
}
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
fi = chunk_faces4[ f ];
uv = obj_uvs[ fi ];
if ( uv === undefined ) continue;
for ( i = 0; i < 4; i ++ ) {
uvi = uv[ i ];
uvArray[ offset_uv ] = uvi.u;
uvArray[ offset_uv + 1 ] = uvi.v;
offset_uv += 2;
}
}
if ( offset_uv > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
}
}
if ( dirtyUvs && obj_uvs2 && uvType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
fi = chunk_faces3[ f ];
uv2 = obj_uvs2[ fi ];
if ( uv2 === undefined ) continue;
for ( i = 0; i < 3; i ++ ) {
uv2i = uv2[ i ];
uv2Array[ offset_uv2 ] = uv2i.u;
uv2Array[ offset_uv2 + 1 ] = uv2i.v;
offset_uv2 += 2;
}
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
fi = chunk_faces4[ f ];
uv2 = obj_uvs2[ fi ];
if ( uv2 === undefined ) continue;
for ( i = 0; i < 4; i ++ ) {
uv2i = uv2[ i ];
uv2Array[ offset_uv2 ] = uv2i.u;
uv2Array[ offset_uv2 + 1 ] = uv2i.v;
offset_uv2 += 2;
}
}
if ( offset_uv2 > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
}
}
if ( dirtyElements ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
faceArray[ offset_face ] = vertexIndex;
faceArray[ offset_face + 1 ] = vertexIndex + 1;
faceArray[ offset_face + 2 ] = vertexIndex + 2;
offset_face += 3;
lineArray[ offset_line ] = vertexIndex;
lineArray[ offset_line + 1 ] = vertexIndex + 1;
lineArray[ offset_line + 2 ] = vertexIndex;
lineArray[ offset_line + 3 ] = vertexIndex + 2;
lineArray[ offset_line + 4 ] = vertexIndex + 1;
lineArray[ offset_line + 5 ] = vertexIndex + 2;
offset_line += 6;
vertexIndex += 3;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
faceArray[ offset_face ] = vertexIndex;
faceArray[ offset_face + 1 ] = vertexIndex + 1;
faceArray[ offset_face + 2 ] = vertexIndex + 3;
faceArray[ offset_face + 3 ] = vertexIndex + 1;
faceArray[ offset_face + 4 ] = vertexIndex + 2;
faceArray[ offset_face + 5 ] = vertexIndex + 3;
offset_face += 6;
lineArray[ offset_line ] = vertexIndex;
lineArray[ offset_line + 1 ] = vertexIndex + 1;
lineArray[ offset_line + 2 ] = vertexIndex;
lineArray[ offset_line + 3 ] = vertexIndex + 3;
lineArray[ offset_line + 4 ] = vertexIndex + 1;
lineArray[ offset_line + 5 ] = vertexIndex + 2;
lineArray[ offset_line + 6 ] = vertexIndex + 2;
lineArray[ offset_line + 7 ] = vertexIndex + 3;
offset_line += 8;
vertexIndex += 4;
}
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( ! customAttribute.__original.needsUpdate ) continue;
offset_custom = 0;
offset_customSrc = 0;
if ( customAttribute.size === 1 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
offset_custom += 3;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
offset_custom += 4;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
customAttribute.array[ offset_custom ] = value;
customAttribute.array[ offset_custom + 1 ] = value;
customAttribute.array[ offset_custom + 2 ] = value;
offset_custom += 3;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces4[ f ] ];
customAttribute.array[ offset_custom ] = value;
customAttribute.array[ offset_custom + 1 ] = value;
customAttribute.array[ offset_custom + 2 ] = value;
customAttribute.array[ offset_custom + 3 ] = value;
offset_custom += 4;
}
}
} else if ( customAttribute.size === 2 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
offset_custom += 6;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
v4 = customAttribute.value[ face.d ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
customAttribute.array[ offset_custom + 6 ] = v4.x;
customAttribute.array[ offset_custom + 7 ] = v4.y;
offset_custom += 8;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
offset_custom += 6;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces4[ f ] ];
v1 = value;
v2 = value;
v3 = value;
v4 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
customAttribute.array[ offset_custom + 6 ] = v4.x;
customAttribute.array[ offset_custom + 7 ] = v4.y;
offset_custom += 8;
}
}
} else if ( customAttribute.size === 3 ) {
var pp;
if ( customAttribute.type === "c" ) {
pp = [ "r", "g", "b" ];
} else {
pp = [ "x", "y", "z" ];
}
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
v4 = customAttribute.value[ face.d ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
offset_custom += 12;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces4[ f ] ];
v1 = value;
v2 = value;
v3 = value;
v4 = value;
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
offset_custom += 12;
}
} else if ( customAttribute.boundTo === "faceVertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces4[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
v4 = value[ 3 ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
offset_custom += 12;
}
}
} else if ( customAttribute.size === 4 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces4[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
v4 = customAttribute.value[ face.d ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
customAttribute.array[ offset_custom + 12 ] = v4.x;
customAttribute.array[ offset_custom + 13 ] = v4.y;
customAttribute.array[ offset_custom + 14 ] = v4.z;
customAttribute.array[ offset_custom + 15 ] = v4.w;
offset_custom += 16;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces4[ f ] ];
v1 = value;
v2 = value;
v3 = value;
v4 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
customAttribute.array[ offset_custom + 12 ] = v4.x;
customAttribute.array[ offset_custom + 13 ] = v4.y;
customAttribute.array[ offset_custom + 14 ] = v4.z;
customAttribute.array[ offset_custom + 15 ] = v4.w;
offset_custom += 16;
}
} else if ( customAttribute.boundTo === "faceVertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces4[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
v4 = value[ 3 ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
customAttribute.array[ offset_custom + 12 ] = v4.x;
customAttribute.array[ offset_custom + 13 ] = v4.y;
customAttribute.array[ offset_custom + 14 ] = v4.z;
customAttribute.array[ offset_custom + 15 ] = v4.w;
offset_custom += 16;
}
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
if ( dispose ) {
delete geometryGroup.__inittedArrays;
delete geometryGroup.__colorArray;
delete geometryGroup.__normalArray;
delete geometryGroup.__tangentArray;
delete geometryGroup.__uvArray;
delete geometryGroup.__uv2Array;
delete geometryGroup.__faceArray;
delete geometryGroup.__vertexArray;
delete geometryGroup.__lineArray;
delete geometryGroup.__skinIndexArray;
delete geometryGroup.__skinWeightArray;
}
};
function setDirectBuffers ( geometry, hint, dispose ) {
var attributes = geometry.attributes;
var index = attributes[ "index" ];
var position = attributes[ "position" ];
var normal = attributes[ "normal" ];
var uv = attributes[ "uv" ];
var color = attributes[ "color" ];
var tangent = attributes[ "tangent" ];
if ( geometry.elementsNeedUpdate && index !== undefined ) {
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
}
if ( geometry.verticesNeedUpdate && position !== undefined ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
}
if ( geometry.normalsNeedUpdate && normal !== undefined ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
}
if ( geometry.uvsNeedUpdate && uv !== undefined ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
}
if ( geometry.colorsNeedUpdate && color !== undefined ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
}
if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
}
if ( dispose ) {
for ( var i in geometry.attributes ) {
delete geometry.attributes[ i ].array;
}
}
};
// Buffer rendering
this.renderBufferImmediate = function ( object, program, material ) {
if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
if ( object.hasPositions ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.position );
_gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
if ( material.shading === THREE.FlatShading ) {
var nx, ny, nz,
nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
normalArray,
i, il = object.count * 3;
for( i = 0; i < il; i += 9 ) {
normalArray = object.normalArray;
nax = normalArray[ i ];
nay = normalArray[ i + 1 ];
naz = normalArray[ i + 2 ];
nbx = normalArray[ i + 3 ];
nby = normalArray[ i + 4 ];
nbz = normalArray[ i + 5 ];
ncx = normalArray[ i + 6 ];
ncy = normalArray[ i + 7 ];
ncz = normalArray[ i + 8 ];
nx = ( nax + nbx + ncx ) / 3;
ny = ( nay + nby + ncy ) / 3;
nz = ( naz + nbz + ncz ) / 3;
normalArray[ i ] = nx;
normalArray[ i + 1 ] = ny;
normalArray[ i + 2 ] = nz;
normalArray[ i + 3 ] = nx;
normalArray[ i + 4 ] = ny;
normalArray[ i + 5 ] = nz;
normalArray[ i + 6 ] = nx;
normalArray[ i + 7 ] = ny;
normalArray[ i + 8 ] = nz;
}
}
_gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.normal );
_gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasUvs && material.map ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.uv );
_gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.color );
_gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
}
_gl.drawArrays( _gl.TRIANGLES, 0, object.count );
object.count = 0;
};
this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
if ( material.visible === false ) return;
var program, attributes, linewidth, primitives, a, attribute;
program = setProgram( camera, lights, fog, material, object );
attributes = program.attributes;
var updateBuffers = false,
wireframeBit = material.wireframe ? 1 : 0,
geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
if ( geometryHash !== _currentGeometryGroupHash ) {
_currentGeometryGroupHash = geometryHash;
updateBuffers = true;
}
// render mesh
if ( object instanceof THREE.Mesh ) {
var offsets = geometry.offsets;
// if there is more than 1 chunk
// must set attribute pointers to use new offsets for each chunk
// even if geometry and materials didn't change
if ( offsets.length > 1 ) updateBuffers = true;
for ( var i = 0, il = offsets.length; i < il; ++ i ) {
var startIndex = offsets[ i ].index;
if ( updateBuffers ) {
// vertices
var position = geometry.attributes[ "position" ];
var positionSize = position.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
_gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
// normals
var normal = geometry.attributes[ "normal" ];
if ( attributes.normal >= 0 && normal ) {
var normalSize = normal.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
_gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
}
// uvs
var uv = geometry.attributes[ "uv" ];
if ( attributes.uv >= 0 && uv ) {
if ( uv.buffer ) {
var uvSize = uv.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
_gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
_gl.enableVertexAttribArray( attributes.uv );
} else {
_gl.disableVertexAttribArray( attributes.uv );
}
}
// colors
var color = geometry.attributes[ "color" ];
if ( attributes.color >= 0 && color ) {
var colorSize = color.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
_gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
}
// tangents
var tangent = geometry.attributes[ "tangent" ];
if ( attributes.tangent >= 0 && tangent ) {
var tangentSize = tangent.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
_gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
}
// indices
var index = geometry.attributes[ "index" ];
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
}
// render indexed triangles
_gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
_this.info.render.calls ++;
_this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
_this.info.render.faces += offsets[ i ].count / 3;
}
// render particles
} else if ( object instanceof THREE.ParticleSystem ) {
if ( updateBuffers ) {
// vertices
var position = geometry.attributes[ "position" ];
var positionSize = position.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
_gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
// colors
var color = geometry.attributes[ "color" ];
if ( attributes.color >= 0 && color ) {
var colorSize = color.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
_gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
}
// render particles
_gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
_this.info.render.calls ++;
_this.info.render.points += position.numItems / 3;
}
}
};
this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
if ( material.visible === false ) return;
var program, attributes, linewidth, primitives, a, attribute, i, il;
program = setProgram( camera, lights, fog, material, object );
attributes = program.attributes;
var updateBuffers = false,
wireframeBit = material.wireframe ? 1 : 0,
geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
if ( geometryGroupHash !== _currentGeometryGroupHash ) {
_currentGeometryGroupHash = geometryGroupHash;
updateBuffers = true;
}
// vertices
if ( !material.morphTargets && attributes.position >= 0 ) {
if ( updateBuffers ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
} else {
if ( object.morphTargetBase ) {
setupMorphTargets( material, geometryGroup, object );
}
}
if ( updateBuffers ) {
// custom attributes
// Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
if ( geometryGroup.__webglCustomAttributesList ) {
for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
attribute = geometryGroup.__webglCustomAttributesList[ i ];
if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
_gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
}
}
}
// colors
if ( attributes.color >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
_gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
}
// normals
if ( attributes.normal >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
_gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
}
// tangents
if ( attributes.tangent >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
_gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
}
// uvs
if ( attributes.uv >= 0 ) {
if ( geometryGroup.__webglUVBuffer ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
_gl.enableVertexAttribArray( attributes.uv );
} else {
_gl.disableVertexAttribArray( attributes.uv );
}
}
if ( attributes.uv2 >= 0 ) {
if ( geometryGroup.__webglUV2Buffer ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
_gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
_gl.enableVertexAttribArray( attributes.uv2 );
} else {
_gl.disableVertexAttribArray( attributes.uv2 );
}
}
if ( material.skinning &&
attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
_gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
_gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
}
}
// render mesh
if ( object instanceof THREE.Mesh ) {
// wireframe
if ( material.wireframe ) {
setLineWidth( material.wireframeLinewidth );
if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
_gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
// triangles
} else {
if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
_gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
}
_this.info.render.calls ++;
_this.info.render.vertices += geometryGroup.__webglFaceCount;
_this.info.render.faces += geometryGroup.__webglFaceCount / 3;
// render lines
} else if ( object instanceof THREE.Line ) {
primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
setLineWidth( material.linewidth );
_gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
_this.info.render.calls ++;
// render particles
} else if ( object instanceof THREE.ParticleSystem ) {
_gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
_this.info.render.calls ++;
_this.info.render.points += geometryGroup.__webglParticleCount;
// render ribbon
} else if ( object instanceof THREE.Ribbon ) {
_gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
_this.info.render.calls ++;
}
};
function setupMorphTargets ( material, geometryGroup, object ) {
// set base
var attributes = material.program.attributes;
if ( object.morphTargetBase !== -1 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
} else if ( attributes.position >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.morphTargetForcedOrder.length ) {
// set forced order
var m = 0;
var order = object.morphTargetForcedOrder;
var influences = object.morphTargetInfluences;
while ( m < material.numSupportedMorphTargets && m < order.length ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
if ( material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
m ++;
}
} else {
// find the most influencing
var influence, activeInfluenceIndices = [];
var influences = object.morphTargetInfluences;
var i, il = influences.length;
for ( i = 0; i < il; i ++ ) {
influence = influences[ i ];
if ( influence > 0 ) {
activeInfluenceIndices.push( [ i, influence ] );
}
}
if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
activeInfluenceIndices.sort( numericalSort );
activeInfluenceIndices.length = material.numSupportedMorphTargets;
} else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
activeInfluenceIndices.sort( numericalSort );
} else if ( activeInfluenceIndices.length === 0 ) {
activeInfluenceIndices.push( [ 0, 0 ] );
};
var influenceIndex, m = 0;
while ( m < material.numSupportedMorphTargets ) {
if ( activeInfluenceIndices[ m ] ) {
influenceIndex = activeInfluenceIndices[ m ][ 0 ];
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
if ( material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
} else {
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
if ( material.morphNormals ) {
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
object.__webglMorphTargetInfluences[ m ] = 0;
}
m ++;
}
}
// load updated influences uniform
if ( material.program.uniforms.morphTargetInfluences !== null ) {
_gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
}
};
// Sorting
function painterSort ( a, b ) {
return b.z - a.z;
};
function numericalSort ( a, b ) {
return b[ 1 ] - a[ 1 ];
};
// Rendering
this.render = function ( scene, camera, renderTarget, forceClear ) {
if ( camera instanceof THREE.Camera === false ) {
console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
return;
}
var i, il,
webglObject, object,
renderList,
lights = scene.__lights,
fog = scene.fog;
// reset caching for this frame
_currentMaterialId = -1;
_lightsNeedUpdate = true;
// update scene graph
if ( this.autoUpdateScene ) scene.updateMatrixWorld();
// update camera matrices and frustum
if ( camera.parent === undefined ) camera.updateMatrixWorld();
if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
_projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// update WebGL objects
if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
// custom render plugins (pre pass)
renderPlugins( this.renderPluginsPre, scene, camera );
//
_this.info.render.calls = 0;
_this.info.render.vertices = 0;
_this.info.render.faces = 0;
_this.info.render.points = 0;
this.setRenderTarget( renderTarget );
if ( this.autoClear || forceClear ) {
this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
}
// set matrices for regular objects (frustum culled)
renderList = scene.__webglObjects;
for ( i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
webglObject.render = false;
if ( object.visible ) {
if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
//object.matrixWorld.flattenToArray( object._modelMatrixArray );
setupMatrices( object, camera );
unrollBufferMaterial( webglObject );
webglObject.render = true;
if ( this.sortObjects === true ) {
if ( object.renderDepth !== null ) {
webglObject.z = object.renderDepth;
} else {
_vector3.copy( object.matrixWorld.getPosition() );
_projScreenMatrix.multiplyVector3( _vector3 );
webglObject.z = _vector3.z;
}
}
}
}
}
if ( this.sortObjects ) {
renderList.sort( painterSort );
}
// set matrices for immediate objects
renderList = scene.__webglObjectsImmediate;
for ( i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
if ( object.visible ) {
/*
if ( object.matrixAutoUpdate ) {
object.matrixWorld.flattenToArray( object._modelMatrixArray );
}
*/
setupMatrices( object, camera );
unrollImmediateBufferMaterial( webglObject );
}
}
if ( scene.overrideMaterial ) {
var material = scene.overrideMaterial;
this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
this.setDepthTest( material.depthTest );
this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
} else {
// opaque pass (front-to-back order)
this.setBlending( THREE.NormalBlending );
renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
// transparent pass (back-to-front order)
renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
}
// custom render plugins (post pass)
renderPlugins( this.renderPluginsPost, scene, camera );
// Generate mipmap if we're using any kind of mipmap filtering
if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
updateRenderTargetMipmap( renderTarget );
}
// Ensure depth buffer writing is enabled so it can be cleared on next render
this.setDepthTest( true );
this.setDepthWrite( true );
// _gl.finish();
};
function renderPlugins( plugins, scene, camera ) {
if ( ! plugins.length ) return;
for ( var i = 0, il = plugins.length; i < il; i ++ ) {
// reset state for plugin (to start from clean slate)
_currentProgram = null;
_currentCamera = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_oldDoubleSided = -1;
_oldFlipSided = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
// reset state after plugin (anything could have changed)
_currentProgram = null;
_currentCamera = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_oldDoubleSided = -1;
_oldFlipSided = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
}
};
function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
var webglObject, object, buffer, material, start, end, delta;
if ( reverse ) {
start = renderList.length - 1;
end = -1;
delta = -1;
} else {
start = 0;
end = renderList.length;
delta = 1;
}
for ( var i = start; i !== end; i += delta ) {
webglObject = renderList[ i ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
if ( overrideMaterial ) {
material = overrideMaterial;
} else {
material = webglObject[ materialType ];
if ( ! material ) continue;
if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
_this.setDepthTest( material.depthTest );
_this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
}
_this.setMaterialFaces( material );
if ( buffer instanceof THREE.BufferGeometry ) {
_this.renderBufferDirect( camera, lights, fog, material, buffer, object );
} else {
_this.renderBuffer( camera, lights, fog, material, buffer, object );
}
}
}
};
function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
var webglObject, object, material, program;
for ( var i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
if ( object.visible ) {
if ( overrideMaterial ) {
material = overrideMaterial;
} else {
material = webglObject[ materialType ];
if ( ! material ) continue;
if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
_this.setDepthTest( material.depthTest );
_this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
}
_this.renderImmediateObject( camera, lights, fog, material, object );
}
}
};
this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
var program = setProgram( camera, lights, fog, material, object );
_currentGeometryGroupHash = -1;
_this.setMaterialFaces( material );
if ( object.immediateRenderCallback ) {
object.immediateRenderCallback( program, _gl, _frustum );
} else {
object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
}
};
function unrollImmediateBufferMaterial ( globject ) {
var object = globject.object,
material = object.material;
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
};
function unrollBufferMaterial ( globject ) {
var object = globject.object,
buffer = globject.buffer,
material, materialIndex, meshMaterial;
meshMaterial = object.material;
if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
materialIndex = buffer.materialIndex;
if ( materialIndex >= 0 ) {
material = object.geometry.materials[ materialIndex ];
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
}
} else {
material = meshMaterial;
if ( material ) {
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
}
}
};
// Geometry splitting
function sortFacesByMaterial ( geometry ) {
var f, fl, face, materialIndex, vertices,
materialHash, groupHash,
hash_map = {};
var numMorphTargets = geometry.morphTargets.length;
var numMorphNormals = geometry.morphNormals.length;
geometry.geometryGroups = {};
for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
face = geometry.faces[ f ];
materialIndex = face.materialIndex;
materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
if ( hash_map[ materialHash ] === undefined ) {
hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
}
groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
if ( geometry.geometryGroups[ groupHash ] === undefined ) {
geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
}
vertices = face instanceof THREE.Face3 ? 3 : 4;
if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
hash_map[ materialHash ].counter += 1;
groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
if ( geometry.geometryGroups[ groupHash ] === undefined ) {
geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
}
}
if ( face instanceof THREE.Face3 ) {
geometry.geometryGroups[ groupHash ].faces3.push( f );
} else {
geometry.geometryGroups[ groupHash ].faces4.push( f );
}
geometry.geometryGroups[ groupHash ].vertices += vertices;
}
geometry.geometryGroupsList = [];
for ( var g in geometry.geometryGroups ) {
geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
}
};
// Objects refresh
this.initWebGLObjects = function ( scene ) {
if ( !scene.__webglObjects ) {
scene.__webglObjects = [];
scene.__webglObjectsImmediate = [];
scene.__webglSprites = [];
scene.__webglFlares = [];
}
while ( scene.__objectsAdded.length ) {
addObject( scene.__objectsAdded[ 0 ], scene );
scene.__objectsAdded.splice( 0, 1 );
}
while ( scene.__objectsRemoved.length ) {
removeObject( scene.__objectsRemoved[ 0 ], scene );
scene.__objectsRemoved.splice( 0, 1 );
}
// update must be called after objects adding / removal
for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
updateObject( scene.__webglObjects[ o ].object );
}
};
// Objects adding
function addObject ( object, scene ) {
var g, geometry, geometryGroup;
if ( ! object.__webglInit ) {
object.__webglInit = true;
object._modelViewMatrix = new THREE.Matrix4();
object._normalMatrix = new THREE.Matrix3();
if ( object instanceof THREE.Mesh ) {
geometry = object.geometry;
if ( geometry instanceof THREE.Geometry ) {
if ( geometry.geometryGroups === undefined ) {
sortFacesByMaterial( geometry );
}
// create separate VBOs per geometry chunk
for ( g in geometry.geometryGroups ) {
geometryGroup = geometry.geometryGroups[ g ];
// initialise VBO on the first access
if ( ! geometryGroup.__webglVertexBuffer ) {
createMeshBuffers( geometryGroup );
initMeshBuffers( geometryGroup, object );
geometry.verticesNeedUpdate = true;
geometry.morphTargetsNeedUpdate = true;
geometry.elementsNeedUpdate = true;
geometry.uvsNeedUpdate = true;
geometry.normalsNeedUpdate = true;
geometry.tangentsNeedUpdate = true;
geometry.colorsNeedUpdate = true;
}
}
} else if ( geometry instanceof THREE.BufferGeometry ) {
initDirectBuffers( geometry );
}
} else if ( object instanceof THREE.Ribbon ) {
geometry = object.geometry;
if( ! geometry.__webglVertexBuffer ) {
createRibbonBuffers( geometry );
initRibbonBuffers( geometry );
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
}
} else if ( object instanceof THREE.Line ) {
geometry = object.geometry;
if( ! geometry.__webglVertexBuffer ) {
createLineBuffers( geometry );
initLineBuffers( geometry, object );
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
}
} else if ( object instanceof THREE.ParticleSystem ) {
geometry = object.geometry;
if ( ! geometry.__webglVertexBuffer ) {
if ( geometry instanceof THREE.Geometry ) {
createParticleBuffers( geometry );
initParticleBuffers( geometry, object );
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
} else if ( geometry instanceof THREE.BufferGeometry ) {
initDirectBuffers( geometry );
}
}
}
}
if ( ! object.__webglActive ) {
if ( object instanceof THREE.Mesh ) {
geometry = object.geometry;
if ( geometry instanceof THREE.BufferGeometry ) {
addBuffer( scene.__webglObjects, geometry, object );
} else {
for ( g in geometry.geometryGroups ) {
geometryGroup = geometry.geometryGroups[ g ];
addBuffer( scene.__webglObjects, geometryGroup, object );
}
}
} else if ( object instanceof THREE.Ribbon ||
object instanceof THREE.Line ||
object instanceof THREE.ParticleSystem ) {
geometry = object.geometry;
addBuffer( scene.__webglObjects, geometry, object );
} else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
addBufferImmediate( scene.__webglObjectsImmediate, object );
} else if ( object instanceof THREE.Sprite ) {
scene.__webglSprites.push( object );
} else if ( object instanceof THREE.LensFlare ) {
scene.__webglFlares.push( object );
}
object.__webglActive = true;
}
};
function addBuffer ( objlist, buffer, object ) {
objlist.push(
{
buffer: buffer,
object: object,
opaque: null,
transparent: null
}
);
};
function addBufferImmediate ( objlist, object ) {
objlist.push(
{
object: object,
opaque: null,
transparent: null
}
);
};
// Objects updates
function updateObject ( object ) {
var geometry = object.geometry,
geometryGroup, customAttributesDirty, material;
if ( object instanceof THREE.Mesh ) {
if ( geometry instanceof THREE.BufferGeometry ) {
if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
}
geometry.verticesNeedUpdate = false;
geometry.elementsNeedUpdate = false;
geometry.uvsNeedUpdate = false;
geometry.normalsNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.tangentsNeedUpdate = false;
} else {
// check all geometry groups
for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
geometryGroup = geometry.geometryGroupsList[ i ];
material = getBufferMaterial( object, geometryGroup );
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
}
}
geometry.verticesNeedUpdate = false;
geometry.morphTargetsNeedUpdate = false;
geometry.elementsNeedUpdate = false;
geometry.uvsNeedUpdate = false;
geometry.normalsNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.tangentsNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
}
} else if ( object instanceof THREE.Ribbon ) {
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
} else if ( object instanceof THREE.Line ) {
material = getBufferMaterial( object, geometryGroup );
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
} else if ( object instanceof THREE.ParticleSystem ) {
if ( geometry instanceof THREE.BufferGeometry ) {
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
} else {
material = getBufferMaterial( object, geometryGroup );
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
}
}
};
// Objects updates - custom attributes check
function areCustomAttributesDirty ( material ) {
for ( var a in material.attributes ) {
if ( material.attributes[ a ].needsUpdate ) return true;
}
return false;
};
function clearCustomAttributes ( material ) {
for ( var a in material.attributes ) {
material.attributes[ a ].needsUpdate = false;
}
};
// Objects removal
function removeObject ( object, scene ) {
if ( object instanceof THREE.Mesh ||
object instanceof THREE.ParticleSystem ||
object instanceof THREE.Ribbon ||
object instanceof THREE.Line ) {
removeInstances( scene.__webglObjects, object );
} else if ( object instanceof THREE.Sprite ) {
removeInstancesDirect( scene.__webglSprites, object );
} else if ( object instanceof THREE.LensFlare ) {
removeInstancesDirect( scene.__webglFlares, object );
} else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
removeInstances( scene.__webglObjectsImmediate, object );
}
object.__webglActive = false;
};
function removeInstances ( objlist, object ) {
for ( var o = objlist.length - 1; o >= 0; o -- ) {
if ( objlist[ o ].object === object ) {
objlist.splice( o, 1 );
}
}
};
function removeInstancesDirect ( objlist, object ) {
for ( var o = objlist.length - 1; o >= 0; o -- ) {
if ( objlist[ o ] === object ) {
objlist.splice( o, 1 );
}
}
};
// Materials
this.initMaterial = function ( material, lights, fog, object ) {
var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
if ( material instanceof THREE.MeshDepthMaterial ) {
shaderID = 'depth';
} else if ( material instanceof THREE.MeshNormalMaterial ) {
shaderID = 'normal';
} else if ( material instanceof THREE.MeshBasicMaterial ) {
shaderID = 'basic';
} else if ( material instanceof THREE.MeshLambertMaterial ) {
shaderID = 'lambert';
} else if ( material instanceof THREE.MeshPhongMaterial ) {
shaderID = 'phong';
} else if ( material instanceof THREE.LineBasicMaterial ) {
shaderID = 'basic';
} else if ( material instanceof THREE.ParticleBasicMaterial ) {
shaderID = 'particle_basic';
}
if ( shaderID ) {
setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
}
// heuristics to create shader parameters according to lights in the scene
// (not to blow over maxLights budget)
maxLightCount = allocateLights( lights );
maxShadows = allocateShadows( lights );
maxBones = allocateBones( object );
parameters = {
map: !!material.map,
envMap: !!material.envMap,
lightMap: !!material.lightMap,
bumpMap: !!material.bumpMap,
normalMap: !!material.normalMap,
specularMap: !!material.specularMap,
vertexColors: material.vertexColors,
fog: fog,
useFog: material.fog,
sizeAttenuation: material.sizeAttenuation,
skinning: material.skinning,
maxBones: maxBones,
useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
boneTextureWidth: object && object.boneTextureWidth,
boneTextureHeight: object && object.boneTextureHeight,
morphTargets: material.morphTargets,
morphNormals: material.morphNormals,
maxMorphTargets: this.maxMorphTargets,
maxMorphNormals: this.maxMorphNormals,
maxDirLights: maxLightCount.directional,
maxPointLights: maxLightCount.point,
maxSpotLights: maxLightCount.spot,
maxHemiLights: maxLightCount.hemi,
maxShadows: maxShadows,
shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
shadowMapSoft: this.shadowMapSoft,
shadowMapDebug: this.shadowMapDebug,
shadowMapCascade: this.shadowMapCascade,
alphaTest: material.alphaTest,
metal: material.metal,
perPixel: material.perPixel,
wrapAround: material.wrapAround,
doubleSided: material.side === THREE.DoubleSide,
flipSided: material.side === THREE.BackSide
};
material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
var attributes = material.program.attributes;
if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
if ( material.skinning &&
attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
_gl.enableVertexAttribArray( attributes.skinIndex );
_gl.enableVertexAttribArray( attributes.skinWeight );
}
if ( material.attributes ) {
for ( a in material.attributes ) {
if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
}
}
if ( material.morphTargets ) {
material.numSupportedMorphTargets = 0;
var id, base = "morphTarget";
for ( i = 0; i < this.maxMorphTargets; i ++ ) {
id = base + i;
if ( attributes[ id ] >= 0 ) {
_gl.enableVertexAttribArray( attributes[ id ] );
material.numSupportedMorphTargets ++;
}
}
}
if ( material.morphNormals ) {
material.numSupportedMorphNormals = 0;
var id, base = "morphNormal";
for ( i = 0; i < this.maxMorphNormals; i ++ ) {
id = base + i;
if ( attributes[ id ] >= 0 ) {
_gl.enableVertexAttribArray( attributes[ id ] );
material.numSupportedMorphNormals ++;
}
}
}
material.uniformsList = [];
for ( u in material.uniforms ) {
material.uniformsList.push( [ material.uniforms[ u ], u ] );
}
};
function setMaterialShaders( material, shaders ) {
material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
material.vertexShader = shaders.vertexShader;
material.fragmentShader = shaders.fragmentShader;
};
function setProgram( camera, lights, fog, material, object ) {
_usedTextureUnits = 0;
if ( material.needsUpdate ) {
if ( material.program ) _this.deallocateMaterial( material );
_this.initMaterial( material, lights, fog, object );
material.needsUpdate = false;
}
if ( material.morphTargets ) {
if ( ! object.__webglMorphTargetInfluences ) {
object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
}
}
var refreshMaterial = false;
var program = material.program,
p_uniforms = program.uniforms,
m_uniforms = material.uniforms;
if ( program !== _currentProgram ) {
_gl.useProgram( program );
_currentProgram = program;
refreshMaterial = true;
}
if ( material.id !== _currentMaterialId ) {
_currentMaterialId = material.id;
refreshMaterial = true;
}
if ( refreshMaterial || camera !== _currentCamera ) {
_gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
if ( camera !== _currentCamera ) _currentCamera = camera;
}
// skinning uniforms must be set even if material didn't change
// auto-setting of texture unit for bone texture must go before other textures
// not sure why, but otherwise weird things happen
if ( material.skinning ) {
if ( _supportsBoneTextures && object.useVertexTexture ) {
if ( p_uniforms.boneTexture !== null ) {
var textureUnit = getTextureUnit();
_gl.uniform1i( p_uniforms.boneTexture, textureUnit );
_this.setTexture( object.boneTexture, textureUnit );
}
} else {
if ( p_uniforms.boneGlobalMatrices !== null ) {
_gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
}
}
}
if ( refreshMaterial ) {
// refresh uniforms common to several materials
if ( fog && material.fog ) {
refreshUniformsFog( m_uniforms, fog );
}
if ( material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material.lights ) {
if ( _lightsNeedUpdate ) {
setupLights( program, lights );
_lightsNeedUpdate = false;
}
refreshUniformsLights( m_uniforms, _lights );
}
if ( material instanceof THREE.MeshBasicMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.MeshPhongMaterial ) {
refreshUniformsCommon( m_uniforms, material );
}
// refresh single material specific uniforms
if ( material instanceof THREE.LineBasicMaterial ) {
refreshUniformsLine( m_uniforms, material );
} else if ( material instanceof THREE.ParticleBasicMaterial ) {
refreshUniformsParticle( m_uniforms, material );
} else if ( material instanceof THREE.MeshPhongMaterial ) {
refreshUniformsPhong( m_uniforms, material );
} else if ( material instanceof THREE.MeshLambertMaterial ) {
refreshUniformsLambert( m_uniforms, material );
} else if ( material instanceof THREE.MeshDepthMaterial ) {
m_uniforms.mNear.value = camera.near;
m_uniforms.mFar.value = camera.far;
m_uniforms.opacity.value = material.opacity;
} else if ( material instanceof THREE.MeshNormalMaterial ) {
m_uniforms.opacity.value = material.opacity;
}
if ( object.receiveShadow && ! material._shadowPass ) {
refreshUniformsShadow( m_uniforms, lights );
}
// load common uniforms
loadUniformsGeneric( program, material.uniformsList );
// load material specific uniforms
// (shader material also gets them for the sake of genericity)
if ( material instanceof THREE.ShaderMaterial ||
material instanceof THREE.MeshPhongMaterial ||
material.envMap ) {
if ( p_uniforms.cameraPosition !== null ) {
var position = camera.matrixWorld.getPosition();
_gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
}
}
if ( material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.ShaderMaterial ||
material.skinning ) {
if ( p_uniforms.viewMatrix !== null ) {
_gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
}
}
}
loadUniformsMatrices( p_uniforms, object );
if ( p_uniforms.modelMatrix !== null ) {
_gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
}
return program;
};
// Uniforms (refresh uniforms objects)
function refreshUniformsCommon ( uniforms, material ) {
uniforms.opacity.value = material.opacity;
if ( _this.gammaInput ) {
uniforms.diffuse.value.copyGammaToLinear( material.color );
} else {
uniforms.diffuse.value = material.color;
}
uniforms.map.value = material.map;
uniforms.lightMap.value = material.lightMap;
uniforms.specularMap.value = material.specularMap;
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
}
// uv repeat and offset setting priorities
// 1. color map
// 2. specular map
// 3. normal map
// 4. bump map
var uvScaleMap;
if ( material.map ) {
uvScaleMap = material.map;
} else if ( material.specularMap ) {
uvScaleMap = material.specularMap;
} else if ( material.normalMap ) {
uvScaleMap = material.normalMap;
} else if ( material.bumpMap ) {
uvScaleMap = material.bumpMap;
}
if ( uvScaleMap !== undefined ) {
var offset = uvScaleMap.offset;
var repeat = uvScaleMap.repeat;
uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
}
uniforms.envMap.value = material.envMap;
uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
if ( _this.gammaInput ) {
//uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
uniforms.reflectivity.value = material.reflectivity;
} else {
uniforms.reflectivity.value = material.reflectivity;
}
uniforms.refractionRatio.value = material.refractionRatio;
uniforms.combine.value = material.combine;
uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
};
function refreshUniformsLine ( uniforms, material ) {
uniforms.diffuse.value = material.color;
uniforms.opacity.value = material.opacity;
};
function refreshUniformsParticle ( uniforms, material ) {
uniforms.psColor.value = material.color;
uniforms.opacity.value = material.opacity;
uniforms.size.value = material.size;
uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
uniforms.map.value = material.map;
};
function refreshUniformsFog ( uniforms, fog ) {
uniforms.fogColor.value = fog.color;
if ( fog instanceof THREE.Fog ) {
uniforms.fogNear.value = fog.near;
uniforms.fogFar.value = fog.far;
} else if ( fog instanceof THREE.FogExp2 ) {
uniforms.fogDensity.value = fog.density;
}
};
function refreshUniformsPhong ( uniforms, material ) {
uniforms.shininess.value = material.shininess;
if ( _this.gammaInput ) {
uniforms.ambient.value.copyGammaToLinear( material.ambient );
uniforms.emissive.value.copyGammaToLinear( material.emissive );
uniforms.specular.value.copyGammaToLinear( material.specular );
} else {
uniforms.ambient.value = material.ambient;
uniforms.emissive.value = material.emissive;
uniforms.specular.value = material.specular;
}
if ( material.wrapAround ) {
uniforms.wrapRGB.value.copy( material.wrapRGB );
}
};
function refreshUniformsLambert ( uniforms, material ) {
if ( _this.gammaInput ) {
uniforms.ambient.value.copyGammaToLinear( material.ambient );
uniforms.emissive.value.copyGammaToLinear( material.emissive );
} else {
uniforms.ambient.value = material.ambient;
uniforms.emissive.value = material.emissive;
}
if ( material.wrapAround ) {
uniforms.wrapRGB.value.copy( material.wrapRGB );
}
};
function refreshUniformsLights ( uniforms, lights ) {
uniforms.ambientLightColor.value = lights.ambient;
uniforms.directionalLightColor.value = lights.directional.colors;
uniforms.directionalLightDirection.value = lights.directional.positions;
uniforms.pointLightColor.value = lights.point.colors;
uniforms.pointLightPosition.value = lights.point.positions;
uniforms.pointLightDistance.value = lights.point.distances;
uniforms.spotLightColor.value = lights.spot.colors;
uniforms.spotLightPosition.value = lights.spot.positions;
uniforms.spotLightDistance.value = lights.spot.distances;
uniforms.spotLightDirection.value = lights.spot.directions;
uniforms.spotLightAngle.value = lights.spot.angles;
uniforms.spotLightExponent.value = lights.spot.exponents;
uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
uniforms.hemisphereLightPosition.value = lights.hemi.positions;
};
function refreshUniformsShadow ( uniforms, lights ) {
if ( uniforms.shadowMatrix ) {
var j = 0;
for ( var i = 0, il = lights.length; i < il; i ++ ) {
var light = lights[ i ];
if ( ! light.castShadow ) continue;
if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
uniforms.shadowMap.value[ j ] = light.shadowMap;
uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
uniforms.shadowBias.value[ j ] = light.shadowBias;
j ++;
}
}
}
};
// Uniforms (load to GPU)
function loadUniformsMatrices ( uniforms, object ) {
_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
if ( uniforms.normalMatrix ) {
_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
}
};
function getTextureUnit() {
var textureUnit = _usedTextureUnits;
if ( textureUnit >= _maxTextures ) {
console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
}
_usedTextureUnits += 1;
return textureUnit;
};
function loadUniformsGeneric ( program, uniforms ) {
var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
location = program.uniforms[ uniforms[ j ][ 1 ] ];
if ( !location ) continue;
uniform = uniforms[ j ][ 0 ];
type = uniform.type;
value = uniform.value;
if ( type === "i" ) { // single integer
_gl.uniform1i( location, value );
} else if ( type === "f" ) { // single float
_gl.uniform1f( location, value );
} else if ( type === "v2" ) { // single THREE.Vector2
_gl.uniform2f( location, value.x, value.y );
} else if ( type === "v3" ) { // single THREE.Vector3
_gl.uniform3f( location, value.x, value.y, value.z );
} else if ( type === "v4" ) { // single THREE.Vector4
_gl.uniform4f( location, value.x, value.y, value.z, value.w );
} else if ( type === "c" ) { // single THREE.Color
_gl.uniform3f( location, value.r, value.g, value.b );
} else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
_gl.uniform1iv( location, value );
} else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
_gl.uniform3iv( location, value );
} else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
_gl.uniform1fv( location, value );
} else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
_gl.uniform3fv( location, value );
} else if ( type === "v2v" ) { // array of THREE.Vector2
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 2 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 2;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
}
_gl.uniform2fv( location, uniform._array );
} else if ( type === "v3v" ) { // array of THREE.Vector3
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 3 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 3;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
uniform._array[ offset + 2 ] = value[ i ].z;
}
_gl.uniform3fv( location, uniform._array );
} else if ( type === "v4v" ) { // array of THREE.Vector4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 4 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 4;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
uniform._array[ offset + 2 ] = value[ i ].z;
uniform._array[ offset + 3 ] = value[ i ].w;
}
_gl.uniform4fv( location, uniform._array );
} else if ( type === "m4") { // single THREE.Matrix4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 16 );
}
value.flattenToArray( uniform._array );
_gl.uniformMatrix4fv( location, false, uniform._array );
} else if ( type === "m4v" ) { // array of THREE.Matrix4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 16 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
}
_gl.uniformMatrix4fv( location, false, uniform._array );
} else if ( type === "t" ) { // single THREE.Texture (2d or cube)
texture = value;
textureUnit = getTextureUnit();
_gl.uniform1i( location, textureUnit );
if ( !texture ) continue;
if ( texture.image instanceof Array && texture.image.length === 6 ) {
setCubeTexture( texture, textureUnit );
} else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
setCubeTextureDynamic( texture, textureUnit );
} else {
_this.setTexture( texture, textureUnit );
}
} else if ( type === "tv" ) { // array of THREE.Texture (2d)
if ( uniform._array === undefined ) {
uniform._array = [];
}
for( i = 0, il = uniform.value.length; i < il; i ++ ) {
uniform._array[ i ] = getTextureUnit();
}
_gl.uniform1iv( location, uniform._array );
for( i = 0, il = uniform.value.length; i < il; i ++ ) {
texture = uniform.value[ i ];
textureUnit = uniform._array[ i ];
if ( !texture ) continue;
_this.setTexture( texture, textureUnit );
}
}
}
};
function setupMatrices ( object, camera ) {
object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
object._normalMatrix.getInverse( object._modelViewMatrix );
object._normalMatrix.transpose();
};
//
function setColorGamma( array, offset, color, intensitySq ) {
array[ offset ] = color.r * color.r * intensitySq;
array[ offset + 1 ] = color.g * color.g * intensitySq;
array[ offset + 2 ] = color.b * color.b * intensitySq;
};
function setColorLinear( array, offset, color, intensity ) {
array[ offset ] = color.r * intensity;
array[ offset + 1 ] = color.g * intensity;
array[ offset + 2 ] = color.b * intensity;
};
function setupLights ( program, lights ) {
var l, ll, light, n,
r = 0, g = 0, b = 0,
color, skyColor, groundColor,
intensity, intensitySq,
position,
distance,
zlights = _lights,
dirColors = zlights.directional.colors,
dirPositions = zlights.directional.positions,
pointColors = zlights.point.colors,
pointPositions = zlights.point.positions,
pointDistances = zlights.point.distances,
spotColors = zlights.spot.colors,
spotPositions = zlights.spot.positions,
spotDistances = zlights.spot.distances,
spotDirections = zlights.spot.directions,
spotAngles = zlights.spot.angles,
spotExponents = zlights.spot.exponents,
hemiSkyColors = zlights.hemi.skyColors,
hemiGroundColors = zlights.hemi.groundColors,
hemiPositions = zlights.hemi.positions,
dirLength = 0,
pointLength = 0,
spotLength = 0,
hemiLength = 0,
dirOffset = 0,
pointOffset = 0,
spotOffset = 0,
hemiOffset = 0;
for ( l = 0, ll = lights.length; l < ll; l ++ ) {
light = lights[ l ];
if ( light.onlyShadow || ! light.visible ) continue;
color = light.color;
intensity = light.intensity;
distance = light.distance;
if ( light instanceof THREE.AmbientLight ) {
if ( _this.gammaInput ) {
r += color.r * color.r;
g += color.g * color.g;
b += color.b * color.b;
} else {
r += color.r;
g += color.g;
b += color.b;
}
} else if ( light instanceof THREE.DirectionalLight ) {
dirOffset = dirLength * 3;
if ( _this.gammaInput ) {
setColorGamma( dirColors, dirOffset, color, intensity * intensity );
} else {
setColorLinear( dirColors, dirOffset, color, intensity );
}
_direction.copy( light.matrixWorld.getPosition() );
_direction.subSelf( light.target.matrixWorld.getPosition() );
_direction.normalize();
dirPositions[ dirOffset ] = _direction.x;
dirPositions[ dirOffset + 1 ] = _direction.y;
dirPositions[ dirOffset + 2 ] = _direction.z;
dirLength += 1;
} else if( light instanceof THREE.PointLight ) {
pointOffset = pointLength * 3;
if ( _this.gammaInput ) {
setColorGamma( pointColors, pointOffset, color, intensity * intensity );
} else {
setColorLinear( pointColors, pointOffset, color, intensity );
}
position = light.matrixWorld.getPosition();
pointPositions[ pointOffset ] = position.x;
pointPositions[ pointOffset + 1 ] = position.y;
pointPositions[ pointOffset + 2 ] = position.z;
pointDistances[ pointLength ] = distance;
pointLength += 1;
} else if( light instanceof THREE.SpotLight ) {
spotOffset = spotLength * 3;
if ( _this.gammaInput ) {
setColorGamma( spotColors, spotOffset, color, intensity * intensity );
} else {
setColorLinear( spotColors, spotOffset, color, intensity );
}
position = light.matrixWorld.getPosition();
spotPositions[ spotOffset ] = position.x;
spotPositions[ spotOffset + 1 ] = position.y;
spotPositions[ spotOffset + 2 ] = position.z;
spotDistances[ spotLength ] = distance;
_direction.copy( position );
_direction.subSelf( light.target.matrixWorld.getPosition() );
_direction.normalize();
spotDirections[ spotOffset ] = _direction.x;
spotDirections[ spotOffset + 1 ] = _direction.y;
spotDirections[ spotOffset + 2 ] = _direction.z;
spotAngles[ spotLength ] = Math.cos( light.angle );
spotExponents[ spotLength ] = light.exponent;
spotLength += 1;
} else if ( light instanceof THREE.HemisphereLight ) {
skyColor = light.color;
groundColor = light.groundColor;
hemiOffset = hemiLength * 3;
if ( _this.gammaInput ) {
intensitySq = intensity * intensity;
setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
} else {
setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
}
position = light.matrixWorld.getPosition();
hemiPositions[ hemiOffset ] = position.x;
hemiPositions[ hemiOffset + 1 ] = position.y;
hemiPositions[ hemiOffset + 2 ] = position.z;
hemiLength += 1;
}
}
// null eventual remains from removed lights
// (this is to avoid if in shader)
for ( l = dirLength * 3, ll = dirColors.length; l < ll; l ++ ) dirColors[ l ] = 0.0;
for ( l = pointLength * 3, ll = pointColors.length; l < ll; l ++ ) pointColors[ l ] = 0.0;
for ( l = spotLength * 3, ll = spotColors.length; l < ll; l ++ ) spotColors[ l ] = 0.0;
for ( l = hemiLength * 3, ll = hemiSkyColors.length; l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
for ( l = hemiLength * 3, ll = hemiGroundColors.length; l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
zlights.directional.length = dirLength;
zlights.point.length = pointLength;
zlights.spot.length = spotLength;
zlights.hemi.length = hemiLength;
zlights.ambient[ 0 ] = r;
zlights.ambient[ 1 ] = g;
zlights.ambient[ 2 ] = b;
};
// GL state setting
this.setFaceCulling = function ( cullFace, frontFace ) {
if ( cullFace ) {
if ( !frontFace || frontFace === "ccw" ) {
_gl.frontFace( _gl.CCW );
} else {
_gl.frontFace( _gl.CW );
}
if( cullFace === "back" ) {
_gl.cullFace( _gl.BACK );
} else if( cullFace === "front" ) {
_gl.cullFace( _gl.FRONT );
} else {
_gl.cullFace( _gl.FRONT_AND_BACK );
}
_gl.enable( _gl.CULL_FACE );
} else {
_gl.disable( _gl.CULL_FACE );
}
};
this.setMaterialFaces = function ( material ) {
var doubleSided = material.side === THREE.DoubleSide;
var flipSided = material.side === THREE.BackSide;
if ( _oldDoubleSided !== doubleSided ) {
if ( doubleSided ) {
_gl.disable( _gl.CULL_FACE );
} else {
_gl.enable( _gl.CULL_FACE );
}
_oldDoubleSided = doubleSided;
}
if ( _oldFlipSided !== flipSided ) {
if ( flipSided ) {
_gl.frontFace( _gl.CW );
} else {
_gl.frontFace( _gl.CCW );
}
_oldFlipSided = flipSided;
}
};
this.setDepthTest = function ( depthTest ) {
if ( _oldDepthTest !== depthTest ) {
if ( depthTest ) {
_gl.enable( _gl.DEPTH_TEST );
} else {
_gl.disable( _gl.DEPTH_TEST );
}
_oldDepthTest = depthTest;
}
};
this.setDepthWrite = function ( depthWrite ) {
if ( _oldDepthWrite !== depthWrite ) {
_gl.depthMask( depthWrite );
_oldDepthWrite = depthWrite;
}
};
function setLineWidth ( width ) {
if ( width !== _oldLineWidth ) {
_gl.lineWidth( width );
_oldLineWidth = width;
}
};
function setPolygonOffset ( polygonoffset, factor, units ) {
if ( _oldPolygonOffset !== polygonoffset ) {
if ( polygonoffset ) {
_gl.enable( _gl.POLYGON_OFFSET_FILL );
} else {
_gl.disable( _gl.POLYGON_OFFSET_FILL );
}
_oldPolygonOffset = polygonoffset;
}
if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
_gl.polygonOffset( factor, units );
_oldPolygonOffsetFactor = factor;
_oldPolygonOffsetUnits = units;
}
};
this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
if ( blending !== _oldBlending ) {
if ( blending === THREE.NoBlending ) {
_gl.disable( _gl.BLEND );
} else if ( blending === THREE.AdditiveBlending ) {
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
} else if ( blending === THREE.SubtractiveBlending ) {
// TODO: Find blendFuncSeparate() combination
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
} else if ( blending === THREE.MultiplyBlending ) {
// TODO: Find blendFuncSeparate() combination
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
} else if ( blending === THREE.CustomBlending ) {
_gl.enable( _gl.BLEND );
} else {
_gl.enable( _gl.BLEND );
_gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
_gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
}
_oldBlending = blending;
}
if ( blending === THREE.CustomBlending ) {
if ( blendEquation !== _oldBlendEquation ) {
_gl.blendEquation( paramThreeToGL( blendEquation ) );
_oldBlendEquation = blendEquation;
}
if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
_gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
_oldBlendSrc = blendSrc;
_oldBlendDst = blendDst;
}
} else {
_oldBlendEquation = null;
_oldBlendSrc = null;
_oldBlendDst = null;
}
};
// Defines
function generateDefines ( defines ) {
var value, chunk, chunks = [];
for ( var d in defines ) {
value = defines[ d ];
if ( value === false ) continue;
chunk = "#define " + d + " " + value;
chunks.push( chunk );
}
return chunks.join( "\n" );
};
// Shaders
function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
var p, pl, d, program, code;
var chunks = [];
// Generate code
if ( shaderID ) {
chunks.push( shaderID );
} else {
chunks.push( fragmentShader );
chunks.push( vertexShader );
}
for ( d in defines ) {
chunks.push( d );
chunks.push( defines[ d ] );
}
for ( p in parameters ) {
chunks.push( p );
chunks.push( parameters[ p ] );
}
code = chunks.join();
// Check if code has been already compiled
for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
var programInfo = _programs[ p ];
if ( programInfo.code === code ) {
// console.log( "Code already compiled." /*: \n\n" + code*/ );
programInfo.usedTimes ++;
return programInfo.program;
}
}
//console.log( "building new program " );
//
var customDefines = generateDefines( defines );
//
program = _gl.createProgram();
var prefix_vertex = [
"precision " + _precision + " float;",
customDefines,
_supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
_this.gammaInput ? "#define GAMMA_INPUT" : "",
_this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
_this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
"#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
"#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
"#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
"#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
"#define MAX_SHADOWS " + parameters.maxShadows,
"#define MAX_BONES " + parameters.maxBones,
parameters.map ? "#define USE_MAP" : "",
parameters.envMap ? "#define USE_ENVMAP" : "",
parameters.lightMap ? "#define USE_LIGHTMAP" : "",
parameters.bumpMap ? "#define USE_BUMPMAP" : "",
parameters.normalMap ? "#define USE_NORMALMAP" : "",
parameters.specularMap ? "#define USE_SPECULARMAP" : "",
parameters.vertexColors ? "#define USE_COLOR" : "",
parameters.skinning ? "#define USE_SKINNING" : "",
parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
parameters.wrapAround ? "#define WRAP_AROUND" : "",
parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
parameters.flipSided ? "#define FLIP_SIDED" : "",
parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
"uniform mat4 modelMatrix;",
"uniform mat4 modelViewMatrix;",
"uniform mat4 projectionMatrix;",
"uniform mat4 viewMatrix;",
"uniform mat3 normalMatrix;",
"uniform vec3 cameraPosition;",
"attribute vec3 position;",
"attribute vec3 normal;",
"attribute vec2 uv;",
"attribute vec2 uv2;",
"#ifdef USE_COLOR",
"attribute vec3 color;",
"#endif",
"#ifdef USE_MORPHTARGETS",
"attribute vec3 morphTarget0;",
"attribute vec3 morphTarget1;",
"attribute vec3 morphTarget2;",
"attribute vec3 morphTarget3;",
"#ifdef USE_MORPHNORMALS",
"attribute vec3 morphNormal0;",
"attribute vec3 morphNormal1;",
"attribute vec3 morphNormal2;",
"attribute vec3 morphNormal3;",
"#else",
"attribute vec3 morphTarget4;",
"attribute vec3 morphTarget5;",
"attribute vec3 morphTarget6;",
"attribute vec3 morphTarget7;",
"#endif",
"#endif",
"#ifdef USE_SKINNING",
"attribute vec4 skinIndex;",
"attribute vec4 skinWeight;",
"#endif",
""
].join("\n");
var prefix_fragment = [
"precision " + _precision + " float;",
( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
customDefines,
"#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
"#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
"#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
"#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
"#define MAX_SHADOWS " + parameters.maxShadows,
parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
_this.gammaInput ? "#define GAMMA_INPUT" : "",
_this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
_this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
parameters.map ? "#define USE_MAP" : "",
parameters.envMap ? "#define USE_ENVMAP" : "",
parameters.lightMap ? "#define USE_LIGHTMAP" : "",
parameters.bumpMap ? "#define USE_BUMPMAP" : "",
parameters.normalMap ? "#define USE_NORMALMAP" : "",
parameters.specularMap ? "#define USE_SPECULARMAP" : "",
parameters.vertexColors ? "#define USE_COLOR" : "",
parameters.metal ? "#define METAL" : "",
parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
parameters.wrapAround ? "#define WRAP_AROUND" : "",
parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
parameters.flipSided ? "#define FLIP_SIDED" : "",
parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
"uniform mat4 viewMatrix;",
"uniform vec3 cameraPosition;",
""
].join("\n");
var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
_gl.attachShader( program, glVertexShader );
_gl.attachShader( program, glFragmentShader );
_gl.linkProgram( program );
if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
}
// clean up
_gl.deleteShader( glFragmentShader );
_gl.deleteShader( glVertexShader );
//console.log( prefix_fragment + fragmentShader );
//console.log( prefix_vertex + vertexShader );
program.uniforms = {};
program.attributes = {};
var identifiers, u, a, i;
// cache uniform locations
identifiers = [
'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
'morphTargetInfluences'
];
if ( parameters.useVertexTexture ) {
identifiers.push( 'boneTexture' );
} else {
identifiers.push( 'boneGlobalMatrices' );
}
for ( u in uniforms ) {
identifiers.push( u );
}
cacheUniformLocations( program, identifiers );
// cache attributes locations
identifiers = [
"position", "normal", "uv", "uv2", "tangent", "color",
"skinIndex", "skinWeight"
];
for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
identifiers.push( "morphTarget" + i );
}
for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
identifiers.push( "morphNormal" + i );
}
for ( a in attributes ) {
identifiers.push( a );
}
cacheAttributeLocations( program, identifiers );
program.id = _programs_counter ++;
_programs.push( { program: program, code: code, usedTimes: 1 } );
_this.info.memory.programs = _programs.length;
return program;
};
// Shader parameters cache
function cacheUniformLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.uniforms[ id ] = _gl.getUniformLocation( program, id );
}
};
function cacheAttributeLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.attributes[ id ] = _gl.getAttribLocation( program, id );
}
};
function addLineNumbers ( string ) {
var chunks = string.split( "\n" );
for ( var i = 0, il = chunks.length; i < il; i ++ ) {
// Chrome reports shader errors on lines
// starting counting from 1
chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
}
return chunks.join( "\n" );
};
function getShader ( type, string ) {
var shader;
if ( type === "fragment" ) {
shader = _gl.createShader( _gl.FRAGMENT_SHADER );
} else if ( type === "vertex" ) {
shader = _gl.createShader( _gl.VERTEX_SHADER );
}
_gl.shaderSource( shader, string );
_gl.compileShader( shader );
if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
console.error( _gl.getShaderInfoLog( shader ) );
console.error( addLineNumbers( string ) );
return null;
}
return shader;
};
// Textures
function isPowerOfTwo ( value ) {
return ( value & ( value - 1 ) ) === 0;
};
function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
if ( isImagePowerOfTwo ) {
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
} else {
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
}
if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
_gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
texture.__oldAnisotropy = texture.anisotropy;
}
}
};
this.setTexture = function ( texture, slot ) {
if ( texture.needsUpdate ) {
if ( ! texture.__webglInit ) {
texture.__webglInit = true;
texture.__webglTexture = _gl.createTexture();
_this.info.memory.textures ++;
}
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
var image = texture.image,
isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
glFormat = paramThreeToGL( texture.format ),
glType = paramThreeToGL( texture.type );
setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
if ( texture instanceof THREE.CompressedTexture ) {
var mipmap, mipmaps = texture.mipmaps;
for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
_gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
}
} else if ( texture instanceof THREE.DataTexture ) {
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
} else {
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
}
if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
texture.needsUpdate = false;
if ( texture.onUpdate ) texture.onUpdate();
} else {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
}
};
function clampToMaxSize ( image, maxSize ) {
if ( image.width <= maxSize && image.height <= maxSize ) {
return image;
}
// Warning: Scaling through the canvas will only work with images that use
// premultiplied alpha.
var maxDimension = Math.max( image.width, image.height );
var newWidth = Math.floor( image.width * maxSize / maxDimension );
var newHeight = Math.floor( image.height * maxSize / maxDimension );
var canvas = document.createElement( 'canvas' );
canvas.width = newWidth;
canvas.height = newHeight;
var ctx = canvas.getContext( "2d" );
ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
return canvas;
}
function setCubeTexture ( texture, slot ) {
if ( texture.image.length === 6 ) {
if ( texture.needsUpdate ) {
if ( ! texture.image.__webglTextureCube ) {
texture.image.__webglTextureCube = _gl.createTexture();
}
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
var isCompressed = texture instanceof THREE.CompressedTexture;
var cubeImage = [];
for ( var i = 0; i < 6; i ++ ) {
if ( _this.autoScaleCubemaps && ! isCompressed ) {
cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
} else {
cubeImage[ i ] = texture.image[ i ];
}
}
var image = cubeImage[ 0 ],
isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
glFormat = paramThreeToGL( texture.format ),
glType = paramThreeToGL( texture.type );
setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
for ( var i = 0; i < 6; i ++ ) {
if ( isCompressed ) {
var mipmap, mipmaps = cubeImage[ i ].mipmaps;
for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
mipmap = mipmaps[ j ];
_gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
}
} else {
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
}
}
if ( texture.generateMipmaps && isImagePowerOfTwo ) {
_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
}
texture.needsUpdate = false;
if ( texture.onUpdate ) texture.onUpdate();
} else {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
}
}
};
function setCubeTextureDynamic ( texture, slot ) {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
};
// Render targets
function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
};
function setupRenderBuffer ( renderbuffer, renderTarget ) {
_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
/* For some reason this is not working. Defaulting to RGBA4.
} else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
*/
} else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
} else {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
}
};
this.setRenderTarget = function ( renderTarget ) {
var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
renderTarget.__webglTexture = _gl.createTexture();
// Setup texture, create render and frame buffers
var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
glFormat = paramThreeToGL( renderTarget.format ),
glType = paramThreeToGL( renderTarget.type );
if ( isCube ) {
renderTarget.__webglFramebuffer = [];
renderTarget.__webglRenderbuffer = [];
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
for ( var i = 0; i < 6; i ++ ) {
renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
}
if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
} else {
renderTarget.__webglFramebuffer = _gl.createFramebuffer();
renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
_gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
}
// Release everything
if ( isCube ) {
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
} else {
_gl.bindTexture( _gl.TEXTURE_2D, null );
}
_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
_gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
}
var framebuffer, width, height, vx, vy;
if ( renderTarget ) {
if ( isCube ) {
framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
} else {
framebuffer = renderTarget.__webglFramebuffer;
}
width = renderTarget.width;
height = renderTarget.height;
vx = 0;
vy = 0;
} else {
framebuffer = null;
width = _viewportWidth;
height = _viewportHeight;
vx = _viewportX;
vy = _viewportY;
}
if ( framebuffer !== _currentFramebuffer ) {
_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
_gl.viewport( vx, vy, width, height );
_currentFramebuffer = framebuffer;
}
_currentWidth = width;
_currentHeight = height;
};
function updateRenderTargetMipmap ( renderTarget ) {
if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
} else {
_gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
_gl.generateMipmap( _gl.TEXTURE_2D );
_gl.bindTexture( _gl.TEXTURE_2D, null );
}
};
// Fallback filters for non-power-of-2 textures
function filterFallback ( f ) {
if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
return _gl.NEAREST;
}
return _gl.LINEAR;
};
// Map three.js constants to WebGL constants
function paramThreeToGL ( p ) {
if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
if ( p === THREE.NearestFilter ) return _gl.NEAREST;
if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
if ( p === THREE.LinearFilter ) return _gl.LINEAR;
if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
if ( p === THREE.ByteType ) return _gl.BYTE;
if ( p === THREE.ShortType ) return _gl.SHORT;
if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
if ( p === THREE.IntType ) return _gl.INT;
if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
if ( p === THREE.FloatType ) return _gl.FLOAT;
if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
if ( p === THREE.RGBFormat ) return _gl.RGB;
if ( p === THREE.RGBAFormat ) return _gl.RGBA;
if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
if ( p === THREE.ZeroFactor ) return _gl.ZERO;
if ( p === THREE.OneFactor ) return _gl.ONE;
if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
if ( _glExtensionCompressedTextureS3TC !== undefined ) {
if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
}
return 0;
};
// Allocations
function allocateBones ( object ) {
if ( _supportsBoneTextures && object && object.useVertexTexture ) {
return 1024;
} else {
// default for when object is not specified
// ( for example when prebuilding shader
// to be used with multiple objects )
//
// - leave some extra space for other uniforms
// - limit here is ANGLE's 254 max uniform vectors
// (up to 54 should be safe)
var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
var maxBones = nVertexMatrices;
if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
maxBones = Math.min( object.bones.length, maxBones );
if ( maxBones < object.bones.length ) {
console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
}
}
return maxBones;
}
};
function allocateLights ( lights ) {
var l, ll, light, dirLights, pointLights, spotLights, hemiLights, maxDirLights, maxPointLights, maxSpotLights, maxHemiLights;
dirLights = pointLights = spotLights = hemiLights = maxDirLights = maxPointLights = maxSpotLights = maxHemiLights = 0;
for ( l = 0, ll = lights.length; l < ll; l ++ ) {
light = lights[ l ];
if ( light.onlyShadow ) continue;
if ( light instanceof THREE.DirectionalLight ) dirLights ++;
if ( light instanceof THREE.PointLight ) pointLights ++;
if ( light instanceof THREE.SpotLight ) spotLights ++;
if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
}
if ( ( pointLights + spotLights + dirLights + hemiLights) <= _maxLights ) {
maxDirLights = dirLights;
maxPointLights = pointLights;
maxSpotLights = spotLights;
maxHemiLights = hemiLights;
} else {
maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
maxPointLights = _maxLights - maxDirLights;
// these are not really correct
maxSpotLights = maxPointLights;
maxHemiLights = maxDirLights;
}
return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights, 'hemi': maxHemiLights };
};
function allocateShadows ( lights ) {
var l, ll, light, maxShadows = 0;
for ( l = 0, ll = lights.length; l < ll; l++ ) {
light = lights[ l ];
if ( ! light.castShadow ) continue;
if ( light instanceof THREE.SpotLight ) maxShadows ++;
if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
}
return maxShadows;
};
// Initialization
function initGL () {
try {
if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
throw 'Error creating WebGL context.';
}
} catch ( error ) {
console.error( error );
}
_glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
_glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
_glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
_gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
_gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
_glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
_gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
_gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
if ( ! _glExtensionTextureFloat ) {
console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
}
if ( ! _glExtensionStandardDerivatives ) {
console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
}
if ( ! _glExtensionTextureFilterAnisotropic ) {
console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
}
if ( ! _glExtensionCompressedTextureS3TC ) {
console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
}
};
function setDefaultGLState () {
_gl.clearColor( 0, 0, 0, 1 );
_gl.clearDepth( 1 );
_gl.clearStencil( 0 );
_gl.enable( _gl.DEPTH_TEST );
_gl.depthFunc( _gl.LEQUAL );
_gl.frontFace( _gl.CCW );
_gl.cullFace( _gl.BACK );
_gl.enable( _gl.CULL_FACE );
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
_gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
};
// default plugins (order is important)
this.shadowMapPlugin = new THREE.ShadowMapPlugin();
this.addPrePlugin( this.shadowMapPlugin );
this.addPostPlugin( new THREE.SpritePlugin() );
this.addPostPlugin( new THREE.LensFlarePlugin() );
};
/**
* @author szimek / https://github.com/szimek/
* @author alteredq / http://alteredqualia.com/
*/
THREE.WebGLRenderTarget = function ( width, height, options ) {
this.width = width;
this.height = height;
options = options || {};
this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
this.offset = new THREE.Vector2( 0, 0 );
this.repeat = new THREE.Vector2( 1, 1 );
this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
this.generateMipmaps = true;
};
THREE.WebGLRenderTarget.prototype.clone = function() {
var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
tmp.wrapS = this.wrapS;
tmp.wrapT = this.wrapT;
tmp.magFilter = this.magFilter;
tmp.anisotropy = this.anisotropy;
tmp.minFilter = this.minFilter;
tmp.offset.copy( this.offset );
tmp.repeat.copy( this.repeat );
tmp.format = this.format;
tmp.type = this.type;
tmp.depthBuffer = this.depthBuffer;
tmp.stencilBuffer = this.stencilBuffer;
tmp.generateMipmaps = this.generateMipmaps;
return tmp;
};
/**
* @author alteredq / http://alteredqualia.com
*/
THREE.WebGLRenderTargetCube = function ( width, height, options ) {
THREE.WebGLRenderTarget.call( this, width, height, options );
this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
};
THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableVertex = function () {
this.positionWorld = new THREE.Vector3();
this.positionScreen = new THREE.Vector4();
this.visible = true;
};
THREE.RenderableVertex.prototype.copy = function ( vertex ) {
this.positionWorld.copy( vertex.positionWorld );
this.positionScreen.copy( vertex.positionScreen );
}
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableFace3 = function () {
this.v1 = new THREE.RenderableVertex();
this.v2 = new THREE.RenderableVertex();
this.v3 = new THREE.RenderableVertex();
this.centroidWorld = new THREE.Vector3();
this.centroidScreen = new THREE.Vector3();
this.normalWorld = new THREE.Vector3();
this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
this.vertexNormalsLength = 0;
this.color = null;
this.material = null;
this.uvs = [[]];
this.z = null;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableFace4 = function () {
this.v1 = new THREE.RenderableVertex();
this.v2 = new THREE.RenderableVertex();
this.v3 = new THREE.RenderableVertex();
this.v4 = new THREE.RenderableVertex();
this.centroidWorld = new THREE.Vector3();
this.centroidScreen = new THREE.Vector3();
this.normalWorld = new THREE.Vector3();
this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
this.vertexNormalsLength = 0;
this.color = null;
this.material = null;
this.uvs = [[]];
this.z = null;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableObject = function () {
this.object = null;
this.z = null;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableParticle = function () {
this.object = null;
this.x = null;
this.y = null;
this.z = null;
this.rotation = null;
this.scale = new THREE.Vector2();
this.material = null;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableLine = function () {
this.z = null;
this.v1 = new THREE.RenderableVertex();
this.v2 = new THREE.RenderableVertex();
this.material = null;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ColorUtils = {
adjustHSV : function ( color, h, s, v ) {
var hsv = THREE.ColorUtils.__hsv;
THREE.ColorUtils.rgbToHsv( color, hsv );
hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
color.setHSV( hsv.h, hsv.s, hsv.v );
},
// based on MochiKit implementation by Bob Ippolito
rgbToHsv : function ( color, hsv ) {
var r = color.r;
var g = color.g;
var b = color.b;
var max = Math.max( Math.max( r, g ), b );
var min = Math.min( Math.min( r, g ), b );
var hue;
var saturation;
var value = max;
if ( min === max ) {
hue = 0;
saturation = 0;
} else {
var delta = ( max - min );
saturation = delta / max;
if ( r === max ) {
hue = ( g - b ) / delta;
} else if ( g === max ) {
hue = 2 + ( ( b - r ) / delta );
} else {
hue = 4 + ( ( r - g ) / delta );
}
hue /= 6;
if ( hue < 0 ) {
hue += 1;
}
if ( hue > 1 ) {
hue -= 1;
}
}
if ( hsv === undefined ) {
hsv = { h: 0, s: 0, v: 0 };
}
hsv.h = hue;
hsv.s = saturation;
hsv.v = value;
return hsv;
}
};
THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.GeometryUtils = {
// Merge two geometries or geometry and geometry from object (using object's transform)
merge: function ( geometry1, object2 /* mesh | geometry */ ) {
var matrix, matrixRotation,
vertexOffset = geometry1.vertices.length,
uvPosition = geometry1.faceVertexUvs[ 0 ].length,
geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
vertices1 = geometry1.vertices,
vertices2 = geometry2.vertices,
faces1 = geometry1.faces,
faces2 = geometry2.faces,
uvs1 = geometry1.faceVertexUvs[ 0 ],
uvs2 = geometry2.faceVertexUvs[ 0 ];
var geo1MaterialsMap = {};
for ( var i = 0; i < geometry1.materials.length; i ++ ) {
var id = geometry1.materials[ i ].id;
geo1MaterialsMap[ id ] = i;
}
if ( object2 instanceof THREE.Mesh ) {
object2.matrixAutoUpdate && object2.updateMatrix();
matrix = object2.matrix;
matrixRotation = new THREE.Matrix4();
matrixRotation.extractRotation( matrix, object2.scale );
}
// vertices
for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
var vertex = vertices2[ i ];
var vertexCopy = vertex.clone();
if ( matrix ) matrix.multiplyVector3( vertexCopy );
vertices1.push( vertexCopy );
}
// faces
for ( i = 0, il = faces2.length; i < il; i ++ ) {
var face = faces2[ i ], faceCopy, normal, color,
faceVertexNormals = face.vertexNormals,
faceVertexColors = face.vertexColors;
if ( face instanceof THREE.Face3 ) {
faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
} else if ( face instanceof THREE.Face4 ) {
faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
}
faceCopy.normal.copy( face.normal );
if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
normal = faceVertexNormals[ j ].clone();
if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
faceCopy.vertexNormals.push( normal );
}
faceCopy.color.copy( face.color );
for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
color = faceVertexColors[ j ];
faceCopy.vertexColors.push( color.clone() );
}
if ( face.materialIndex !== undefined ) {
var material2 = geometry2.materials[ face.materialIndex ];
var materialId2 = material2.id;
var materialIndex = geo1MaterialsMap[ materialId2 ];
if ( materialIndex === undefined ) {
materialIndex = geometry1.materials.length;
geo1MaterialsMap[ materialId2 ] = materialIndex;
geometry1.materials.push( material2 );
}
faceCopy.materialIndex = materialIndex;
}
faceCopy.centroid.copy( face.centroid );
if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
faces1.push( faceCopy );
}
// uvs
for ( i = 0, il = uvs2.length; i < il; i ++ ) {
var uv = uvs2[ i ], uvCopy = [];
for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
}
uvs1.push( uvCopy );
}
},
clone: function ( geometry ) {
var cloneGeo = new THREE.Geometry();
var i, il;
var vertices = geometry.vertices,
faces = geometry.faces,
uvs = geometry.faceVertexUvs[ 0 ];
// materials
if ( geometry.materials ) {
cloneGeo.materials = geometry.materials.slice();
}
// vertices
for ( i = 0, il = vertices.length; i < il; i ++ ) {
var vertex = vertices[ i ];
cloneGeo.vertices.push( vertex.clone() );
}
// faces
for ( i = 0, il = faces.length; i < il; i ++ ) {
var face = faces[ i ];
cloneGeo.faces.push( face.clone() );
}
// uvs
for ( i = 0, il = uvs.length; i < il; i ++ ) {
var uv = uvs[ i ], uvCopy = [];
for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
}
cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
}
return cloneGeo;
},
// Get random point in triangle (via barycentric coordinates)
// (uniform distribution)
// http://www.cgafaq.info/wiki/Random_Point_In_Triangle
randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
var a, b, c,
point = new THREE.Vector3(),
tmp = THREE.GeometryUtils.__v1;
a = THREE.GeometryUtils.random();
b = THREE.GeometryUtils.random();
if ( ( a + b ) > 1 ) {
a = 1 - a;
b = 1 - b;
}
c = 1 - a - b;
point.copy( vectorA );
point.multiplyScalar( a );
tmp.copy( vectorB );
tmp.multiplyScalar( b );
point.addSelf( tmp );
tmp.copy( vectorC );
tmp.multiplyScalar( c );
point.addSelf( tmp );
return point;
},
// Get random point in face (triangle / quad)
// (uniform distribution)
randomPointInFace: function ( face, geometry, useCachedAreas ) {
var vA, vB, vC, vD;
if ( face instanceof THREE.Face3 ) {
vA = geometry.vertices[ face.a ];
vB = geometry.vertices[ face.b ];
vC = geometry.vertices[ face.c ];
return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
} else if ( face instanceof THREE.Face4 ) {
vA = geometry.vertices[ face.a ];
vB = geometry.vertices[ face.b ];
vC = geometry.vertices[ face.c ];
vD = geometry.vertices[ face.d ];
var area1, area2;
if ( useCachedAreas ) {
if ( face._area1 && face._area2 ) {
area1 = face._area1;
area2 = face._area2;
} else {
area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
face._area1 = area1;
face._area2 = area2;
}
} else {
area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
}
var r = THREE.GeometryUtils.random() * ( area1 + area2 );
if ( r < area1 ) {
return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
} else {
return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
}
}
},
// Get uniformly distributed random points in mesh
// - create array with cumulative sums of face areas
// - pick random number from 0 to total area
// - find corresponding place in area array by binary search
// - get random point in face
randomPointsInGeometry: function ( geometry, n ) {
var face, i,
faces = geometry.faces,
vertices = geometry.vertices,
il = faces.length,
totalArea = 0,
cumulativeAreas = [],
vA, vB, vC, vD;
// precompute face areas
for ( i = 0; i < il; i ++ ) {
face = faces[ i ];
if ( face instanceof THREE.Face3 ) {
vA = vertices[ face.a ];
vB = vertices[ face.b ];
vC = vertices[ face.c ];
face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
} else if ( face instanceof THREE.Face4 ) {
vA = vertices[ face.a ];
vB = vertices[ face.b ];
vC = vertices[ face.c ];
vD = vertices[ face.d ];
face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
face._area = face._area1 + face._area2;
}
totalArea += face._area;
cumulativeAreas[ i ] = totalArea;
}
// binary search cumulative areas array
function binarySearchIndices( value ) {
function binarySearch( start, end ) {
// return closest larger index
// if exact number is not found
if ( end < start )
return start;
var mid = start + Math.floor( ( end - start ) / 2 );
if ( cumulativeAreas[ mid ] > value ) {
return binarySearch( start, mid - 1 );
} else if ( cumulativeAreas[ mid ] < value ) {
return binarySearch( mid + 1, end );
} else {
return mid;
}
}
var result = binarySearch( 0, cumulativeAreas.length - 1 )
return result;
}
// pick random face weighted by face area
var r, index,
result = [];
var stats = {};
for ( i = 0; i < n; i ++ ) {
r = THREE.GeometryUtils.random() * totalArea;
index = binarySearchIndices( r );
result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
if ( ! stats[ index ] ) {
stats[ index ] = 1;
} else {
stats[ index ] += 1;
}
}
return result;
},
// Get triangle area (by Heron's formula)
// http://en.wikipedia.org/wiki/Heron%27s_formula
triangleArea: function ( vectorA, vectorB, vectorC ) {
var s, a, b, c,
tmp = THREE.GeometryUtils.__v1;
tmp.sub( vectorA, vectorB );
a = tmp.length();
tmp.sub( vectorA, vectorC );
b = tmp.length();
tmp.sub( vectorB, vectorC );
c = tmp.length();
s = 0.5 * ( a + b + c );
return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
},
// Center geometry so that 0,0,0 is in center of bounding box
center: function ( geometry ) {
geometry.computeBoundingBox();
var bb = geometry.boundingBox;
var offset = new THREE.Vector3();
offset.add( bb.min, bb.max );
offset.multiplyScalar( -0.5 );
geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
geometry.computeBoundingBox();
return offset;
},
// Normalize UVs to be from <0,1>
// (for now just the first set of UVs)
normalizeUVs: function ( geometry ) {
var uvSet = geometry.faceVertexUvs[ 0 ];
for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
var uvs = uvSet[ i ];
for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
// texture repeat
if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
}
}
},
triangulateQuads: function ( geometry ) {
var i, il, j, jl;
var faces = [];
var faceUvs = [];
var faceVertexUvs = [];
for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
faceUvs[ i ] = [];
}
for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
faceVertexUvs[ i ] = [];
}
for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
var face = geometry.faces[ i ];
if ( face instanceof THREE.Face4 ) {
var a = face.a;
var b = face.b;
var c = face.c;
var d = face.d;
var triA = new THREE.Face3();
var triB = new THREE.Face3();
triA.color.copy( face.color );
triB.color.copy( face.color );
triA.materialIndex = face.materialIndex;
triB.materialIndex = face.materialIndex;
triA.a = a;
triA.b = b;
triA.c = d;
triB.a = b;
triB.b = c;
triB.c = d;
if ( face.vertexColors.length === 4 ) {
triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
}
faces.push( triA, triB );
for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
if ( geometry.faceVertexUvs[ j ].length ) {
var uvs = geometry.faceVertexUvs[ j ][ i ];
var uvA = uvs[ 0 ];
var uvB = uvs[ 1 ];
var uvC = uvs[ 2 ];
var uvD = uvs[ 3 ];
var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
}
}
for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
if ( geometry.faceUvs[ j ].length ) {
var faceUv = geometry.faceUvs[ j ][ i ];
faceUvs[ j ].push( faceUv, faceUv );
}
}
} else {
faces.push( face );
for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
}
for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
}
}
}
geometry.faces = faces;
geometry.faceUvs = faceUvs;
geometry.faceVertexUvs = faceVertexUvs;
geometry.computeCentroids();
geometry.computeFaceNormals();
geometry.computeVertexNormals();
if ( geometry.hasTangents ) geometry.computeTangents();
},
// Make all faces use unique vertices
// so that each face can be separated from others
explode: function( geometry ) {
var vertices = [];
for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
var n = vertices.length;
var face = geometry.faces[ i ];
if ( face instanceof THREE.Face4 ) {
var a = face.a;
var b = face.b;
var c = face.c;
var d = face.d;
var va = geometry.vertices[ a ];
var vb = geometry.vertices[ b ];
var vc = geometry.vertices[ c ];
var vd = geometry.vertices[ d ];
vertices.push( va.clone() );
vertices.push( vb.clone() );
vertices.push( vc.clone() );
vertices.push( vd.clone() );
face.a = n;
face.b = n + 1;
face.c = n + 2;
face.d = n + 3;
} else {
var a = face.a;
var b = face.b;
var c = face.c;
var va = geometry.vertices[ a ];
var vb = geometry.vertices[ b ];
var vc = geometry.vertices[ c ];
vertices.push( va.clone() );
vertices.push( vb.clone() );
vertices.push( vc.clone() );
face.a = n;
face.b = n + 1;
face.c = n + 2;
}
}
geometry.vertices = vertices;
delete geometry.__tmpVertices;
},
// Break faces with edges longer than maxEdgeLength
// - not recursive
tessellate: function ( geometry, maxEdgeLength ) {
var i, il, face,
a, b, c, d,
va, vb, vc, vd,
dab, dbc, dac, dcd, dad,
m, m1, m2,
vm, vm1, vm2,
vnm, vnm1, vnm2,
vcm, vcm1, vcm2,
triA, triB,
quadA, quadB,
edge;
var faces = [];
var faceVertexUvs = [];
for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
faceVertexUvs[ i ] = [];
}
for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
face = geometry.faces[ i ];
if ( face instanceof THREE.Face3 ) {
a = face.a;
b = face.b;
c = face.c;
va = geometry.vertices[ a ];
vb = geometry.vertices[ b ];
vc = geometry.vertices[ c ];
dab = va.distanceTo( vb );
dbc = vb.distanceTo( vc );
dac = va.distanceTo( vc );
if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
m = geometry.vertices.length;
triA = face.clone();
triB = face.clone();
if ( dab >= dbc && dab >= dac ) {
vm = va.clone();
vm.lerpSelf( vb, 0.5 );
triA.a = a;
triA.b = m;
triA.c = c;
triB.a = m;
triB.b = b;
triB.c = c;
if ( face.vertexNormals.length === 3 ) {
vnm = face.vertexNormals[ 0 ].clone();
vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
triA.vertexNormals[ 1 ].copy( vnm );
triB.vertexNormals[ 0 ].copy( vnm );
}
if ( face.vertexColors.length === 3 ) {
vcm = face.vertexColors[ 0 ].clone();
vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
triA.vertexColors[ 1 ].copy( vcm );
triB.vertexColors[ 0 ].copy( vcm );
}
edge = 0;
} else if ( dbc >= dab && dbc >= dac ) {
vm = vb.clone();
vm.lerpSelf( vc, 0.5 );
triA.a = a;
triA.b = b;
triA.c = m;
triB.a = m;
triB.b = c;
triB.c = a;
if ( face.vertexNormals.length === 3 ) {
vnm = face.vertexNormals[ 1 ].clone();
vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
triA.vertexNormals[ 2 ].copy( vnm );
triB.vertexNormals[ 0 ].copy( vnm );
triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
}
if ( face.vertexColors.length === 3 ) {
vcm = face.vertexColors[ 1 ].clone();
vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
triA.vertexColors[ 2 ].copy( vcm );
triB.vertexColors[ 0 ].copy( vcm );
triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
}
edge = 1;
} else {
vm = va.clone();
vm.lerpSelf( vc, 0.5 );
triA.a = a;
triA.b = b;
triA.c = m;
triB.a = m;
triB.b = b;
triB.c = c;
if ( face.vertexNormals.length === 3 ) {
vnm = face.vertexNormals[ 0 ].clone();
vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
triA.vertexNormals[ 2 ].copy( vnm );
triB.vertexNormals[ 0 ].copy( vnm );
}
if ( face.vertexColors.length === 3 ) {
vcm = face.vertexColors[ 0 ].clone();
vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
triA.vertexColors[ 2 ].copy( vcm );
triB.vertexColors[ 0 ].copy( vcm );
}
edge = 2;
}
faces.push( triA, triB );
geometry.vertices.push( vm );
var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
if ( geometry.faceVertexUvs[ j ].length ) {
uvs = geometry.faceVertexUvs[ j ][ i ];
uvA = uvs[ 0 ];
uvB = uvs[ 1 ];
uvC = uvs[ 2 ];
// AB
if ( edge === 0 ) {
uvM = uvA.clone();
uvM.lerpSelf( uvB, 0.5 );
uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
// BC
} else if ( edge === 1 ) {
uvM = uvB.clone();
uvM.lerpSelf( uvC, 0.5 );
uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
// AC
} else {
uvM = uvA.clone();
uvM.lerpSelf( uvC, 0.5 );
uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
}
faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
}
}
} else {
faces.push( face );
for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
}
}
} else {
a = face.a;
b = face.b;
c = face.c;
d = face.d;
va = geometry.vertices[ a ];
vb = geometry.vertices[ b ];
vc = geometry.vertices[ c ];
vd = geometry.vertices[ d ];
dab = va.distanceTo( vb );
dbc = vb.distanceTo( vc );
dcd = vc.distanceTo( vd );
dad = va.distanceTo( vd );
if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
m1 = geometry.vertices.length;
m2 = geometry.vertices.length + 1;
quadA = face.clone();
quadB = face.clone();
if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
vm1 = va.clone();
vm1.lerpSelf( vb, 0.5 );
vm2 = vc.clone();
vm2.lerpSelf( vd, 0.5 );
quadA.a = a;
quadA.b = m1;
quadA.c = m2;
quadA.d = d;
quadB.a = m1;
quadB.b = b;
quadB.c = c;
quadB.d = m2;
if ( face.vertexNormals.length === 4 ) {
vnm1 = face.vertexNormals[ 0 ].clone();
vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
vnm2 = face.vertexNormals[ 2 ].clone();
vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
quadA.vertexNormals[ 1 ].copy( vnm1 );
quadA.vertexNormals[ 2 ].copy( vnm2 );
quadB.vertexNormals[ 0 ].copy( vnm1 );
quadB.vertexNormals[ 3 ].copy( vnm2 );
}
if ( face.vertexColors.length === 4 ) {
vcm1 = face.vertexColors[ 0 ].clone();
vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
vcm2 = face.vertexColors[ 2 ].clone();
vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
quadA.vertexColors[ 1 ].copy( vcm1 );
quadA.vertexColors[ 2 ].copy( vcm2 );
quadB.vertexColors[ 0 ].copy( vcm1 );
quadB.vertexColors[ 3 ].copy( vcm2 );
}
edge = 0;
} else {
vm1 = vb.clone();
vm1.lerpSelf( vc, 0.5 );
vm2 = vd.clone();
vm2.lerpSelf( va, 0.5 );
quadA.a = a;
quadA.b = b;
quadA.c = m1;
quadA.d = m2;
quadB.a = m2;
quadB.b = m1;
quadB.c = c;
quadB.d = d;
if ( face.vertexNormals.length === 4 ) {
vnm1 = face.vertexNormals[ 1 ].clone();
vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
vnm2 = face.vertexNormals[ 3 ].clone();
vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
quadA.vertexNormals[ 2 ].copy( vnm1 );
quadA.vertexNormals[ 3 ].copy( vnm2 );
quadB.vertexNormals[ 0 ].copy( vnm2 );
quadB.vertexNormals[ 1 ].copy( vnm1 );
}
if ( face.vertexColors.length === 4 ) {
vcm1 = face.vertexColors[ 1 ].clone();
vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
vcm2 = face.vertexColors[ 3 ].clone();
vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
quadA.vertexColors[ 2 ].copy( vcm1 );
quadA.vertexColors[ 3 ].copy( vcm2 );
quadB.vertexColors[ 0 ].copy( vcm2 );
quadB.vertexColors[ 1 ].copy( vcm1 );
}
edge = 1;
}
faces.push( quadA, quadB );
geometry.vertices.push( vm1, vm2 );
var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
if ( geometry.faceVertexUvs[ j ].length ) {
uvs = geometry.faceVertexUvs[ j ][ i ];
uvA = uvs[ 0 ];
uvB = uvs[ 1 ];
uvC = uvs[ 2 ];
uvD = uvs[ 3 ];
// AB + CD
if ( edge === 0 ) {
uvM1 = uvA.clone();
uvM1.lerpSelf( uvB, 0.5 );
uvM2 = uvC.clone();
uvM2.lerpSelf( uvD, 0.5 );
uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
// BC + AD
} else {
uvM1 = uvB.clone();
uvM1.lerpSelf( uvC, 0.5 );
uvM2 = uvD.clone();
uvM2.lerpSelf( uvA, 0.5 );
uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
}
faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
}
}
} else {
faces.push( face );
for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
}
}
}
}
geometry.faces = faces;
geometry.faceVertexUvs = faceVertexUvs;
}
};
THREE.GeometryUtils.random = THREE.Math.random16;
THREE.GeometryUtils.__v1 = new THREE.Vector3();
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
THREE.ImageUtils = {
crossOrigin: 'anonymous',
loadTexture: function ( url, mapping, onLoad, onError ) {
var image = new Image();
var texture = new THREE.Texture( image, mapping );
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
texture.image = event.content;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
} );
loader.addEventListener( 'error', function ( event ) {
if ( onError ) onError( event.message );
} );
loader.crossOrigin = this.crossOrigin;
loader.load( url, image );
return texture;
},
loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
var texture = new THREE.CompressedTexture();
texture.mapping = mapping;
var request = new XMLHttpRequest();
request.onload = function () {
var buffer = request.response;
var dds = THREE.ImageUtils.parseDDS( buffer, true );
texture.format = dds.format;
texture.mipmaps = dds.mipmaps;
texture.image.width = dds.width;
texture.image.height = dds.height;
// gl.generateMipmap fails for compressed textures
// mipmaps must be embedded in the DDS file
// or texture filters must not use mipmapping
texture.generateMipmaps = false;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
request.onerror = onError;
request.open( 'GET', url, true );
request.responseType = "arraybuffer";
request.send( null );
return texture;
},
loadTextureCube: function ( array, mapping, onLoad, onError ) {
var images = [];
images.loadCount = 0;
var texture = new THREE.Texture();
texture.image = images;
if ( mapping !== undefined ) texture.mapping = mapping;
// no flipping needed for cube textures
texture.flipY = false;
for ( var i = 0, il = array.length; i < il; ++ i ) {
var cubeImage = new Image();
images[ i ] = cubeImage;
cubeImage.onload = function () {
images.loadCount += 1;
if ( images.loadCount === 6 ) {
texture.needsUpdate = true;
if ( onLoad ) onLoad();
}
};
cubeImage.onerror = onError;
cubeImage.crossOrigin = this.crossOrigin;
cubeImage.src = array[ i ];
}
return texture;
},
loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
var images = [];
images.loadCount = 0;
var texture = new THREE.CompressedTexture();
texture.image = images;
if ( mapping !== undefined ) texture.mapping = mapping;
// no flipping for cube textures
// (also flipping doesn't work for compressed textures )
texture.flipY = false;
// can't generate mipmaps for compressed textures
// mips must be embedded in DDS files
texture.generateMipmaps = false;
var generateCubeFaceCallback = function ( rq, img ) {
return function () {
var buffer = rq.response;
var dds = THREE.ImageUtils.parseDDS( buffer, true );
img.format = dds.format;
img.mipmaps = dds.mipmaps;
img.width = dds.width;
img.height = dds.height;
images.loadCount += 1;
if ( images.loadCount === 6 ) {
texture.format = dds.format;
texture.needsUpdate = true;
if ( onLoad ) onLoad();
}
}
}
for ( var i = 0, il = array.length; i < il; ++ i ) {
var cubeImage = {};
images[ i ] = cubeImage;
var request = new XMLHttpRequest();
request.onload = generateCubeFaceCallback( request, cubeImage );
request.onerror = onError;
var url = array[ i ];
request.open( 'GET', url, true );
request.responseType = "arraybuffer";
request.send( null );
}
return texture;
},
parseDDS: function ( buffer, loadMipmaps ) {
var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
// Adapted from @toji's DDS utils
// https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
// All values and structures referenced from:
// http://msdn.microsoft.com/en-us/library/bb943991.aspx/
var DDS_MAGIC = 0x20534444;
var DDSD_CAPS = 0x1,
DDSD_HEIGHT = 0x2,
DDSD_WIDTH = 0x4,
DDSD_PITCH = 0x8,
DDSD_PIXELFORMAT = 0x1000,
DDSD_MIPMAPCOUNT = 0x20000,
DDSD_LINEARSIZE = 0x80000,
DDSD_DEPTH = 0x800000;
var DDSCAPS_COMPLEX = 0x8,
DDSCAPS_MIPMAP = 0x400000,
DDSCAPS_TEXTURE = 0x1000;
var DDSCAPS2_CUBEMAP = 0x200,
DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
DDSCAPS2_VOLUME = 0x200000;
var DDPF_ALPHAPIXELS = 0x1,
DDPF_ALPHA = 0x2,
DDPF_FOURCC = 0x4,
DDPF_RGB = 0x40,
DDPF_YUV = 0x200,
DDPF_LUMINANCE = 0x20000;
function fourCCToInt32( value ) {
return value.charCodeAt(0) +
(value.charCodeAt(1) << 8) +
(value.charCodeAt(2) << 16) +
(value.charCodeAt(3) << 24);
}
function int32ToFourCC( value ) {
return String.fromCharCode(
value & 0xff,
(value >> 8) & 0xff,
(value >> 16) & 0xff,
(value >> 24) & 0xff
);
}
var FOURCC_DXT1 = fourCCToInt32("DXT1");
var FOURCC_DXT3 = fourCCToInt32("DXT3");
var FOURCC_DXT5 = fourCCToInt32("DXT5");
var headerLengthInt = 31; // The header length in 32 bit ints
// Offsets into the header array
var off_magic = 0;
var off_size = 1;
var off_flags = 2;
var off_height = 3;
var off_width = 4;
var off_mipmapCount = 7;
var off_pfFlags = 20;
var off_pfFourCC = 21;
// Parse header
var header = new Int32Array( buffer, 0, headerLengthInt );
if ( header[ off_magic ] !== DDS_MAGIC ) {
console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
return dds;
}
if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
return dds;
}
var blockBytes;
var fourCC = header[ off_pfFourCC ];
switch ( fourCC ) {
case FOURCC_DXT1:
blockBytes = 8;
dds.format = THREE.RGB_S3TC_DXT1_Format;
break;
case FOURCC_DXT3:
blockBytes = 16;
dds.format = THREE.RGBA_S3TC_DXT3_Format;
break;
case FOURCC_DXT5:
blockBytes = 16;
dds.format = THREE.RGBA_S3TC_DXT5_Format;
break;
default:
console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
return dds;
}
dds.mipmapCount = 1;
if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
}
dds.width = header[ off_width ];
dds.height = header[ off_height ];
var dataOffset = header[ off_size ] + 4;
// Extract mipmaps buffers
var width = dds.width;
var height = dds.height;
for ( var i = 0; i < dds.mipmapCount; i ++ ) {
var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
var mipmap = { "data": byteArray, "width": width, "height": height };
dds.mipmaps.push( mipmap );
dataOffset += dataLength;
width = Math.max( width * 0.5, 1 );
height = Math.max( height * 0.5, 1 );
}
return dds;
},
getNormalMap: function ( image, depth ) {
// Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
var cross = function ( a, b ) {
return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
}
var subtract = function ( a, b ) {
return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
}
var normalize = function ( a ) {
var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
}
depth = depth | 1;
var width = image.width;
var height = image.height;
var canvas = document.createElement( 'canvas' );
canvas.width = width;
canvas.height = height;
var context = canvas.getContext( '2d' );
context.drawImage( image, 0, 0 );
var data = context.getImageData( 0, 0, width, height ).data;
var imageData = context.createImageData( width, height );
var output = imageData.data;
for ( var x = 0; x < width; x ++ ) {
for ( var y = 0; y < height; y ++ ) {
var ly = y - 1 < 0 ? 0 : y - 1;
var uy = y + 1 > height - 1 ? height - 1 : y + 1;
var lx = x - 1 < 0 ? 0 : x - 1;
var ux = x + 1 > width - 1 ? width - 1 : x + 1;
var points = [];
var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
var normals = [];
var num_points = points.length;
for ( var i = 0; i < num_points; i ++ ) {
var v1 = points[ i ];
var v2 = points[ ( i + 1 ) % num_points ];
v1 = subtract( v1, origin );
v2 = subtract( v2, origin );
normals.push( normalize( cross( v1, v2 ) ) );
}
var normal = [ 0, 0, 0 ];
for ( var i = 0; i < normals.length; i ++ ) {
normal[ 0 ] += normals[ i ][ 0 ];
normal[ 1 ] += normals[ i ][ 1 ];
normal[ 2 ] += normals[ i ][ 2 ];
}
normal[ 0 ] /= normals.length;
normal[ 1 ] /= normals.length;
normal[ 2 ] /= normals.length;
var idx = ( y * width + x ) * 4;
output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
output[ idx + 3 ] = 255;
}
}
context.putImageData( imageData, 0, 0 );
return canvas;
},
generateDataTexture: function ( width, height, color ) {
var size = width * height;
var data = new Uint8Array( 3 * size );
var r = Math.floor( color.r * 255 );
var g = Math.floor( color.g * 255 );
var b = Math.floor( color.b * 255 );
for ( var i = 0; i < size; i ++ ) {
data[ i * 3 ] = r;
data[ i * 3 + 1 ] = g;
data[ i * 3 + 2 ] = b;
}
var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
texture.needsUpdate = true;
return texture;
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.SceneUtils = {
createMultiMaterialObject: function ( geometry, materials ) {
var group = new THREE.Object3D();
for ( var i = 0, l = materials.length; i < l; i ++ ) {
group.add( new THREE.Mesh( geometry, materials[ i ] ) );
}
return group;
},
detach : function ( child, parent, scene ) {
child.applyMatrix( parent.matrixWorld );
parent.remove( child );
scene.add( child );
},
attach: function ( child, scene, parent ) {
var matrixWorldInverse = new THREE.Matrix4();
matrixWorldInverse.getInverse( parent.matrixWorld );
child.applyMatrix( matrixWorldInverse );
scene.remove( child );
parent.add( child );
}
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*
* ShaderUtils currently contains:
*
* fresnel
* normal
* cube
*
*/
if ( THREE.WebGLRenderer ) {
THREE.ShaderUtils = {
lib: {
/* -------------------------------------------------------------------------
// Fresnel shader
// - based on Nvidia Cg tutorial
------------------------------------------------------------------------- */
'fresnel': {
uniforms: {
"mRefractionRatio": { type: "f", value: 1.02 },
"mFresnelBias": { type: "f", value: 0.1 },
"mFresnelPower": { type: "f", value: 2.0 },
"mFresnelScale": { type: "f", value: 1.0 },
"tCube": { type: "t", value: null }
},
fragmentShader: [
"uniform samplerCube tCube;",
"varying vec3 vReflect;",
"varying vec3 vRefract[3];",
"varying float vReflectionFactor;",
"void main() {",
"vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
"vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
"refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
"refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
"refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
"refractedColor.a = 1.0;",
"gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
"}"
].join("\n"),
vertexShader: [
"uniform float mRefractionRatio;",
"uniform float mFresnelBias;",
"uniform float mFresnelScale;",
"uniform float mFresnelPower;",
"varying vec3 vReflect;",
"varying vec3 vRefract[3];",
"varying float vReflectionFactor;",
"void main() {",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
"vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
"vec3 I = mPosition.xyz - cameraPosition;",
"vReflect = reflect( I, nWorld );",
"vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
"vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
"vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
"vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
"gl_Position = projectionMatrix * mvPosition;",
"}"
].join("\n")
},
/* -------------------------------------------------------------------------
// Normal map shader
// - Blinn-Phong
// - normal + diffuse + specular + AO + displacement + reflection + shadow maps
// - point and directional lights (use with "lights: true" material option)
------------------------------------------------------------------------- */
'normal' : {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
THREE.UniformsLib[ "shadowmap" ],
{
"enableAO" : { type: "i", value: 0 },
"enableDiffuse" : { type: "i", value: 0 },
"enableSpecular" : { type: "i", value: 0 },
"enableReflection": { type: "i", value: 0 },
"enableDisplacement": { type: "i", value: 0 },
"tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
"tDiffuse" : { type: "t", value: null },
"tCube" : { type: "t", value: null },
"tNormal" : { type: "t", value: null },
"tSpecular" : { type: "t", value: null },
"tAO" : { type: "t", value: null },
"uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
"uDisplacementBias": { type: "f", value: 0.0 },
"uDisplacementScale": { type: "f", value: 1.0 },
"uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
"uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
"uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
"uShininess": { type: "f", value: 30 },
"uOpacity": { type: "f", value: 1 },
"useRefract": { type: "i", value: 0 },
"uRefractionRatio": { type: "f", value: 0.98 },
"uReflectivity": { type: "f", value: 0.5 },
"uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
"uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
"wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
}
] ),
fragmentShader: [
"uniform vec3 uAmbientColor;",
"uniform vec3 uDiffuseColor;",
"uniform vec3 uSpecularColor;",
"uniform float uShininess;",
"uniform float uOpacity;",
"uniform bool enableDiffuse;",
"uniform bool enableSpecular;",
"uniform bool enableAO;",
"uniform bool enableReflection;",
"uniform sampler2D tDiffuse;",
"uniform sampler2D tNormal;",
"uniform sampler2D tSpecular;",
"uniform sampler2D tAO;",
"uniform samplerCube tCube;",
"uniform vec2 uNormalScale;",
"uniform bool useRefract;",
"uniform float uRefractionRatio;",
"uniform float uReflectivity;",
"varying vec3 vTangent;",
"varying vec3 vBinormal;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"uniform vec3 ambientLightColor;",
"#if MAX_DIR_LIGHTS > 0",
"uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
"uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
"uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
"uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
"#endif",
"#ifdef WRAP_AROUND",
"uniform vec3 wrapRGB;",
"#endif",
"varying vec3 vWorldPosition;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
"vec3 specularTex = vec3( 1.0 );",
"vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
"normalTex.xy *= uNormalScale;",
"normalTex = normalize( normalTex );",
"if( enableDiffuse ) {",
"#ifdef GAMMA_INPUT",
"vec4 texelColor = texture2D( tDiffuse, vUv );",
"texelColor.xyz *= texelColor.xyz;",
"gl_FragColor = gl_FragColor * texelColor;",
"#else",
"gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
"#endif",
"}",
"if( enableAO ) {",
"#ifdef GAMMA_INPUT",
"vec4 aoColor = texture2D( tAO, vUv );",
"aoColor.xyz *= aoColor.xyz;",
"gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
"#else",
"gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
"#endif",
"}",
"if( enableSpecular )",
"specularTex = texture2D( tSpecular, vUv ).xyz;",
"mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
"vec3 finalNormal = tsb * normalTex;",
"#ifdef FLIP_SIDED",
"finalNormal = -finalNormal;",
"#endif",
"vec3 normal = normalize( finalNormal );",
"vec3 viewPosition = normalize( vViewPosition );",
// point lights
"#if MAX_POINT_LIGHTS > 0",
"vec3 pointDiffuse = vec3( 0.0 );",
"vec3 pointSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
"vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
"float pointDistance = 1.0;",
"if ( pointLightDistance[ i ] > 0.0 )",
"pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
"pointVector = normalize( pointVector );",
// diffuse
"#ifdef WRAP_AROUND",
"float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
"float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
"vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
"#else",
"float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
"#endif",
"pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
// specular
"vec3 pointHalfVector = normalize( pointVector + viewPosition );",
"float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
"float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
"vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
"pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
"#else",
"pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
"#endif",
"}",
"#endif",
// spot lights
"#if MAX_SPOT_LIGHTS > 0",
"vec3 spotDiffuse = vec3( 0.0 );",
"vec3 spotSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
"vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
"float spotDistance = 1.0;",
"if ( spotLightDistance[ i ] > 0.0 )",
"spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
"spotVector = normalize( spotVector );",
"float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
"if ( spotEffect > spotLightAngle[ i ] ) {",
"spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
// diffuse
"#ifdef WRAP_AROUND",
"float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
"float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
"vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
"#else",
"float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
"#endif",
"spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
// specular
"vec3 spotHalfVector = normalize( spotVector + viewPosition );",
"float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
"float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
"vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
"spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
"#else",
"spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
"#endif",
"}",
"}",
"#endif",
// directional lights
"#if MAX_DIR_LIGHTS > 0",
"vec3 dirDiffuse = vec3( 0.0 );",
"vec3 dirSpecular = vec3( 0.0 );",
"for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
"vec3 dirVector = normalize( lDirection.xyz );",
// diffuse
"#ifdef WRAP_AROUND",
"float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
"float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
"vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
"#else",
"float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
"#endif",
"dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
// specular
"vec3 dirHalfVector = normalize( dirVector + viewPosition );",
"float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
"float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
"vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
"dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
"#else",
"dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
"#endif",
"}",
"#endif",
// hemisphere lights
"#if MAX_HEMI_LIGHTS > 0",
"vec3 hemiDiffuse = vec3( 0.0 );",
"vec3 hemiSpecular = vec3( 0.0 );" ,
"for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
"vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",
// diffuse
"float dotProduct = dot( normal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
"hemiDiffuse += uDiffuseColor * hemiColor;",
// specular (sky light)
"vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
"float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
"float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
// specular (ground light)
"vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
"vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
"float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
"float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
"#ifdef PHYSICALLY_BASED_SHADING",
"float dotProductGround = dot( normal, lVectorGround );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
"vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
"vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
"hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
"#else",
"hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
"#endif",
"}",
"#endif",
// all lights contribution summation
"vec3 totalDiffuse = vec3( 0.0 );",
"vec3 totalSpecular = vec3( 0.0 );",
"#if MAX_DIR_LIGHTS > 0",
"totalDiffuse += dirDiffuse;",
"totalSpecular += dirSpecular;",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"totalDiffuse += hemiDiffuse;",
"totalSpecular += hemiSpecular;",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"totalDiffuse += pointDiffuse;",
"totalSpecular += pointSpecular;",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"totalDiffuse += spotDiffuse;",
"totalSpecular += spotSpecular;",
"#endif",
"#ifdef METAL",
"gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
"#else",
"gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
"#endif",
"if ( enableReflection ) {",
"vec3 vReflect;",
"vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
"if ( useRefract ) {",
"vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
"} else {",
"vReflect = reflect( cameraToVertex, normal );",
"}",
"vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
"#ifdef GAMMA_INPUT",
"cubeColor.xyz *= cubeColor.xyz;",
"#endif",
"gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
"}",
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n"),
vertexShader: [
"attribute vec4 tangent;",
"uniform vec2 uOffset;",
"uniform vec2 uRepeat;",
"uniform bool enableDisplacement;",
"#ifdef VERTEX_TEXTURES",
"uniform sampler2D tDisplacement;",
"uniform float uDisplacementScale;",
"uniform float uDisplacementBias;",
"#endif",
"varying vec3 vTangent;",
"varying vec3 vBinormal;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vWorldPosition;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
// normal, tangent and binormal vectors
"#ifdef USE_SKINNING",
"vNormal = normalMatrix * skinnedNormal.xyz;",
"vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
"vTangent = normalMatrix * skinnedTangent.xyz;",
"#else",
"vNormal = normalMatrix * normal;",
"vTangent = normalMatrix * tangent.xyz;",
"#endif",
"vBinormal = cross( vNormal, vTangent ) * tangent.w;",
"vUv = uv * uRepeat + uOffset;",
// displacement mapping
"vec3 displacedPosition;",
"#ifdef VERTEX_TEXTURES",
"if ( enableDisplacement ) {",
"vec3 dv = texture2D( tDisplacement, uv ).xyz;",
"float df = uDisplacementScale * dv.x + uDisplacementBias;",
"displacedPosition = position + normalize( normal ) * df;",
"} else {",
"#ifdef USE_SKINNING",
"vec4 skinVertex = vec4( position, 1.0 );",
"vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
"skinned += boneMatY * skinVertex * skinWeight.y;",
"displacedPosition = skinned.xyz;",
"#else",
"displacedPosition = position;",
"#endif",
"}",
"#else",
"#ifdef USE_SKINNING",
"vec4 skinVertex = vec4( position, 1.0 );",
"vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
"skinned += boneMatY * skinVertex * skinWeight.y;",
"displacedPosition = skinned.xyz;",
"#else",
"displacedPosition = position;",
"#endif",
"#endif",
//
"vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
"vec4 mPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
"gl_Position = projectionMatrix * mvPosition;",
//
"vWorldPosition = mPosition.xyz;",
"vViewPosition = -mvPosition.xyz;",
// shadows
"#ifdef USE_SHADOWMAP",
"for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
"vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
"}",
"#endif",
"}"
].join("\n")
},
/* -------------------------------------------------------------------------
// Cube map shader
------------------------------------------------------------------------- */
'cube': {
uniforms: { "tCube": { type: "t", value: null },
"tFlip": { type: "f", value: -1 } },
vertexShader: [
"varying vec3 vViewPosition;",
"void main() {",
"vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
"vViewPosition = cameraPosition - mPosition.xyz;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform samplerCube tCube;",
"uniform float tFlip;",
"varying vec3 vViewPosition;",
"void main() {",
"vec3 wPos = cameraPosition - vViewPosition;",
"gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
"}"
].join("\n")
}
}
};
};
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author alteredq / http://alteredqualia.com/
*
* For Text operations in three.js (See TextGeometry)
*
* It uses techniques used in:
*
* typeface.js and canvastext
* For converting fonts and rendering with javascript
* http://typeface.neocracy.org
*
* Triangulation ported from AS3
* Simple Polygon Triangulation
* http://actionsnippet.com/?p=1462
*
* A Method to triangulate shapes with holes
* http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
*
*/
THREE.FontUtils = {
faces : {},
// Just for now. face[weight][style]
face : "helvetiker",
weight: "normal",
style : "normal",
size : 150,
divisions : 10,
getFace : function() {
return this.faces[ this.face ][ this.weight ][ this.style ];
},
loadFace : function( data ) {
var family = data.familyName.toLowerCase();
var ThreeFont = this;
ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
return data;
},
drawText : function( text ) {
var characterPts = [], allPts = [];
// RenderText
var i, p,
face = this.getFace(),
scale = this.size / face.resolution,
offset = 0,
chars = String( text ).split( '' ),
length = chars.length;
var fontPaths = [];
for ( i = 0; i < length; i ++ ) {
var path = new THREE.Path();
var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
offset += ret.offset;
fontPaths.push( ret.path );
}
// get the width
var width = offset / 2;
//
// for ( p = 0; p < allPts.length; p++ ) {
//
// allPts[ p ].x -= width;
//
// }
//var extract = this.extractPoints( allPts, characterPts );
//extract.contour = allPts;
//extract.paths = fontPaths;
//extract.offset = width;
return { paths : fontPaths, offset : width };
},
extractGlyphPoints : function( c, face, scale, offset, path ) {
var pts = [];
var i, i2, divisions,
outline, action, length,
scaleX, scaleY,
x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
laste,
glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
if ( !glyph ) return;
if ( glyph.o ) {
outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
length = outline.length;
scaleX = scale;
scaleY = scale;
for ( i = 0; i < length; ) {
action = outline[ i ++ ];
//console.log( action );
switch( action ) {
case 'm':
// Move To
x = outline[ i++ ] * scaleX + offset;
y = outline[ i++ ] * scaleY;
path.moveTo( x, y );
break;
case 'l':
// Line To
x = outline[ i++ ] * scaleX + offset;
y = outline[ i++ ] * scaleY;
path.lineTo(x,y);
break;
case 'q':
// QuadraticCurveTo
cpx = outline[ i++ ] * scaleX + offset;
cpy = outline[ i++ ] * scaleY;
cpx1 = outline[ i++ ] * scaleX + offset;
cpy1 = outline[ i++ ] * scaleY;
path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
laste = pts[ pts.length - 1 ];
if ( laste ) {
cpx0 = laste.x;
cpy0 = laste.y;
for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
var t = i2 / divisions;
var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
}
}
break;
case 'b':
// Cubic Bezier Curve
cpx = outline[ i++ ] * scaleX + offset;
cpy = outline[ i++ ] * scaleY;
cpx1 = outline[ i++ ] * scaleX + offset;
cpy1 = outline[ i++ ] * -scaleY;
cpx2 = outline[ i++ ] * scaleX + offset;
cpy2 = outline[ i++ ] * -scaleY;
path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
laste = pts[ pts.length - 1 ];
if ( laste ) {
cpx0 = laste.x;
cpy0 = laste.y;
for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
var t = i2 / divisions;
var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
}
}
break;
}
}
}
return { offset: glyph.ha*scale, path:path};
}
};
THREE.FontUtils.generateShapes = function( text, parameters ) {
// Parameters
parameters = parameters || {};
var size = parameters.size !== undefined ? parameters.size : 100;
var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
var font = parameters.font !== undefined ? parameters.font : "helvetiker";
var weight = parameters.weight !== undefined ? parameters.weight : "normal";
var style = parameters.style !== undefined ? parameters.style : "normal";
THREE.FontUtils.size = size;
THREE.FontUtils.divisions = curveSegments;
THREE.FontUtils.face = font;
THREE.FontUtils.weight = weight;
THREE.FontUtils.style = style;
// Get a Font data json object
var data = THREE.FontUtils.drawText( text );
var paths = data.paths;
var shapes = [];
for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
}
return shapes;
};
/**
* This code is a quick port of code written in C++ which was submitted to
* flipcode.com by John W. Ratcliff // July 22, 2000
* See original code and more information here:
* http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
*
* ported to actionscript by Zevan Rosser
* www.actionsnippet.com
*
* ported to javascript by Joshua Koo
* http://www.lab4games.net/zz85/blog
*
*/
( function( namespace ) {
var EPSILON = 0.0000000001;
// takes in an contour array and returns
var process = function( contour, indices ) {
var n = contour.length;
if ( n < 3 ) return null;
var result = [],
verts = [],
vertIndices = [];
/* we want a counter-clockwise polygon in verts */
var u, v, w;
if ( area( contour ) > 0.0 ) {
for ( v = 0; v < n; v++ ) verts[ v ] = v;
} else {
for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
}
var nv = n;
/* remove nv - 2 vertices, creating 1 triangle every time */
var count = 2 * nv; /* error detection */
for( v = nv - 1; nv > 2; ) {
/* if we loop, it is probably a non-simple polygon */
if ( ( count-- ) <= 0 ) {
//** Triangulate: ERROR - probable bad polygon!
//throw ( "Warning, unable to triangulate polygon!" );
//return null;
// Sometimes warning is fine, especially polygons are triangulated in reverse.
console.log( "Warning, unable to triangulate polygon!" );
if ( indices ) return vertIndices;
return result;
}
/* three consecutive vertices in current polygon, <u,v,w> */
u = v; if ( nv <= u ) u = 0; /* previous */
v = u + 1; if ( nv <= v ) v = 0; /* new v */
w = v + 1; if ( nv <= w ) w = 0; /* next */
if ( snip( contour, u, v, w, nv, verts ) ) {
var a, b, c, s, t;
/* true names of the vertices */
a = verts[ u ];
b = verts[ v ];
c = verts[ w ];
/* output Triangle */
/*
result.push( contour[ a ] );
result.push( contour[ b ] );
result.push( contour[ c ] );
*/
result.push( [ contour[ a ],
contour[ b ],
contour[ c ] ] );
vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
/* remove v from the remaining polygon */
for( s = v, t = v + 1; t < nv; s++, t++ ) {
verts[ s ] = verts[ t ];
}
nv--;
/* reset error detection counter */
count = 2 * nv;
}
}
if ( indices ) return vertIndices;
return result;
};
// calculate area of the contour polygon
var area = function ( contour ) {
var n = contour.length;
var a = 0.0;
for( var p = n - 1, q = 0; q < n; p = q++ ) {
a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
}
return a * 0.5;
};
// see if p is inside triangle abc
var insideTriangle = function( ax, ay,
bx, by,
cx, cy,
px, py ) {
var aX, aY, bX, bY;
var cX, cY, apx, apy;
var bpx, bpy, cpx, cpy;
var cCROSSap, bCROSScp, aCROSSbp;
aX = cx - bx; aY = cy - by;
bX = ax - cx; bY = ay - cy;
cX = bx - ax; cY = by - ay;
apx= px -ax; apy= py - ay;
bpx= px - bx; bpy= py - by;
cpx= px - cx; cpy= py - cy;
aCROSSbp = aX*bpy - aY*bpx;
cCROSSap = cX*apy - cY*apx;
bCROSScp = bX*cpy - bY*cpx;
return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
};
var snip = function ( contour, u, v, w, n, verts ) {
var p;
var ax, ay, bx, by;
var cx, cy, px, py;
ax = contour[ verts[ u ] ].x;
ay = contour[ verts[ u ] ].y;
bx = contour[ verts[ v ] ].x;
by = contour[ verts[ v ] ].y;
cx = contour[ verts[ w ] ].x;
cy = contour[ verts[ w ] ].y;
if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
for ( p = 0; p < n; p++ ) {
if( (p == u) || (p == v) || (p == w) ) continue;
px = contour[ verts[ p ] ].x
py = contour[ verts[ p ] ].y
if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
}
return true;
};
namespace.Triangulate = process;
namespace.Triangulate.area = area;
return namespace;
})(THREE.FontUtils);
// To use the typeface.js face files, hook up the API
self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Extensible curve object
*
* Some common of Curve methods
* .getPoint(t), getTangent(t)
* .getPointAt(u), getTagentAt(u)
* .getPoints(), .getSpacedPoints()
* .getLength()
* .updateArcLengths()
*
* This file contains following classes:
*
* -- 2d classes --
* THREE.Curve
* THREE.LineCurve
* THREE.QuadraticBezierCurve
* THREE.CubicBezierCurve
* THREE.SplineCurve
* THREE.ArcCurve
* THREE.EllipseCurve
*
* -- 3d classes --
* THREE.LineCurve3
* THREE.QuadraticBezierCurve3
* THREE.CubicBezierCurve3
* THREE.SplineCurve3
* THREE.ClosedSplineCurve3
*
* A series of curves can be represented as a THREE.CurvePath
*
**/
/**************************************************************
* Abstract Curve base class
**************************************************************/
THREE.Curve = function () {
};
// Virtual base class method to overwrite and implement in subclasses
// - t [0 .. 1]
THREE.Curve.prototype.getPoint = function ( t ) {
console.log( "Warning, getPoint() not implemented!" );
return null;
};
// Get point at relative position in curve according to arc length
// - u [0 .. 1]
THREE.Curve.prototype.getPointAt = function ( u ) {
var t = this.getUtoTmapping( u );
return this.getPoint( t );
};
// Get sequence of points using getPoint( t )
THREE.Curve.prototype.getPoints = function ( divisions ) {
if ( !divisions ) divisions = 5;
var d, pts = [];
for ( d = 0; d <= divisions; d ++ ) {
pts.push( this.getPoint( d / divisions ) );
}
return pts;
};
// Get sequence of points using getPointAt( u )
THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
if ( !divisions ) divisions = 5;
var d, pts = [];
for ( d = 0; d <= divisions; d ++ ) {
pts.push( this.getPointAt( d / divisions ) );
}
return pts;
};
// Get total curve arc length
THREE.Curve.prototype.getLength = function () {
var lengths = this.getLengths();
return lengths[ lengths.length - 1 ];
};
// Get list of cumulative segment lengths
THREE.Curve.prototype.getLengths = function ( divisions ) {
if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
if ( this.cacheArcLengths
&& ( this.cacheArcLengths.length == divisions + 1 )
&& !this.needsUpdate) {
//console.log( "cached", this.cacheArcLengths );
return this.cacheArcLengths;
}
this.needsUpdate = false;
var cache = [];
var current, last = this.getPoint( 0 );
var p, sum = 0;
cache.push( 0 );
for ( p = 1; p <= divisions; p ++ ) {
current = this.getPoint ( p / divisions );
sum += current.distanceTo( last );
cache.push( sum );
last = current;
}
this.cacheArcLengths = cache;
return cache; // { sums: cache, sum:sum }; Sum is in the last element.
};
THREE.Curve.prototype.updateArcLengths = function() {
this.needsUpdate = true;
this.getLengths();
};
// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
var arcLengths = this.getLengths();
var i = 0, il = arcLengths.length;
var targetArcLength; // The targeted u distance value to get
if ( distance ) {
targetArcLength = distance;
} else {
targetArcLength = u * arcLengths[ il - 1 ];
}
//var time = Date.now();
// binary search for the index with largest value smaller than target u distance
var low = 0, high = il - 1, comparison;
while ( low <= high ) {
i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
comparison = arcLengths[ i ] - targetArcLength;
if ( comparison < 0 ) {
low = i + 1;
continue;
} else if ( comparison > 0 ) {
high = i - 1;
continue;
} else {
high = i;
break;
// DONE
}
}
i = high;
//console.log('b' , i, low, high, Date.now()- time);
if ( arcLengths[ i ] == targetArcLength ) {
var t = i / ( il - 1 );
return t;
}
// we could get finer grain at lengths, or use simple interpolatation between two points
var lengthBefore = arcLengths[ i ];
var lengthAfter = arcLengths[ i + 1 ];
var segmentLength = lengthAfter - lengthBefore;
// determine where we are between the 'before' and 'after' points
var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
// add that fractional amount to t
var t = ( i + segmentFraction ) / ( il -1 );
return t;
};
// In 2D space, there are actually 2 normal vectors,
// and in 3D space, infinte
// TODO this should be depreciated.
THREE.Curve.prototype.getNormalVector = function( t ) {
var vec = this.getTangent( t );
return new THREE.Vector2( -vec.y , vec.x );
};
// Returns a unit vector tangent at t
// In case any sub curve does not implement its tangent / normal finding,
// we get 2 points with a small delta and find a gradient of the 2 points
// which seems to make a reasonable approximation
THREE.Curve.prototype.getTangent = function( t ) {
var delta = 0.0001;
var t1 = t - delta;
var t2 = t + delta;
// Capping in case of danger
if ( t1 < 0 ) t1 = 0;
if ( t2 > 1 ) t2 = 1;
var pt1 = this.getPoint( t1 );
var pt2 = this.getPoint( t2 );
var vec = pt2.clone().subSelf(pt1);
return vec.normalize();
};
THREE.Curve.prototype.getTangentAt = function ( u ) {
var t = this.getUtoTmapping( u );
return this.getTangent( t );
};
/**************************************************************
* Line
**************************************************************/
THREE.LineCurve = function ( v1, v2 ) {
this.v1 = v1;
this.v2 = v2;
};
THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.LineCurve.prototype.getPoint = function ( t ) {
var point = this.v2.clone().subSelf(this.v1);
point.multiplyScalar( t ).addSelf( this.v1 );
return point;
};
// Line curve is linear, so we can overwrite default getPointAt
THREE.LineCurve.prototype.getPointAt = function ( u ) {
return this.getPoint( u );
};
THREE.LineCurve.prototype.getTangent = function( t ) {
var tangent = this.v2.clone().subSelf(this.v1);
return tangent.normalize();
};
/**************************************************************
* Quadratic Bezier curve
**************************************************************/
THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
};
THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
var tx, ty;
tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
return new THREE.Vector2( tx, ty );
};
THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
var tx, ty;
tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
// returns unit vector
var tangent = new THREE.Vector2( tx, ty );
tangent.normalize();
return tangent;
};
/**************************************************************
* Cubic Bezier curve
**************************************************************/
THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
};
THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
var tx, ty;
tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
return new THREE.Vector2( tx, ty );
};
THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
var tx, ty;
tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
var tangent = new THREE.Vector2( tx, ty );
tangent.normalize();
return tangent;
};
/**************************************************************
* Spline curve
**************************************************************/
THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
this.points = (points == undefined) ? [] : points;
};
THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.SplineCurve.prototype.getPoint = function ( t ) {
var v = new THREE.Vector2();
var c = [];
var points = this.points, point, intPoint, weight;
point = ( points.length - 1 ) * t;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
return v;
};
/**************************************************************
* Ellipse curve
**************************************************************/
THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
aStartAngle, aEndAngle,
aClockwise ) {
this.aX = aX;
this.aY = aY;
this.xRadius = xRadius;
this.yRadius = yRadius;
this.aStartAngle = aStartAngle;
this.aEndAngle = aEndAngle;
this.aClockwise = aClockwise;
};
THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.EllipseCurve.prototype.getPoint = function ( t ) {
var deltaAngle = this.aEndAngle - this.aStartAngle;
if ( !this.aClockwise ) {
t = 1 - t;
}
var angle = this.aStartAngle + t * deltaAngle;
var tx = this.aX + this.xRadius * Math.cos( angle );
var ty = this.aY + this.yRadius * Math.sin( angle );
return new THREE.Vector2( tx, ty );
};
/**************************************************************
* Arc curve
**************************************************************/
THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
};
THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
/**************************************************************
* Utils
**************************************************************/
THREE.Curve.Utils = {
tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
},
// Puay Bing, thanks for helping with this derivative!
tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
return -3 * p0 * (1 - t) * (1 - t) +
3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
6 * t * p2 * (1-t) - 3 * t * t * p2 +
3 * t * t * p3;
},
tangentSpline: function ( t, p0, p1, p2, p3 ) {
// To check if my formulas are correct
var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
var h11 = 3 * t * t - 2 * t; // t3 − t2
return h00 + h10 + h01 + h11;
},
// Catmull-Rom
interpolate: function( p0, p1, p2, p3, t ) {
var v0 = ( p2 - p0 ) * 0.5;
var v1 = ( p3 - p1 ) * 0.5;
var t2 = t * t;
var t3 = t * t2;
return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
}
};
// TODO: Transformation for Curves?
/**************************************************************
* 3D Curves
**************************************************************/
// A Factory method for creating new curve subclasses
THREE.Curve.create = function ( constructor, getPointFunc ) {
constructor.prototype = Object.create( THREE.Curve.prototype );
constructor.prototype.getPoint = getPointFunc;
return constructor;
};
/**************************************************************
* Line3D
**************************************************************/
THREE.LineCurve3 = THREE.Curve.create(
function ( v1, v2 ) {
this.v1 = v1;
this.v2 = v2;
},
function ( t ) {
var r = new THREE.Vector3();
r.sub( this.v2, this.v1 ); // diff
r.multiplyScalar( t );
r.addSelf( this.v1 );
return r;
}
);
/**************************************************************
* Quadratic Bezier 3D curve
**************************************************************/
THREE.QuadraticBezierCurve3 = THREE.Curve.create(
function ( v0, v1, v2 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
},
function ( t ) {
var tx, ty, tz;
tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
return new THREE.Vector3( tx, ty, tz );
}
);
/**************************************************************
* Cubic Bezier 3D curve
**************************************************************/
THREE.CubicBezierCurve3 = THREE.Curve.create(
function ( v0, v1, v2, v3 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
},
function ( t ) {
var tx, ty, tz;
tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
return new THREE.Vector3( tx, ty, tz );
}
);
/**************************************************************
* Spline 3D curve
**************************************************************/
THREE.SplineCurve3 = THREE.Curve.create(
function ( points /* array of Vector3 */) {
this.points = (points == undefined) ? [] : points;
},
function ( t ) {
var v = new THREE.Vector3();
var c = [];
var points = this.points, point, intPoint, weight;
point = ( points.length - 1 ) * t;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
var pt0 = points[ c[0] ],
pt1 = points[ c[1] ],
pt2 = points[ c[2] ],
pt3 = points[ c[3] ];
v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
return v;
}
);
// THREE.SplineCurve3.prototype.getTangent = function(t) {
// var v = new THREE.Vector3();
// var c = [];
// var points = this.points, point, intPoint, weight;
// point = ( points.length - 1 ) * t;
// intPoint = Math.floor( point );
// weight = point - intPoint;
// c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
// c[ 1 ] = intPoint;
// c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
// c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
// var pt0 = points[ c[0] ],
// pt1 = points[ c[1] ],
// pt2 = points[ c[2] ],
// pt3 = points[ c[3] ];
// // t = weight;
// v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
// v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
// v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
// return v;
// }
/**************************************************************
* Closed Spline 3D curve
**************************************************************/
THREE.ClosedSplineCurve3 = THREE.Curve.create(
function ( points /* array of Vector3 */) {
this.points = (points == undefined) ? [] : points;
},
function ( t ) {
var v = new THREE.Vector3();
var c = [];
var points = this.points, point, intPoint, weight;
point = ( points.length - 0 ) * t;
// This needs to be from 0-length +1
intPoint = Math.floor( point );
weight = point - intPoint;
intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
c[ 0 ] = ( intPoint - 1 ) % points.length;
c[ 1 ] = ( intPoint ) % points.length;
c[ 2 ] = ( intPoint + 1 ) % points.length;
c[ 3 ] = ( intPoint + 2 ) % points.length;
v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
return v;
}
);
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*
**/
/**************************************************************
* Curved Path - a curve path is simply a array of connected
* curves, but retains the api of a curve
**************************************************************/
THREE.CurvePath = function () {
this.curves = [];
this.bends = [];
this.autoClose = false; // Automatically closes the path
};
THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
THREE.CurvePath.prototype.add = function ( curve ) {
this.curves.push( curve );
};
THREE.CurvePath.prototype.checkConnection = function() {
// TODO
// If the ending of curve is not connected to the starting
// or the next curve, then, this is not a real path
};
THREE.CurvePath.prototype.closePath = function() {
// TODO Test
// and verify for vector3 (needs to implement equals)
// Add a line curve if start and end of lines are not connected
var startPoint = this.curves[0].getPoint(0);
var endPoint = this.curves[this.curves.length-1].getPoint(1);
if (!startPoint.equals(endPoint)) {
this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
}
};
// To get accurate point with reference to
// entire path distance at time t,
// following has to be done:
// 1. Length of each sub path have to be known
// 2. Locate and identify type of curve
// 3. Get t for the curve
// 4. Return curve.getPointAt(t')
THREE.CurvePath.prototype.getPoint = function( t ) {
var d = t * this.getLength();
var curveLengths = this.getCurveLengths();
var i = 0, diff, curve;
// To think about boundaries points.
while ( i < curveLengths.length ) {
if ( curveLengths[ i ] >= d ) {
diff = curveLengths[ i ] - d;
curve = this.curves[ i ];
var u = 1 - diff / curve.getLength();
return curve.getPointAt( u );
break;
}
i ++;
}
return null;
// loop where sum != 0, sum > d , sum+1 <d
};
/*
THREE.CurvePath.prototype.getTangent = function( t ) {
};*/
// We cannot use the default THREE.Curve getPoint() with getLength() because in
// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
// getPoint() depends on getLength
THREE.CurvePath.prototype.getLength = function() {
var lens = this.getCurveLengths();
return lens[ lens.length - 1 ];
};
// Compute lengths and cache them
// We cannot overwrite getLengths() because UtoT mapping uses it.
THREE.CurvePath.prototype.getCurveLengths = function() {
// We use cache values if curves and cache array are same length
if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
return this.cacheLengths;
};
// Get length of subsurve
// Push sums into cached array
var lengths = [], sums = 0;
var i, il = this.curves.length;
for ( i = 0; i < il; i ++ ) {
sums += this.curves[ i ].getLength();
lengths.push( sums );
}
this.cacheLengths = lengths;
return lengths;
};
// Returns min and max coordinates, as well as centroid
THREE.CurvePath.prototype.getBoundingBox = function () {
var points = this.getPoints();
var maxX, maxY, maxZ;
var minX, minY, minZ;
maxX = maxY = Number.NEGATIVE_INFINITY;
minX = minY = Number.POSITIVE_INFINITY;
var p, i, il, sum;
var v3 = points[0] instanceof THREE.Vector3;
sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
for ( i = 0, il = points.length; i < il; i ++ ) {
p = points[ i ];
if ( p.x > maxX ) maxX = p.x;
else if ( p.x < minX ) minX = p.x;
if ( p.y > maxY ) maxY = p.y;
else if ( p.y < minY ) minY = p.y;
if (v3) {
if ( p.z > maxZ ) maxZ = p.z;
else if ( p.z < minZ ) minZ = p.z;
}
sum.addSelf( p );
}
var ret = {
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY,
centroid: sum.divideScalar( il )
};
if (v3) {
ret.maxZ = maxZ;
ret.minZ = minZ;
}
return ret;
};
/**************************************************************
* Create Geometries Helpers
**************************************************************/
/// Generate geometry from path points (for Line or ParticleSystem objects)
THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
var pts = this.getPoints( divisions, true );
return this.createGeometry( pts );
};
// Generate geometry from equidistance sampling along the path
THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
var pts = this.getSpacedPoints( divisions, true );
return this.createGeometry( pts );
};
THREE.CurvePath.prototype.createGeometry = function( points ) {
var geometry = new THREE.Geometry();
for ( var i = 0; i < points.length; i ++ ) {
geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
}
return geometry;
};
/**************************************************************
* Bend / Wrap Helper Methods
**************************************************************/
// Wrap path / Bend modifiers?
THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
this.bends.push( bendpath );
};
THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
var i, il;
if ( !bends ) {
bends = this.bends;
}
for ( i = 0, il = bends.length; i < il; i ++ ) {
oldPts = this.getWrapPoints( oldPts, bends[ i ] );
}
return oldPts;
};
THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
var oldPts = this.getSpacedPoints( segments );
var i, il;
if ( !bends ) {
bends = this.bends;
}
for ( i = 0, il = bends.length; i < il; i ++ ) {
oldPts = this.getWrapPoints( oldPts, bends[ i ] );
}
return oldPts;
};
// This returns getPoints() bend/wrapped around the contour of a path.
// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
var bounds = this.getBoundingBox();
var i, il, p, oldX, oldY, xNorm;
for ( i = 0, il = oldPts.length; i < il; i ++ ) {
p = oldPts[ i ];
oldX = p.x;
oldY = p.y;
xNorm = oldX / bounds.maxX;
// If using actual distance, for length > path, requires line extrusions
//xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
xNorm = path.getUtoTmapping( xNorm, oldX );
// check for out of bounds?
var pathPt = path.getPoint( xNorm );
var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
p.x = pathPt.x + normal.x;
p.y = pathPt.y + normal.y;
}
return oldPts;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Gyroscope = function () {
THREE.Object3D.call( this );
};
THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
this.matrixAutoUpdate && this.updateMatrix();
// update matrixWorld
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent ) {
this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
} else {
this.matrixWorld.copy( this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].updateMatrixWorld( force );
}
};
THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Creates free form 2d path using series of points, lines or curves.
*
**/
THREE.Path = function ( points ) {
THREE.CurvePath.call(this);
this.actions = [];
if ( points ) {
this.fromPoints( points );
}
};
THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
THREE.PathActions = {
MOVE_TO: 'moveTo',
LINE_TO: 'lineTo',
QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
CSPLINE_THRU: 'splineThru', // Catmull-rom spline
ARC: 'arc', // Circle
ELLIPSE: 'ellipse'
};
// TODO Clean up PATH API
// Create path using straight lines to connect all points
// - vectors: array of Vector2
THREE.Path.prototype.fromPoints = function ( vectors ) {
this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
this.lineTo( vectors[ v ].x, vectors[ v ].y );
};
};
// startPath() endPath()?
THREE.Path.prototype.moveTo = function ( x, y ) {
var args = Array.prototype.slice.call( arguments );
this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
};
THREE.Path.prototype.lineTo = function ( x, y ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
};
THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
new THREE.Vector2( aCPx, aCPy ),
new THREE.Vector2( aX, aY ) );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
};
THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
aCP2x, aCP2y,
aX, aY ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
new THREE.Vector2( aCP1x, aCP1y ),
new THREE.Vector2( aCP2x, aCP2y ),
new THREE.Vector2( aX, aY ) );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
};
THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
//---
var npts = [ new THREE.Vector2( x0, y0 ) ];
Array.prototype.push.apply( npts, pts );
var curve = new THREE.SplineCurve( npts );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
};
// FUTURE: Change the API or follow canvas API?
THREE.Path.prototype.arc = function ( aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise ) {
var lastargs = this.actions[ this.actions.length - 1].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
this.absarc(aX + x0, aY + y0, aRadius,
aStartAngle, aEndAngle, aClockwise );
};
THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise ) {
this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
};
THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise ) {
var lastargs = this.actions[ this.actions.length - 1].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise );
};
THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise ) {
var args = Array.prototype.slice.call( arguments );
var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise );
this.curves.push( curve );
var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
args.push(lastPoint.x);
args.push(lastPoint.y);
this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
};
THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
if ( ! divisions ) divisions = 40;
var points = [];
for ( var i = 0; i < divisions; i ++ ) {
points.push( this.getPoint( i / divisions ) );
//if( !this.getPoint( i / divisions ) ) throw "DIE";
}
// if ( closedPath ) {
//
// points.push( points[ 0 ] );
//
// }
return points;
};
/* Return an array of vectors based on contour of the path */
THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
if (this.useSpacedPoints) {
console.log('tata');
return this.getSpacedPoints( divisions, closedPath );
}
divisions = divisions || 12;
var points = [];
var i, il, item, action, args;
var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
laste, j,
t, tx, ty;
for ( i = 0, il = this.actions.length; i < il; i ++ ) {
item = this.actions[ i ];
action = item.action;
args = item.args;
switch( action ) {
case THREE.PathActions.MOVE_TO:
points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
break;
case THREE.PathActions.LINE_TO:
points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
break;
case THREE.PathActions.QUADRATIC_CURVE_TO:
cpx = args[ 2 ];
cpy = args[ 3 ];
cpx1 = args[ 0 ];
cpy1 = args[ 1 ];
if ( points.length > 0 ) {
laste = points[ points.length - 1 ];
cpx0 = laste.x;
cpy0 = laste.y;
} else {
laste = this.actions[ i - 1 ].args;
cpx0 = laste[ laste.length - 2 ];
cpy0 = laste[ laste.length - 1 ];
}
for ( j = 1; j <= divisions; j ++ ) {
t = j / divisions;
tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
points.push( new THREE.Vector2( tx, ty ) );
}
break;
case THREE.PathActions.BEZIER_CURVE_TO:
cpx = args[ 4 ];
cpy = args[ 5 ];
cpx1 = args[ 0 ];
cpy1 = args[ 1 ];
cpx2 = args[ 2 ];
cpy2 = args[ 3 ];
if ( points.length > 0 ) {
laste = points[ points.length - 1 ];
cpx0 = laste.x;
cpy0 = laste.y;
} else {
laste = this.actions[ i - 1 ].args;
cpx0 = laste[ laste.length - 2 ];
cpy0 = laste[ laste.length - 1 ];
}
for ( j = 1; j <= divisions; j ++ ) {
t = j / divisions;
tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
points.push( new THREE.Vector2( tx, ty ) );
}
break;
case THREE.PathActions.CSPLINE_THRU:
laste = this.actions[ i - 1 ].args;
var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
var spts = [ last ];
var n = divisions * args[ 0 ].length;
spts = spts.concat( args[ 0 ] );
var spline = new THREE.SplineCurve( spts );
for ( j = 1; j <= n; j ++ ) {
points.push( spline.getPointAt( j / n ) ) ;
}
break;
case THREE.PathActions.ARC:
var aX = args[ 0 ], aY = args[ 1 ],
aRadius = args[ 2 ],
aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
aClockwise = !!args[ 5 ];
var deltaAngle = aEndAngle - aStartAngle;
var angle;
var tdivisions = divisions * 2;
for ( j = 1; j <= tdivisions; j ++ ) {
t = j / tdivisions;
if ( ! aClockwise ) {
t = 1 - t;
}
angle = aStartAngle + t * deltaAngle;
tx = aX + aRadius * Math.cos( angle );
ty = aY + aRadius * Math.sin( angle );
//console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
points.push( new THREE.Vector2( tx, ty ) );
}
//console.log(points);
break;
case THREE.PathActions.ELLIPSE:
var aX = args[ 0 ], aY = args[ 1 ],
xRadius = args[ 2 ],
yRadius = args[ 3 ],
aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
aClockwise = !!args[ 6 ];
var deltaAngle = aEndAngle - aStartAngle;
var angle;
var tdivisions = divisions * 2;
for ( j = 1; j <= tdivisions; j ++ ) {
t = j / tdivisions;
if ( ! aClockwise ) {
t = 1 - t;
}
angle = aStartAngle + t * deltaAngle;
tx = aX + xRadius * Math.cos( angle );
ty = aY + yRadius * Math.sin( angle );
//console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
points.push( new THREE.Vector2( tx, ty ) );
}
//console.log(points);
break;
} // end switch
}
// Normalize to remove the closing point by default.
var lastPoint = points[ points.length - 1];
var EPSILON = 0.0000000001;
if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
points.splice( points.length - 1, 1);
if ( closedPath ) {
points.push( points[ 0 ] );
}
return points;
};
// Breaks path into shapes
THREE.Path.prototype.toShapes = function() {
var i, il, item, action, args;
var subPaths = [], lastPath = new THREE.Path();
for ( i = 0, il = this.actions.length; i < il; i ++ ) {
item = this.actions[ i ];
args = item.args;
action = item.action;
if ( action == THREE.PathActions.MOVE_TO ) {
if ( lastPath.actions.length != 0 ) {
subPaths.push( lastPath );
lastPath = new THREE.Path();
}
}
lastPath[ action ].apply( lastPath, args );
}
if ( lastPath.actions.length != 0 ) {
subPaths.push( lastPath );
}
// console.log(subPaths);
if ( subPaths.length == 0 ) return [];
var tmpPath, tmpShape, shapes = [];
var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
// console.log("Holes first", holesFirst);
if ( subPaths.length == 1) {
tmpPath = subPaths[0];
tmpShape = new THREE.Shape();
tmpShape.actions = tmpPath.actions;
tmpShape.curves = tmpPath.curves;
shapes.push( tmpShape );
return shapes;
};
if ( holesFirst ) {
tmpShape = new THREE.Shape();
for ( i = 0, il = subPaths.length; i < il; i ++ ) {
tmpPath = subPaths[ i ];
if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
tmpShape.actions = tmpPath.actions;
tmpShape.curves = tmpPath.curves;
shapes.push( tmpShape );
tmpShape = new THREE.Shape();
//console.log('cw', i);
} else {
tmpShape.holes.push( tmpPath );
//console.log('ccw', i);
}
}
} else {
// Shapes first
for ( i = 0, il = subPaths.length; i < il; i ++ ) {
tmpPath = subPaths[ i ];
if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
if ( tmpShape ) shapes.push( tmpShape );
tmpShape = new THREE.Shape();
tmpShape.actions = tmpPath.actions;
tmpShape.curves = tmpPath.curves;
} else {
tmpShape.holes.push( tmpPath );
}
}
shapes.push( tmpShape );
}
//console.log("shape", shapes);
return shapes;
};
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Defines a 2d shape plane using paths.
**/
// STEP 1 Create a path.
// STEP 2 Turn path into shape.
// STEP 3 ExtrudeGeometry takes in Shape/Shapes
// STEP 3a - Extract points from each shape, turn to vertices
// STEP 3b - Triangulate each shape, add faces.
THREE.Shape = function ( ) {
THREE.Path.apply( this, arguments );
this.holes = [];
};
THREE.Shape.prototype = Object.create( THREE.Path.prototype );
// Convenience method to return ExtrudeGeometry
THREE.Shape.prototype.extrude = function ( options ) {
var extruded = new THREE.ExtrudeGeometry( this, options );
return extruded;
};
// Convenience method to return ShapeGeometry
THREE.Shape.prototype.makeGeometry = function ( options ) {
var geometry = new THREE.ShapeGeometry( this, options );
return geometry;
};
// Get points of holes
THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
var i, il = this.holes.length, holesPts = [];
for ( i = 0; i < il; i ++ ) {
holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
}
return holesPts;
};
// Get points of holes (spaced by regular distance)
THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
var i, il = this.holes.length, holesPts = [];
for ( i = 0; i < il; i ++ ) {
holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
}
return holesPts;
};
// Get points of shape and holes (keypoints based on segments parameter)
THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
return {
shape: this.getTransformedPoints( divisions ),
holes: this.getPointsHoles( divisions )
};
};
THREE.Shape.prototype.extractPoints = function ( divisions ) {
if (this.useSpacedPoints) {
return this.extractAllSpacedPoints(divisions);
}
return this.extractAllPoints(divisions);
};
//
// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
//
// return {
//
// shape: this.transform( bend, divisions ),
// holes: this.getPointsHoles( divisions, bend )
//
// };
//
// };
// Get points of shape and holes (spaced by regular distance)
THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
return {
shape: this.getTransformedSpacedPoints( divisions ),
holes: this.getSpacedPointsHoles( divisions )
};
};
/**************************************************************
* Utils
**************************************************************/
THREE.Shape.Utils = {
/*
contour - array of vector2 for contour
holes - array of array of vector2
*/
removeHoles: function ( contour, holes ) {
var shape = contour.concat(); // work on this shape
var allpoints = shape.concat();
/* For each isolated shape, find the closest points and break to the hole to allow triangulation */
var prevShapeVert, nextShapeVert,
prevHoleVert, nextHoleVert,
holeIndex, shapeIndex,
shapeId, shapeGroup,
h, h2,
hole, shortest, d,
p, pts1, pts2,
tmpShape1, tmpShape2,
tmpHole1, tmpHole2,
verts = [];
for ( h = 0; h < holes.length; h ++ ) {
hole = holes[ h ];
/*
shapeholes[ h ].concat(); // preserves original
holes.push( hole );
*/
Array.prototype.push.apply( allpoints, hole );
shortest = Number.POSITIVE_INFINITY;
// Find the shortest pair of pts between shape and hole
// Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
// Using distanceToSquared() intead of distanceTo() should speed a little
// since running square roots operations are reduced.
for ( h2 = 0; h2 < hole.length; h2 ++ ) {
pts1 = hole[ h2 ];
var dist = [];
for ( p = 0; p < shape.length; p++ ) {
pts2 = shape[ p ];
d = pts1.distanceToSquared( pts2 );
dist.push( d );
if ( d < shortest ) {
shortest = d;
holeIndex = h2;
shapeIndex = p;
}
}
}
//console.log("shortest", shortest, dist);
prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
var areaapts = [
hole[ holeIndex ],
shape[ shapeIndex ],
shape[ prevShapeVert ]
];
var areaa = THREE.FontUtils.Triangulate.area( areaapts );
var areabpts = [
hole[ holeIndex ],
hole[ prevHoleVert ],
shape[ shapeIndex ]
];
var areab = THREE.FontUtils.Triangulate.area( areabpts );
var shapeOffset = 1;
var holeOffset = -1;
var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
shapeIndex += shapeOffset;
holeIndex += holeOffset;
if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
shapeIndex %= shape.length;
if ( holeIndex < 0 ) { holeIndex += hole.length; }
holeIndex %= hole.length;
prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
areaapts = [
hole[ holeIndex ],
shape[ shapeIndex ],
shape[ prevShapeVert ]
];
var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
areabpts = [
hole[ holeIndex ],
hole[ prevHoleVert ],
shape[ shapeIndex ]
];
var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
//console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
// In case areas are not correct.
//console.log("USE THIS");
shapeIndex = oldShapeIndex;
holeIndex = oldHoleIndex ;
if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
shapeIndex %= shape.length;
if ( holeIndex < 0 ) { holeIndex += hole.length; }
holeIndex %= hole.length;
prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
} else {
//console.log("USE THAT ")
}
tmpShape1 = shape.slice( 0, shapeIndex );
tmpShape2 = shape.slice( shapeIndex );
tmpHole1 = hole.slice( holeIndex );
tmpHole2 = hole.slice( 0, holeIndex );
// Should check orders here again?
var trianglea = [
hole[ holeIndex ],
shape[ shapeIndex ],
shape[ prevShapeVert ]
];
var triangleb = [
hole[ holeIndex ] ,
hole[ prevHoleVert ],
shape[ shapeIndex ]
];
verts.push( trianglea );
verts.push( triangleb );
shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
}
return {
shape:shape, /* shape with no holes */
isolatedPts: verts, /* isolated faces */
allpoints: allpoints
}
},
triangulateShape: function ( contour, holes ) {
var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
var shape = shapeWithoutHoles.shape,
allpoints = shapeWithoutHoles.allpoints,
isolatedPts = shapeWithoutHoles.isolatedPts;
var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
// To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
//console.log( "triangles",triangles, triangles.length );
//console.log( "allpoints",allpoints, allpoints.length );
var i, il, f, face,
key, index,
allPointsMap = {},
isolatedPointsMap = {};
// prepare all points map
for ( i = 0, il = allpoints.length; i < il; i ++ ) {
key = allpoints[ i ].x + ":" + allpoints[ i ].y;
if ( allPointsMap[ key ] !== undefined ) {
console.log( "Duplicate point", key );
}
allPointsMap[ key ] = i;
}
// check all face vertices against all points map
for ( i = 0, il = triangles.length; i < il; i ++ ) {
face = triangles[ i ];
for ( f = 0; f < 3; f ++ ) {
key = face[ f ].x + ":" + face[ f ].y;
index = allPointsMap[ key ];
if ( index !== undefined ) {
face[ f ] = index;
}
}
}
// check isolated points vertices against all points map
for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
face = isolatedPts[ i ];
for ( f = 0; f < 3; f ++ ) {
key = face[ f ].x + ":" + face[ f ].y;
index = allPointsMap[ key ];
if ( index !== undefined ) {
face[ f ] = index;
}
}
}
return triangles.concat( isolatedPts );
}, // end triangulate shapes
/*
triangulate2 : function( pts, holes ) {
// For use with Poly2Tri.js
var allpts = pts.concat();
var shape = [];
for (var p in pts) {
shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
}
var swctx = new js.poly2tri.SweepContext(shape);
for (var h in holes) {
var aHole = holes[h];
var newHole = []
for (i in aHole) {
newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
allpts.push(aHole[i]);
}
swctx.AddHole(newHole);
}
var find;
var findIndexForPt = function (pt) {
find = new THREE.Vector2(pt.x, pt.y);
var p;
for (p=0, pl = allpts.length; p<pl; p++) {
if (allpts[p].equals(find)) return p;
}
return -1;
};
// triangulate
js.poly2tri.sweep.Triangulate(swctx);
var triangles = swctx.GetTriangles();
var tr ;
var facesPts = [];
for (var t in triangles) {
tr = triangles[t];
facesPts.push([
findIndexForPt(tr.GetPoint(0)),
findIndexForPt(tr.GetPoint(1)),
findIndexForPt(tr.GetPoint(2))
]);
}
// console.log(facesPts);
// console.log("triangles", triangles.length, triangles);
// Returns array of faces with 3 element each
return facesPts;
},
*/
isClockWise: function ( pts ) {
return THREE.FontUtils.Triangulate.area( pts ) < 0;
},
// Bezier Curves formulas obtained from
// http://en.wikipedia.org/wiki/B%C3%A9zier_curve
// Quad Bezier Functions
b2p0: function ( t, p ) {
var k = 1 - t;
return k * k * p;
},
b2p1: function ( t, p ) {
return 2 * ( 1 - t ) * t * p;
},
b2p2: function ( t, p ) {
return t * t * p;
},
b2: function ( t, p0, p1, p2 ) {
return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
},
// Cubic Bezier Functions
b3p0: function ( t, p ) {
var k = 1 - t;
return k * k * k * p;
},
b3p1: function ( t, p ) {
var k = 1 - t;
return 3 * k * k * t * p;
},
b3p2: function ( t, p ) {
var k = 1 - t;
return 3 * k * t * t * p;
},
b3p3: function ( t, p ) {
return t * t * t * p;
},
b3: function ( t, p0, p1, p2, p3 ) {
return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
}
};
/**
* @author mikael emtinger / http://gomo.se/
*/
THREE.AnimationHandler = (function() {
var playing = [];
var library = {};
var that = {};
//--- update ---
that.update = function( deltaTimeMS ) {
for( var i = 0; i < playing.length; i ++ )
playing[ i ].update( deltaTimeMS );
};
//--- add ---
that.addToUpdate = function( animation ) {
if ( playing.indexOf( animation ) === -1 )
playing.push( animation );
};
//--- remove ---
that.removeFromUpdate = function( animation ) {
var index = playing.indexOf( animation );
if( index !== -1 )
playing.splice( index, 1 );
};
//--- add ---
that.add = function( data ) {
if ( library[ data.name ] !== undefined )
console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
library[ data.name ] = data;
initData( data );
};
//--- get ---
that.get = function( name ) {
if ( typeof name === "string" ) {
if ( library[ name ] ) {
return library[ name ];
} else {
console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
return null;
}
} else {
// todo: add simple tween library
}
};
//--- parse ---
that.parse = function( root ) {
// setup hierarchy
var hierarchy = [];
if ( root instanceof THREE.SkinnedMesh ) {
for( var b = 0; b < root.bones.length; b++ ) {
hierarchy.push( root.bones[ b ] );
}
} else {
parseRecurseHierarchy( root, hierarchy );
}
return hierarchy;
};
var parseRecurseHierarchy = function( root, hierarchy ) {
hierarchy.push( root );
for( var c = 0; c < root.children.length; c++ )
parseRecurseHierarchy( root.children[ c ], hierarchy );
}
//--- init data ---
var initData = function( data ) {
if( data.initialized === true )
return;
// loop through all keys
for( var h = 0; h < data.hierarchy.length; h ++ ) {
for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
// remove minus times
if( data.hierarchy[ h ].keys[ k ].time < 0 )
data.hierarchy[ h ].keys[ k ].time = 0;
// create quaternions
if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
!( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
var quat = data.hierarchy[ h ].keys[ k ].rot;
data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
}
}
// prepare morph target keys
if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
// get all used
var usedMorphTargets = {};
for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
usedMorphTargets[ morphTargetName ] = -1;
}
}
data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
// set all used on all frames
for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
var influences = {};
for ( var morphTargetName in usedMorphTargets ) {
for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
break;
}
}
if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
influences[ morphTargetName ] = 0;
}
}
data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
}
}
// remove all keys that are on the same time
for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
data.hierarchy[ h ].keys.splice( k, 1 );
k --;
}
}
// set index
for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
data.hierarchy[ h ].keys[ k ].index = k;
}
}
// JIT
var lengthInFrames = parseInt( data.length * data.fps, 10 );
data.JIT = {};
data.JIT.hierarchy = [];
for( var h = 0; h < data.hierarchy.length; h ++ )
data.JIT.hierarchy.push( new Array( lengthInFrames ) );
// done
data.initialized = true;
};
// interpolation types
that.LINEAR = 0;
that.CATMULLROM = 1;
that.CATMULLROM_FORWARD = 2;
return that;
}());
/**
* @author mikael emtinger / http://gomo.se/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Animation = function ( root, name, interpolationType ) {
this.root = root;
this.data = THREE.AnimationHandler.get( name );
this.hierarchy = THREE.AnimationHandler.parse( root );
this.currentTime = 0;
this.timeScale = 1;
this.isPlaying = false;
this.isPaused = true;
this.loop = true;
this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
this.points = [];
this.target = new THREE.Vector3();
};
THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
if ( this.isPlaying === false ) {
this.isPlaying = true;
this.loop = loop !== undefined ? loop : true;
this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
// reset key cache
var h, hl = this.hierarchy.length,
object;
for ( h = 0; h < hl; h ++ ) {
object = this.hierarchy[ h ];
if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
object.useQuaternion = true;
}
object.matrixAutoUpdate = true;
if ( object.animationCache === undefined ) {
object.animationCache = {};
object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
}
var prevKey = object.animationCache.prevKey;
var nextKey = object.animationCache.nextKey;
prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
}
this.update( 0 );
}
this.isPaused = false;
THREE.AnimationHandler.addToUpdate( this );
};
THREE.Animation.prototype.pause = function() {
if ( this.isPaused === true ) {
THREE.AnimationHandler.addToUpdate( this );
} else {
THREE.AnimationHandler.removeFromUpdate( this );
}
this.isPaused = !this.isPaused;
};
THREE.Animation.prototype.stop = function() {
this.isPlaying = false;
this.isPaused = false;
THREE.AnimationHandler.removeFromUpdate( this );
};
THREE.Animation.prototype.update = function ( deltaTimeMS ) {
// early out
if ( this.isPlaying === false ) return;
// vars
var types = [ "pos", "rot", "scl" ];
var type;
var scale;
var vector;
var prevXYZ, nextXYZ;
var prevKey, nextKey;
var object;
var animationCache;
var frame;
var JIThierarchy = this.data.JIT.hierarchy;
var currentTime, unloopedCurrentTime;
var currentPoint, forwardPoint, angle;
this.currentTime += deltaTimeMS * this.timeScale;
unloopedCurrentTime = this.currentTime;
currentTime = this.currentTime = this.currentTime % this.data.length;
frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
object = this.hierarchy[ h ];
animationCache = object.animationCache;
// loop through pos/rot/scl
for ( var t = 0; t < 3; t ++ ) {
// get keys
type = types[ t ];
prevKey = animationCache.prevKey[ type ];
nextKey = animationCache.nextKey[ type ];
// switch keys?
if ( nextKey.time <= unloopedCurrentTime ) {
// did we loop?
if ( currentTime < unloopedCurrentTime ) {
if ( this.loop ) {
prevKey = this.data.hierarchy[ h ].keys[ 0 ];
nextKey = this.getNextKeyWith( type, h, 1 );
while( nextKey.time < currentTime ) {
prevKey = nextKey;
nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
}
} else {
this.stop();
return;
}
} else {
do {
prevKey = nextKey;
nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
} while( nextKey.time < currentTime )
}
animationCache.prevKey[ type ] = prevKey;
animationCache.nextKey[ type ] = nextKey;
}
object.matrixAutoUpdate = true;
object.matrixWorldNeedsUpdate = true;
scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
prevXYZ = prevKey[ type ];
nextXYZ = nextKey[ type ];
// check scale error
if ( scale < 0 || scale > 1 ) {
console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
scale = scale < 0 ? 0 : 1;
}
// interpolate
if ( type === "pos" ) {
vector = object.position;
if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
} else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
this.points[ 1 ] = prevXYZ;
this.points[ 2 ] = nextXYZ;
this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
scale = scale * 0.33 + 0.33;
currentPoint = this.interpolateCatmullRom( this.points, scale );
vector.x = currentPoint[ 0 ];
vector.y = currentPoint[ 1 ];
vector.z = currentPoint[ 2 ];
if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
this.target.subSelf( vector );
this.target.y = 0;
this.target.normalize();
angle = Math.atan2( this.target.x, this.target.z );
object.rotation.set( 0, angle, 0 );
}
}
} else if ( type === "rot" ) {
THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
} else if ( type === "scl" ) {
vector = object.scale;
vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
}
}
}
};
// Catmull-Rom spline
THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
var c = [], v3 = [],
point, intPoint, weight, w2, w3,
pa, pb, pc, pd;
point = ( points.length - 1 ) * scale;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
pa = points[ c[ 0 ] ];
pb = points[ c[ 1 ] ];
pc = points[ c[ 2 ] ];
pd = points[ c[ 3 ] ];
w2 = weight * weight;
w3 = weight * w2;
v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
return v3;
};
THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
var v0 = ( p2 - p0 ) * 0.5,
v1 = ( p3 - p1 ) * 0.5;
return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
};
// Get next key with
THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
key = key < keys.length - 1 ? key : keys.length - 1;
} else {
key = key % keys.length;
}
for ( ; key < keys.length; key++ ) {
if ( keys[ key ][ type ] !== undefined ) {
return keys[ key ];
}
}
return this.data.hierarchy[ h ].keys[ 0 ];
};
// Get previous key with
THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
key = key > 0 ? key : 0;
} else {
key = key >= 0 ? key : key + keys.length;
}
for ( ; key >= 0; key -- ) {
if ( keys[ key ][ type ] !== undefined ) {
return keys[ key ];
}
}
return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
};
/**
* @author mikael emtinger / http://gomo.se/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author khang duong
* @author erik kitson
*/
THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
this.root = root;
this.data = THREE.AnimationHandler.get( data );
this.hierarchy = THREE.AnimationHandler.parse( root );
this.currentTime = 0;
this.timeScale = 0.001;
this.isPlaying = false;
this.isPaused = true;
this.loop = true;
this.JITCompile = JITCompile !== undefined ? JITCompile : true;
// initialize to first keyframes
for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
var keys = this.data.hierarchy[h].keys,
sids = this.data.hierarchy[h].sids,
obj = this.hierarchy[h];
if ( keys.length && sids ) {
for ( var s = 0; s < sids.length; s++ ) {
var sid = sids[ s ],
next = this.getNextKeyWith( sid, h, 0 );
if ( next ) {
next.apply( sid );
}
}
obj.matrixAutoUpdate = false;
this.data.hierarchy[h].node.updateMatrix();
obj.matrixWorldNeedsUpdate = true;
}
}
};
// Play
THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
if( !this.isPlaying ) {
this.isPlaying = true;
this.loop = loop !== undefined ? loop : true;
this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
this.startTimeMs = startTimeMS;
this.startTime = 10000000;
this.endTime = -this.startTime;
// reset key cache
var h, hl = this.hierarchy.length,
object,
node;
for ( h = 0; h < hl; h++ ) {
object = this.hierarchy[ h ];
node = this.data.hierarchy[ h ];
object.useQuaternion = true;
if ( node.animationCache === undefined ) {
node.animationCache = {};
node.animationCache.prevKey = null;
node.animationCache.nextKey = null;
node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
}
var keys = this.data.hierarchy[h].keys;
if (keys.length) {
node.animationCache.prevKey = keys[ 0 ];
node.animationCache.nextKey = keys[ 1 ];
this.startTime = Math.min( keys[0].time, this.startTime );
this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
}
}
this.update( 0 );
}
this.isPaused = false;
THREE.AnimationHandler.addToUpdate( this );
};
// Pause
THREE.KeyFrameAnimation.prototype.pause = function() {
if( this.isPaused ) {
THREE.AnimationHandler.addToUpdate( this );
} else {
THREE.AnimationHandler.removeFromUpdate( this );
}
this.isPaused = !this.isPaused;
};
// Stop
THREE.KeyFrameAnimation.prototype.stop = function() {
this.isPlaying = false;
this.isPaused = false;
THREE.AnimationHandler.removeFromUpdate( this );
// reset JIT matrix and remove cache
for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
var obj = this.hierarchy[ h ];
var node = this.data.hierarchy[ h ];
if ( node.animationCache !== undefined ) {
var original = node.animationCache.originalMatrix;
if( obj instanceof THREE.Bone ) {
original.copy( obj.skinMatrix );
obj.skinMatrix = original;
} else {
original.copy( obj.matrix );
obj.matrix = original;
}
delete node.animationCache;
}
}
};
// Update
THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
// early out
if( !this.isPlaying ) return;
// vars
var prevKey, nextKey;
var object;
var node;
var frame;
var JIThierarchy = this.data.JIT.hierarchy;
var currentTime, unloopedCurrentTime;
var looped;
// update
this.currentTime += deltaTimeMS * this.timeScale;
unloopedCurrentTime = this.currentTime;
currentTime = this.currentTime = this.currentTime % this.data.length;
// if looped around, the current time should be based on the startTime
if ( currentTime < this.startTimeMs ) {
currentTime = this.currentTime = this.startTimeMs + currentTime;
}
frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
looped = currentTime < unloopedCurrentTime;
if ( looped && !this.loop ) {
// Set the animation to the last keyframes and stop
for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
var keys = this.data.hierarchy[h].keys,
sids = this.data.hierarchy[h].sids,
end = keys.length-1,
obj = this.hierarchy[h];
if ( keys.length ) {
for ( var s = 0; s < sids.length; s++ ) {
var sid = sids[ s ],
prev = this.getPrevKeyWith( sid, h, end );
if ( prev ) {
prev.apply( sid );
}
}
this.data.hierarchy[h].node.updateMatrix();
obj.matrixWorldNeedsUpdate = true;
}
}
this.stop();
return;
}
// check pre-infinity
if ( currentTime < this.startTime ) {
return;
}
// update
for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
object = this.hierarchy[ h ];
node = this.data.hierarchy[ h ];
var keys = node.keys,
animationCache = node.animationCache;
// use JIT?
if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
if( object instanceof THREE.Bone ) {
object.skinMatrix = JIThierarchy[ h ][ frame ];
object.matrixWorldNeedsUpdate = false;
} else {
object.matrix = JIThierarchy[ h ][ frame ];
object.matrixWorldNeedsUpdate = true;
}
// use interpolation
} else if ( keys.length ) {
// make sure so original matrix and not JIT matrix is set
if ( this.JITCompile && animationCache ) {
if( object instanceof THREE.Bone ) {
object.skinMatrix = animationCache.originalMatrix;
} else {
object.matrix = animationCache.originalMatrix;
}
}
prevKey = animationCache.prevKey;
nextKey = animationCache.nextKey;
if ( prevKey && nextKey ) {
// switch keys?
if ( nextKey.time <= unloopedCurrentTime ) {
// did we loop?
if ( looped && this.loop ) {
prevKey = keys[ 0 ];
nextKey = keys[ 1 ];
while ( nextKey.time < currentTime ) {
prevKey = nextKey;
nextKey = keys[ prevKey.index + 1 ];
}
} else if ( !looped ) {
var lastIndex = keys.length - 1;
while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
prevKey = nextKey;
nextKey = keys[ prevKey.index + 1 ];
}
}
animationCache.prevKey = prevKey;
animationCache.nextKey = nextKey;
}
if(nextKey.time >= currentTime)
prevKey.interpolate( nextKey, currentTime );
else
prevKey.interpolate( nextKey, nextKey.time);
}
this.data.hierarchy[h].node.updateMatrix();
object.matrixWorldNeedsUpdate = true;
}
}
// update JIT?
if ( this.JITCompile ) {
if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
this.hierarchy[ 0 ].updateMatrixWorld( true );
for ( var h = 0; h < this.hierarchy.length; h++ ) {
if( this.hierarchy[ h ] instanceof THREE.Bone ) {
JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
} else {
JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
}
}
}
}
};
// Get next key with
THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
key = key % keys.length;
for ( ; key < keys.length; key++ ) {
if ( keys[ key ].hasTarget( sid ) ) {
return keys[ key ];
}
}
return keys[ 0 ];
};
// Get previous key with
THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
key = key >= 0 ? key : key + keys.length;
for ( ; key >= 0; key-- ) {
if ( keys[ key ].hasTarget( sid ) ) {
return keys[ key ];
}
}
return keys[ keys.length - 1 ];
};
/**
* Camera for rendering cube maps
* - renders scene into axis-aligned cube
*
* @author alteredq / http://alteredqualia.com/
*/
THREE.CubeCamera = function ( near, far, cubeResolution ) {
THREE.Object3D.call( this );
var fov = 90, aspect = 1;
var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraPX.up.set( 0, -1, 0 );
cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
this.add( cameraPX );
var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraNX.up.set( 0, -1, 0 );
cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
this.add( cameraNX );
var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraPY.up.set( 0, 0, 1 );
cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
this.add( cameraPY );
var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraNY.up.set( 0, 0, -1 );
cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
this.add( cameraNY );
var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraPZ.up.set( 0, -1, 0 );
cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
this.add( cameraPZ );
var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraNZ.up.set( 0, -1, 0 );
cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
this.add( cameraNZ );
this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
this.updateCubeMap = function ( renderer, scene ) {
var renderTarget = this.renderTarget;
var generateMipmaps = renderTarget.generateMipmaps;
renderTarget.generateMipmaps = false;
renderTarget.activeCubeFace = 0;
renderer.render( scene, cameraPX, renderTarget );
renderTarget.activeCubeFace = 1;
renderer.render( scene, cameraNX, renderTarget );
renderTarget.activeCubeFace = 2;
renderer.render( scene, cameraPY, renderTarget );
renderTarget.activeCubeFace = 3;
renderer.render( scene, cameraNY, renderTarget );
renderTarget.activeCubeFace = 4;
renderer.render( scene, cameraPZ, renderTarget );
renderTarget.generateMipmaps = generateMipmaps;
renderTarget.activeCubeFace = 5;
renderer.render( scene, cameraNZ, renderTarget );
};
};
THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
/*
* @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
*
* A general perpose camera, for setting FOV, Lens Focal Length,
* and switching between perspective and orthographic views easily.
* Use this only if you do not wish to manage
* both a Orthographic and Perspective Camera
*
*/
THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
THREE.Camera.call( this );
this.fov = fov;
this.left = -width / 2;
this.right = width / 2
this.top = height / 2;
this.bottom = -height / 2;
// We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
this.zoom = 1;
this.toPerspective();
var aspect = width/height;
};
THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
THREE.CombinedCamera.prototype.toPerspective = function () {
// Switches to the Perspective Camera
this.near = this.cameraP.near;
this.far = this.cameraP.far;
this.cameraP.fov = this.fov / this.zoom ;
this.cameraP.updateProjectionMatrix();
this.projectionMatrix = this.cameraP.projectionMatrix;
this.inPerspectiveMode = true;
this.inOrthographicMode = false;
};
THREE.CombinedCamera.prototype.toOrthographic = function () {
// Switches to the Orthographic camera estimating viewport from Perspective
var fov = this.fov;
var aspect = this.cameraP.aspect;
var near = this.cameraP.near;
var far = this.cameraP.far;
// The size that we set is the mid plane of the viewing frustum
var hyperfocus = ( near + far ) / 2;
var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
var planeHeight = 2 * halfHeight;
var planeWidth = planeHeight * aspect;
var halfWidth = planeWidth / 2;
halfHeight /= this.zoom;
halfWidth /= this.zoom;
this.cameraO.left = -halfWidth;
this.cameraO.right = halfWidth;
this.cameraO.top = halfHeight;
this.cameraO.bottom = -halfHeight;
// this.cameraO.left = -farHalfWidth;
// this.cameraO.right = farHalfWidth;
// this.cameraO.top = farHalfHeight;
// this.cameraO.bottom = -farHalfHeight;
// this.cameraO.left = this.left / this.zoom;
// this.cameraO.right = this.right / this.zoom;
// this.cameraO.top = this.top / this.zoom;
// this.cameraO.bottom = this.bottom / this.zoom;
this.cameraO.updateProjectionMatrix();
this.near = this.cameraO.near;
this.far = this.cameraO.far;
this.projectionMatrix = this.cameraO.projectionMatrix;
this.inPerspectiveMode = false;
this.inOrthographicMode = true;
};
THREE.CombinedCamera.prototype.setSize = function( width, height ) {
this.cameraP.aspect = width / height;
this.left = -width / 2;
this.right = width / 2
this.top = height / 2;
this.bottom = -height / 2;
};
THREE.CombinedCamera.prototype.setFov = function( fov ) {
this.fov = fov;
if ( this.inPerspectiveMode ) {
this.toPerspective();
} else {
this.toOrthographic();
}
};
// For mantaining similar API with PerspectiveCamera
THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
if ( this.inPerspectiveMode ) {
this.toPerspective();
} else {
this.toPerspective();
this.toOrthographic();
}
};
/*
* Uses Focal Length (in mm) to estimate and set FOV
* 35mm (fullframe) camera is used if frame size is not specified;
* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
*/
THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
if ( frameHeight === undefined ) frameHeight = 24;
var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
this.setFov( fov );
return fov;
};
THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
this.zoom = zoom;
if ( this.inPerspectiveMode ) {
this.toPerspective();
} else {
this.toOrthographic();
}
};
THREE.CombinedCamera.prototype.toFrontView = function() {
this.rotation.x = 0;
this.rotation.y = 0;
this.rotation.z = 0;
// should we be modifing the matrix instead?
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toBackView = function() {
this.rotation.x = 0;
this.rotation.y = Math.PI;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toLeftView = function() {
this.rotation.x = 0;
this.rotation.y = - Math.PI / 2;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toRightView = function() {
this.rotation.x = 0;
this.rotation.y = Math.PI / 2;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toTopView = function() {
this.rotation.x = - Math.PI / 2;
this.rotation.y = 0;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toBottomView = function() {
this.rotation.x = Math.PI / 2;
this.rotation.y = 0;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
/**
* @author hughes
*/
THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
THREE.Geometry.call( this );
radius = radius || 50;
thetaStart = thetaStart !== undefined ? thetaStart : 0;
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
segments = segments !== undefined ? Math.max( 3, segments ) : 8;
var i, uvs = [],
center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
this.vertices.push(center);
uvs.push( centerUV );
for ( i = 0; i <= segments; i ++ ) {
var vertex = new THREE.Vector3();
vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
this.vertices.push( vertex );
uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
}
var n = new THREE.Vector3( 0, 0, -1 );
for ( i = 1; i <= segments; i ++ ) {
var v1 = i;
var v2 = i + 1 ;
var v3 = 0;
this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
}
this.computeCentroids();
this.computeFaceNormals();
this.boundingSphere = { radius: radius };
};
THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author mrdoob / http://mrdoob.com/
* based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
*/
THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
THREE.Geometry.call( this );
var scope = this,
width_half = width / 2,
height_half = height / 2,
depth_half = depth / 2;
var mpx, mpy, mpz, mnx, mny, mnz;
if ( materials !== undefined ) {
if ( materials instanceof Array ) {
this.materials = materials;
} else {
this.materials = [];
for ( var i = 0; i < 6; i ++ ) {
this.materials.push( materials );
}
}
mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
} else {
this.materials = [];
}
this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
if ( sides != undefined ) {
for ( var s in sides ) {
if ( this.sides[ s ] !== undefined ) {
this.sides[ s ] = sides[ s ];
}
}
}
this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
var w, ix, iy,
gridX = segmentsWidth || 1,
gridY = segmentsHeight || 1,
width_half = width / 2,
height_half = height / 2,
offset = scope.vertices.length;
if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
w = 'z';
} else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
w = 'y';
gridY = segmentsDepth || 1;
} else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
w = 'x';
gridX = segmentsDepth || 1;
}
var gridX1 = gridX + 1,
gridY1 = gridY + 1,
segment_width = width / gridX,
segment_height = height / gridY,
normal = new THREE.Vector3();
normal[ w ] = depth > 0 ? 1 : - 1;
for ( iy = 0; iy < gridY1; iy ++ ) {
for ( ix = 0; ix < gridX1; ix ++ ) {
var vector = new THREE.Vector3();
vector[ u ] = ( ix * segment_width - width_half ) * udir;
vector[ v ] = ( iy * segment_height - height_half ) * vdir;
vector[ w ] = depth;
scope.vertices.push( vector );
}
}
for ( iy = 0; iy < gridY; iy++ ) {
for ( ix = 0; ix < gridX; ix++ ) {
var a = ix + gridX1 * iy;
var b = ix + gridX1 * ( iy + 1 );
var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
var d = ( ix + 1 ) + gridX1 * iy;
var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
face.normal.copy( normal );
face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
face.materialIndex = material;
scope.faces.push( face );
scope.faceVertexUvs[ 0 ].push( [
new THREE.UV( ix / gridX, 1 - iy / gridY ),
new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
] );
}
}
}
this.computeCentroids();
this.mergeVertices();
};
THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
THREE.Geometry.call( this );
radiusTop = radiusTop !== undefined ? radiusTop : 20;
radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
height = height !== undefined ? height : 100;
var heightHalf = height / 2;
var segmentsX = radiusSegments || 8;
var segmentsY = heightSegments || 1;
var x, y, vertices = [], uvs = [];
for ( y = 0; y <= segmentsY; y ++ ) {
var verticesRow = [];
var uvsRow = [];
var v = y / segmentsY;
var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
for ( x = 0; x <= segmentsX; x ++ ) {
var u = x / segmentsX;
var vertex = new THREE.Vector3();
vertex.x = radius * Math.sin( u * Math.PI * 2 );
vertex.y = - v * height + heightHalf;
vertex.z = radius * Math.cos( u * Math.PI * 2 );
this.vertices.push( vertex );
verticesRow.push( this.vertices.length - 1 );
uvsRow.push( new THREE.UV( u, 1 - v ) );
}
vertices.push( verticesRow );
uvs.push( uvsRow );
}
var tanTheta = ( radiusBottom - radiusTop ) / height;
var na, nb;
for ( x = 0; x < segmentsX; x ++ ) {
if ( radiusTop !== 0 ) {
na = this.vertices[ vertices[ 0 ][ x ] ].clone();
nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
} else {
na = this.vertices[ vertices[ 1 ][ x ] ].clone();
nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
}
na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
for ( y = 0; y < segmentsY; y ++ ) {
var v1 = vertices[ y ][ x ];
var v2 = vertices[ y + 1 ][ x ];
var v3 = vertices[ y + 1 ][ x + 1 ];
var v4 = vertices[ y ][ x + 1 ];
var n1 = na.clone();
var n2 = na.clone();
var n3 = nb.clone();
var n4 = nb.clone();
var uv1 = uvs[ y ][ x ].clone();
var uv2 = uvs[ y + 1 ][ x ].clone();
var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
var uv4 = uvs[ y ][ x + 1 ].clone();
this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
}
}
// top cap
if ( !openEnded && radiusTop > 0 ) {
this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
for ( x = 0; x < segmentsX; x ++ ) {
var v1 = vertices[ 0 ][ x ];
var v2 = vertices[ 0 ][ x + 1 ];
var v3 = this.vertices.length - 1;
var n1 = new THREE.Vector3( 0, 1, 0 );
var n2 = new THREE.Vector3( 0, 1, 0 );
var n3 = new THREE.Vector3( 0, 1, 0 );
var uv1 = uvs[ 0 ][ x ].clone();
var uv2 = uvs[ 0 ][ x + 1 ].clone();
var uv3 = new THREE.UV( uv2.u, 0 );
this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
}
}
// bottom cap
if ( !openEnded && radiusBottom > 0 ) {
this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
for ( x = 0; x < segmentsX; x ++ ) {
var v1 = vertices[ y ][ x + 1 ];
var v2 = vertices[ y ][ x ];
var v3 = this.vertices.length - 1;
var n1 = new THREE.Vector3( 0, - 1, 0 );
var n2 = new THREE.Vector3( 0, - 1, 0 );
var n3 = new THREE.Vector3( 0, - 1, 0 );
var uv1 = uvs[ y ][ x + 1 ].clone();
var uv2 = uvs[ y ][ x ].clone();
var uv3 = new THREE.UV( uv2.u, 1 );
this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
}
THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*
* Creates extruded geometry from a path shape.
*
* parameters = {
*
* size: <float>, // size of the text
* height: <float>, // thickness to extrude text
* curveSegments: <int>, // number of points on the curves
* steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
* amount: <int>, // Amount
*
* bevelEnabled: <bool>, // turn on bevel
* bevelThickness: <float>, // how deep into text bevel goes
* bevelSize: <float>, // how far from text outline is bevel
* bevelSegments: <int>, // number of bevel layers
*
* extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
* frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
*
* material: <int> // material index for front and back faces
* extrudeMaterial: <int> // material index for extrusion and beveled faces
* uvGenerator: <Object> // object that provides UV generator functions
*
* }
**/
THREE.ExtrudeGeometry = function ( shapes, options ) {
if ( typeof( shapes ) === "undefined" ) {
shapes = [];
return;
}
THREE.Geometry.call( this );
shapes = shapes instanceof Array ? shapes : [ shapes ];
this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
this.addShapeList( shapes, options );
this.computeCentroids();
this.computeFaceNormals();
// can't really use automatic vertex normals
// as then front and back sides get smoothed too
// should do separate smoothing just for sides
//this.computeVertexNormals();
//console.log( "took", ( Date.now() - startTime ) );
};
THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
var sl = shapes.length;
for ( var s = 0; s < sl; s ++ ) {
var shape = shapes[ s ];
this.addShape( shape, options );
}
};
THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
var amount = options.amount !== undefined ? options.amount : 100;
var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
var steps = options.steps !== undefined ? options.steps : 1;
var extrudePath = options.extrudePath;
var extrudePts, extrudeByPath = false;
var material = options.material;
var extrudeMaterial = options.extrudeMaterial;
// Use default WorldUVGenerator if no UV generators are specified.
var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
var shapebb = this.shapebb;
//shapebb = shape.getBoundingBox();
var splineTube, binormal, normal, position2;
if ( extrudePath ) {
extrudePts = extrudePath.getSpacedPoints( steps );
extrudeByPath = true;
bevelEnabled = false; // bevels not supported for path extrusion
// SETUP TNB variables
// Reuse TNB from TubeGeomtry for now.
// TODO1 - have a .isClosed in spline?
splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
// console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
binormal = new THREE.Vector3();
normal = new THREE.Vector3();
position2 = new THREE.Vector3();
}
// Safeguards if bevels are not enabled
if ( ! bevelEnabled ) {
bevelSegments = 0;
bevelThickness = 0;
bevelSize = 0;
}
// Variables initalization
var ahole, h, hl; // looping of holes
var scope = this;
var bevelPoints = [];
var shapesOffset = this.vertices.length;
var shapePoints = shape.extractPoints();
var vertices = shapePoints.shape;
var holes = shapePoints.holes;
var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
if ( reverse ) {
vertices = vertices.reverse();
// Maybe we should also check if holes are in the opposite direction, just to be safe ...
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
holes[ h ] = ahole.reverse();
}
}
reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
}
var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
/* Vertices */
var contour = vertices; // vertices has all points but contour has only points of circumference
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
vertices = vertices.concat( ahole );
}
function scalePt2 ( pt, vec, size ) {
if ( !vec ) console.log( "die" );
return vec.clone().multiplyScalar( size ).addSelf( pt );
}
var b, bs, t, z,
vert, vlen = vertices.length,
face, flen = faces.length,
cont, clen = contour.length;
// Find directions for point movement
var RAD_TO_DEGREES = 180 / Math.PI;
function getBevelVec( pt_i, pt_j, pt_k ) {
// Algorithm 2
return getBevelVec2( pt_i, pt_j, pt_k );
}
function getBevelVec1( pt_i, pt_j, pt_k ) {
var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
if ( anglea > angleb ) {
angleb += Math.PI * 2;
}
var anglec = ( anglea + angleb ) / 2;
//console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
var x = - Math.cos( anglec );
var y = - Math.sin( anglec );
var vec = new THREE.Vector2( x, y ); //.normalize();
return vec;
}
function getBevelVec2( pt_i, pt_j, pt_k ) {
var a = THREE.ExtrudeGeometry.__v1,
b = THREE.ExtrudeGeometry.__v2,
v_hat = THREE.ExtrudeGeometry.__v3,
w_hat = THREE.ExtrudeGeometry.__v4,
p = THREE.ExtrudeGeometry.__v5,
q = THREE.ExtrudeGeometry.__v6,
v, w,
v_dot_w_hat, q_sub_p_dot_w_hat,
s, intersection;
// good reading for line-line intersection
// http://sputsoft.com/blog/2010/03/line-line-intersection.html
// define a as vector j->i
// define b as vectot k->i
a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
// get unit vectors
v = a.normalize();
w = b.normalize();
// normals from pt i
v_hat.set( -v.y, v.x );
w_hat.set( w.y, -w.x );
// pts from i
p.copy( pt_i ).addSelf( v_hat );
q.copy( pt_i ).addSelf( w_hat );
if ( p.equals( q ) ) {
//console.log("Warning: lines are straight");
return w_hat.clone();
}
// Points from j, k. helps prevents points cross overover most of the time
p.copy( pt_j ).addSelf( v_hat );
q.copy( pt_k ).addSelf( w_hat );
v_dot_w_hat = v.dot( w_hat );
q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
// We should not reach these conditions
if ( v_dot_w_hat === 0 ) {
console.log( "Either infinite or no solutions!" );
if ( q_sub_p_dot_w_hat === 0 ) {
console.log( "Its finite solutions." );
} else {
console.log( "Too bad, no solutions." );
}
}
s = q_sub_p_dot_w_hat / v_dot_w_hat;
if ( s < 0 ) {
// in case of emergecy, revert to algorithm 1.
return getBevelVec1( pt_i, pt_j, pt_k );
}
intersection = v.multiplyScalar( s ).addSelf( p );
return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
}
var contourMovements = [];
for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
if ( j === il ) j = 0;
if ( k === il ) k = 0;
// (j)---(i)---(k)
// console.log('i,j,k', i, j , k)
var pt_i = contour[ i ];
var pt_j = contour[ j ];
var pt_k = contour[ k ];
contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
}
var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
oneHoleMovements = [];
for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
if ( j === il ) j = 0;
if ( k === il ) k = 0;
// (j)---(i)---(k)
oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
}
holesMovements.push( oneHoleMovements );
verticesMovements = verticesMovements.concat( oneHoleMovements );
}
// Loop bevelSegments, 1 for the front, 1 for the back
for ( b = 0; b < bevelSegments; b ++ ) {
//for ( b = bevelSegments; b > 0; b -- ) {
t = b / bevelSegments;
z = bevelThickness * ( 1 - t );
//z = bevelThickness * t;
bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
//bs = bevelSize * t ; // linear
// contract shape
for ( i = 0, il = contour.length; i < il; i ++ ) {
vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
//vert = scalePt( contour[ i ], contourCentroid, bs, false );
v( vert.x, vert.y, - z );
}
// expand holes
for ( h = 0, hl = holes.length; h < hl; h++ ) {
ahole = holes[ h ];
oneHoleMovements = holesMovements[ h ];
for ( i = 0, il = ahole.length; i < il; i++ ) {
vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
//vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
v( vert.x, vert.y, -z );
}
}
}
bs = bevelSize;
// Back facing vertices
for ( i = 0; i < vlen; i ++ ) {
vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
if ( !extrudeByPath ) {
v( vert.x, vert.y, 0 );
} else {
// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
v( position2.x, position2.y, position2.z );
}
}
// Add stepped vertices...
// Including front facing vertices
var s;
for ( s = 1; s <= steps; s ++ ) {
for ( i = 0; i < vlen; i ++ ) {
vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
if ( !extrudeByPath ) {
v( vert.x, vert.y, amount / steps * s );
} else {
// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
v( position2.x, position2.y, position2.z );
}
}
}
// Add bevel segments planes
//for ( b = 1; b <= bevelSegments; b ++ ) {
for ( b = bevelSegments - 1; b >= 0; b -- ) {
t = b / bevelSegments;
z = bevelThickness * ( 1 - t );
//bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
// contract shape
for ( i = 0, il = contour.length; i < il; i ++ ) {
vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
v( vert.x, vert.y, amount + z );
}
// expand holes
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
oneHoleMovements = holesMovements[ h ];
for ( i = 0, il = ahole.length; i < il; i ++ ) {
vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
if ( !extrudeByPath ) {
v( vert.x, vert.y, amount + z );
} else {
v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
}
}
}
}
/* Faces */
// Top and bottom faces
buildLidFaces();
// Sides faces
buildSideFaces();
///// Internal functions
function buildLidFaces() {
if ( bevelEnabled ) {
var layer = 0 ; // steps + 1
var offset = vlen * layer;
// Bottom faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
}
layer = steps + bevelSegments * 2;
offset = vlen * layer;
// Top faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
}
} else {
// Bottom faces
for ( i = 0; i < flen; i++ ) {
face = faces[ i ];
f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
}
// Top faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
}
}
}
// Create faces for the z-sides of the shape
function buildSideFaces() {
var layeroffset = 0;
sidewalls( contour, layeroffset );
layeroffset += contour.length;
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
sidewalls( ahole, layeroffset );
//, true
layeroffset += ahole.length;
}
}
function sidewalls( contour, layeroffset ) {
var j, k;
i = contour.length;
while ( --i >= 0 ) {
j = i;
k = i - 1;
if ( k < 0 ) k = contour.length - 1;
//console.log('b', i,j, i-1, k,vertices.length);
var s = 0, sl = steps + bevelSegments * 2;
for ( s = 0; s < sl; s ++ ) {
var slen1 = vlen * s;
var slen2 = vlen * ( s + 1 );
var a = layeroffset + j + slen1,
b = layeroffset + k + slen1,
c = layeroffset + k + slen2,
d = layeroffset + j + slen2;
f4( a, b, c, d, contour, s, sl, j, k );
}
}
}
function v( x, y, z ) {
scope.vertices.push( new THREE.Vector3( x, y, z ) );
}
function f3( a, b, c, isBottom ) {
a += shapesOffset;
b += shapesOffset;
c += shapesOffset;
// normal, color, material
scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
scope.faceVertexUvs[ 0 ].push( uvs );
}
function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
a += shapesOffset;
b += shapesOffset;
c += shapesOffset;
d += shapesOffset;
scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
stepIndex, stepsLength, contourIndex1, contourIndex2 );
scope.faceVertexUvs[ 0 ].push( uvs );
}
};
THREE.ExtrudeGeometry.WorldUVGenerator = {
generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
var ax = geometry.vertices[ indexA ].x,
ay = geometry.vertices[ indexA ].y,
bx = geometry.vertices[ indexB ].x,
by = geometry.vertices[ indexB ].y,
cx = geometry.vertices[ indexC ].x,
cy = geometry.vertices[ indexC ].y;
return [
new THREE.UV( ax, ay ),
new THREE.UV( bx, by ),
new THREE.UV( cx, cy )
];
},
generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
},
generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
indexA, indexB, indexC, indexD, stepIndex, stepsLength,
contourIndex1, contourIndex2 ) {
var ax = geometry.vertices[ indexA ].x,
ay = geometry.vertices[ indexA ].y,
az = geometry.vertices[ indexA ].z,
bx = geometry.vertices[ indexB ].x,
by = geometry.vertices[ indexB ].y,
bz = geometry.vertices[ indexB ].z,
cx = geometry.vertices[ indexC ].x,
cy = geometry.vertices[ indexC ].y,
cz = geometry.vertices[ indexC ].z,
dx = geometry.vertices[ indexD ].x,
dy = geometry.vertices[ indexD ].y,
dz = geometry.vertices[ indexD ].z;
if ( Math.abs( ay - by ) < 0.01 ) {
return [
new THREE.UV( ax, 1 - az ),
new THREE.UV( bx, 1 - bz ),
new THREE.UV( cx, 1 - cz ),
new THREE.UV( dx, 1 - dz )
];
} else {
return [
new THREE.UV( ay, 1 - az ),
new THREE.UV( by, 1 - bz ),
new THREE.UV( cy, 1 - cz ),
new THREE.UV( dy, 1 - dz )
];
}
}
};
THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
/**
* @author jonobr1 / http://jonobr1.com
*
* Creates a one-sided polygonal geometry from a path shape. Similar to
* ExtrudeGeometry.
*
* parameters = {
*
* curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
*
* material: <int> // material index for front and back faces
* uvGenerator: <Object> // object that provides UV generator functions
*
* }
**/
THREE.ShapeGeometry = function ( shapes, options ) {
THREE.Geometry.call( this );
if ( shapes instanceof Array === false ) shapes = [ shapes ];
this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
this.addShapeList( shapes, options );
this.computeCentroids();
this.computeFaceNormals();
};
THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* Add an array of shapes to THREE.ShapeGeometry.
*/
THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
for ( var i = 0, l = shapes.length; i < l; i++ ) {
this.addShape( shapes[ i ], options );
}
return this;
};
/**
* Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
*/
THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
if ( options === undefined ) options = {};
var material = options.material;
var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
var shapebb = this.shapebb;
//
var i, l, hole, s;
var shapesOffset = this.vertices.length;
var shapePoints = shape.extractPoints();
var vertices = shapePoints.shape;
var holes = shapePoints.holes;
var reverse = !THREE.Shape.Utils.isClockWise( vertices );
if ( reverse ) {
vertices = vertices.reverse();
// Maybe we should also check if holes are in the opposite direction, just to be safe...
for ( i = 0, l = holes.length; i < l; i++ ) {
hole = holes[ i ];
if ( THREE.Shape.Utils.isClockWise( hole ) ) {
holes[ i ] = hole.reverse();
}
}
reverse = false;
}
var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
// Vertices
var contour = vertices;
for ( i = 0, l = holes.length; i < l; i++ ) {
hole = holes[ i ];
vertices = vertices.concat( hole );
}
//
var vert, vlen = vertices.length;
var face, flen = faces.length;
var cont, clen = contour.length;
for ( i = 0; i < vlen; i++ ) {
vert = vertices[ i ];
this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
}
for ( i = 0; i < flen; i++ ) {
face = faces[ i ];
var a = face[ 0 ] + shapesOffset;
var b = face[ 1 ] + shapesOffset;
var c = face[ 2 ] + shapesOffset;
this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
}
};
/**
* @author astrodud / http://astrodud.isgreat.org/
* @author zz85 / https://github.com/zz85
*/
THREE.LatheGeometry = function ( points, steps, angle ) {
THREE.Geometry.call( this );
var _steps = steps || 12;
var _angle = angle || 2 * Math.PI;
var _newV = [];
var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
for ( var j = 0; j < points.length; j ++ ) {
_newV[ j ] = points[ j ].clone();
this.vertices.push( _newV[ j ] );
}
var i, il = _steps + 1;
for ( i = 0; i < il; i ++ ) {
for ( var j = 0; j < _newV.length; j ++ ) {
_newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
this.vertices.push( _newV[ j ] );
}
}
for ( i = 0; i < _steps; i ++ ) {
for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
var a = i * kl + k;
var b = ( ( i + 1 ) % il ) * kl + k;
var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
var d = i * kl + ( k + 1 ) % kl;
this.faces.push( new THREE.Face4( a, b, c, d ) );
this.faceVertexUvs[ 0 ].push( [
new THREE.UV( 1 - i / _steps, k / kl ),
new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
] );
}
}
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
};
THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author mrdoob / http://mrdoob.com/
* based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
*/
THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
THREE.Geometry.call( this );
var ix, iz,
width_half = width / 2,
height_half = height / 2,
gridX = widthSegments || 1,
gridZ = heightSegments || 1,
gridX1 = gridX + 1,
gridZ1 = gridZ + 1,
segment_width = width / gridX,
segment_height = height / gridZ,
normal = new THREE.Vector3( 0, 0, 1 );
for ( iz = 0; iz < gridZ1; iz ++ ) {
for ( ix = 0; ix < gridX1; ix ++ ) {
var x = ix * segment_width - width_half;
var y = iz * segment_height - height_half;
this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
}
}
for ( iz = 0; iz < gridZ; iz ++ ) {
for ( ix = 0; ix < gridX; ix ++ ) {
var a = ix + gridX1 * iz;
var b = ix + gridX1 * ( iz + 1 );
var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
var d = ( ix + 1 ) + gridX1 * iz;
var face = new THREE.Face4( a, b, c, d );
face.normal.copy( normal );
face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
this.faces.push( face );
this.faceVertexUvs[ 0 ].push( [
new THREE.UV( ix / gridX, 1 - iz / gridZ ),
new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
] );
}
}
this.computeCentroids();
};
THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
THREE.Geometry.call( this );
radius = radius || 50;
phiStart = phiStart !== undefined ? phiStart : 0;
phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
thetaStart = thetaStart !== undefined ? thetaStart : 0;
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
var segmentsX = Math.max( 3, Math.floor( widthSegments ) || 8 );
var segmentsY = Math.max( 2, Math.floor( heightSegments ) || 6 );
var x, y, vertices = [], uvs = [];
for ( y = 0; y <= segmentsY; y ++ ) {
var verticesRow = [];
var uvsRow = [];
for ( x = 0; x <= segmentsX; x ++ ) {
var u = x / segmentsX;
var v = y / segmentsY;
var vertex = new THREE.Vector3();
vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
this.vertices.push( vertex );
verticesRow.push( this.vertices.length - 1 );
uvsRow.push( new THREE.UV( u, 1 - v ) );
}
vertices.push( verticesRow );
uvs.push( uvsRow );
}
for ( y = 0; y < segmentsY; y ++ ) {
for ( x = 0; x < segmentsX; x ++ ) {
var v1 = vertices[ y ][ x + 1 ];
var v2 = vertices[ y ][ x ];
var v3 = vertices[ y + 1 ][ x ];
var v4 = vertices[ y + 1 ][ x + 1 ];
var n1 = this.vertices[ v1 ].clone().normalize();
var n2 = this.vertices[ v2 ].clone().normalize();
var n3 = this.vertices[ v3 ].clone().normalize();
var n4 = this.vertices[ v4 ].clone().normalize();
var uv1 = uvs[ y ][ x + 1 ].clone();
var uv2 = uvs[ y ][ x ].clone();
var uv3 = uvs[ y + 1 ][ x ].clone();
var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
} else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
} else {
this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
}
}
}
this.computeCentroids();
this.computeFaceNormals();
this.boundingSphere = { radius: radius };
};
THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author alteredq / http://alteredqualia.com/
*
* For creating 3D text geometry in three.js
*
* Text = 3D Text
*
* parameters = {
* size: <float>, // size of the text
* height: <float>, // thickness to extrude text
* curveSegments: <int>, // number of points on the curves
*
* font: <string>, // font name
* weight: <string>, // font weight (normal, bold)
* style: <string>, // font style (normal, italics)
*
* bevelEnabled: <bool>, // turn on bevel
* bevelThickness: <float>, // how deep into text bevel goes
* bevelSize: <float>, // how far from text outline is bevel
* }
*
*/
/* Usage Examples
// TextGeometry wrapper
var text3d = new TextGeometry( text, options );
// Complete manner
var textShapes = THREE.FontUtils.generateShapes( text, options );
var text3d = new ExtrudeGeometry( textShapes, options );
*/
THREE.TextGeometry = function ( text, parameters ) {
var textShapes = THREE.FontUtils.generateShapes( text, parameters );
// translate parameters to ExtrudeGeometry API
parameters.amount = parameters.height !== undefined ? parameters.height : 50;
// defaults
if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
THREE.ExtrudeGeometry.call( this, textShapes, parameters );
};
THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
/**
* @author oosmoxiecode
* @author mrdoob / http://mrdoob.com/
* based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
*/
THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
THREE.Geometry.call( this );
var scope = this;
this.radius = radius || 100;
this.tube = tube || 40;
this.radialSegments = radialSegments || 8;
this.tubularSegments = tubularSegments || 6;
this.arc = arc || Math.PI * 2;
var center = new THREE.Vector3(), uvs = [], normals = [];
for ( var j = 0; j <= this.radialSegments; j ++ ) {
for ( var i = 0; i <= this.tubularSegments; i ++ ) {
var u = i / this.tubularSegments * this.arc;
var v = j / this.radialSegments * Math.PI * 2;
center.x = this.radius * Math.cos( u );
center.y = this.radius * Math.sin( u );
var vertex = new THREE.Vector3();
vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
vertex.z = this.tube * Math.sin( v );
this.vertices.push( vertex );
uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
normals.push( vertex.clone().subSelf( center ).normalize() );
}
}
for ( var j = 1; j <= this.radialSegments; j ++ ) {
for ( var i = 1; i <= this.tubularSegments; i ++ ) {
var a = ( this.tubularSegments + 1 ) * j + i - 1;
var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
var d = ( this.tubularSegments + 1 ) * j + i;
var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
face.normal.addSelf( normals[ a ] );
face.normal.addSelf( normals[ b ] );
face.normal.addSelf( normals[ c ] );
face.normal.addSelf( normals[ d ] );
face.normal.normalize();
this.faces.push( face );
this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
}
}
this.computeCentroids();
};
THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author oosmoxiecode
* based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
*/
THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
THREE.Geometry.call( this );
var scope = this;
this.radius = radius || 200;
this.tube = tube || 40;
this.radialSegments = radialSegments || 64;
this.tubularSegments = tubularSegments || 8;
this.p = p || 2;
this.q = q || 3;
this.heightScale = heightScale || 1;
this.grid = new Array(this.radialSegments);
var tang = new THREE.Vector3();
var n = new THREE.Vector3();
var bitan = new THREE.Vector3();
for ( var i = 0; i < this.radialSegments; ++ i ) {
this.grid[ i ] = new Array( this.tubularSegments );
for ( var j = 0; j < this.tubularSegments; ++ j ) {
var u = i / this.radialSegments * 2 * this.p * Math.PI;
var v = j / this.tubularSegments * 2 * Math.PI;
var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
var cx, cy;
tang.sub( p2, p1 );
n.add( p2, p1 );
bitan.cross( tang, n );
n.cross( bitan, tang );
bitan.normalize();
n.normalize();
cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
cy = this.tube * Math.sin( v );
p1.x += cx * n.x + cy * bitan.x;
p1.y += cx * n.y + cy * bitan.y;
p1.z += cx * n.z + cy * bitan.z;
this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
}
}
for ( var i = 0; i < this.radialSegments; ++ i ) {
for ( var j = 0; j < this.tubularSegments; ++ j ) {
var ip = ( i + 1 ) % this.radialSegments;
var jp = ( j + 1 ) % this.tubularSegments;
var a = this.grid[ i ][ j ];
var b = this.grid[ ip ][ j ];
var c = this.grid[ ip ][ jp ];
var d = this.grid[ i ][ jp ];
var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
this.faces.push( new THREE.Face4( a, b, c, d ) );
this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
function vert( x, y, z ) {
return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
}
function getPos( u, v, in_q, in_p, radius, heightScale ) {
var cu = Math.cos( u );
var cv = Math.cos( v );
var su = Math.sin( u );
var quOverP = in_q / in_p * u;
var cs = Math.cos( quOverP );
var tx = radius * ( 2 + cs ) * 0.5 * cu;
var ty = radius * ( 2 + cs ) * su * 0.5;
var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
return new THREE.Vector3( tx, ty, tz );
}
};
THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author WestLangley / https://github.com/WestLangley
* @author zz85 / https://github.com/zz85
* @author miningold / https://github.com/miningold
*
* Modified from the TorusKnotGeometry by @oosmoxiecode
*
* Creates a tube which extrudes along a 3d spline
*
* Uses parallel transport frames as described in
* http://www.cs.indiana.edu/pub/techreports/TR425.pdf
*/
THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
THREE.Geometry.call( this );
this.path = path;
this.segments = segments || 64;
this.radius = radius || 1;
this.radiusSegments = radiusSegments || 8;
this.closed = closed || false;
if ( debug ) this.debug = new THREE.Object3D();
this.grid = [];
var scope = this,
tangent,
normal,
binormal,
numpoints = this.segments + 1,
x, y, z,
tx, ty, tz,
u, v,
cx, cy,
pos, pos2 = new THREE.Vector3(),
i, j,
ip, jp,
a, b, c, d,
uva, uvb, uvc, uvd;
var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
tangents = frames.tangents,
normals = frames.normals,
binormals = frames.binormals;
// proxy internals
this.tangents = tangents;
this.normals = normals;
this.binormals = binormals;
function vert( x, y, z ) {
return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
}
// consruct the grid
for ( i = 0; i < numpoints; i++ ) {
this.grid[ i ] = [];
u = i / ( numpoints - 1 );
pos = path.getPointAt( u );
tangent = tangents[ i ];
normal = normals[ i ];
binormal = binormals[ i ];
if ( this.debug ) {
this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
}
for ( j = 0; j < this.radiusSegments; j++ ) {
v = j / this.radiusSegments * 2 * Math.PI;
cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
cy = this.radius * Math.sin( v );
pos2.copy( pos );
pos2.x += cx * normal.x + cy * binormal.x;
pos2.y += cx * normal.y + cy * binormal.y;
pos2.z += cx * normal.z + cy * binormal.z;
this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
}
}
// construct the mesh
for ( i = 0; i < this.segments; i++ ) {
for ( j = 0; j < this.radiusSegments; j++ ) {
ip = ( closed ) ? (i + 1) % this.segments : i + 1;
jp = (j + 1) % this.radiusSegments;
a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
b = this.grid[ ip ][ j ];
c = this.grid[ ip ][ jp ];
d = this.grid[ i ][ jp ];
uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
this.faces.push( new THREE.Face4( a, b, c, d ) );
this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
};
THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
// For computing of Frenet frames, exposing the tangents, normals and binormals the spline
THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
var
tangent = new THREE.Vector3(),
normal = new THREE.Vector3(),
binormal = new THREE.Vector3(),
tangents = [],
normals = [],
binormals = [],
vec = new THREE.Vector3(),
mat = new THREE.Matrix4(),
numpoints = segments + 1,
theta,
epsilon = 0.0001,
smallest,
tx, ty, tz,
i, u, v;
// expose internals
this.tangents = tangents;
this.normals = normals;
this.binormals = binormals;
// compute the tangent vectors for each segment on the path
for ( i = 0; i < numpoints; i++ ) {
u = i / ( numpoints - 1 );
tangents[ i ] = path.getTangentAt( u );
tangents[ i ].normalize();
}
initialNormal3();
function initialNormal1(lastBinormal) {
// fixed start binormal. Has dangers of 0 vectors
normals[ 0 ] = new THREE.Vector3();
binormals[ 0 ] = new THREE.Vector3();
if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
}
function initialNormal2() {
// This uses the Frenet-Serret formula for deriving binormal
var t2 = path.getTangentAt( epsilon );
normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
}
function initialNormal3() {
// select an initial normal vector perpenicular to the first tangent vector,
// and in the direction of the smallest tangent xyz component
normals[ 0 ] = new THREE.Vector3();
binormals[ 0 ] = new THREE.Vector3();
smallest = Number.MAX_VALUE;
tx = Math.abs( tangents[ 0 ].x );
ty = Math.abs( tangents[ 0 ].y );
tz = Math.abs( tangents[ 0 ].z );
if ( tx <= smallest ) {
smallest = tx;
normal.set( 1, 0, 0 );
}
if ( ty <= smallest ) {
smallest = ty;
normal.set( 0, 1, 0 );
}
if ( tz <= smallest ) {
normal.set( 0, 0, 1 );
}
vec.cross( tangents[ 0 ], normal ).normalize();
normals[ 0 ].cross( tangents[ 0 ], vec );
binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
}
// compute the slowly-varying normal and binormal vectors for each segment on the path
for ( i = 1; i < numpoints; i++ ) {
normals[ i ] = normals[ i-1 ].clone();
binormals[ i ] = binormals[ i-1 ].clone();
vec.cross( tangents[ i-1 ], tangents[ i ] );
if ( vec.length() > epsilon ) {
vec.normalize();
theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
}
binormals[ i ].cross( tangents[ i ], normals[ i ] );
}
// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
if ( closed ) {
theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
theta /= ( numpoints - 1 );
if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
theta = -theta;
}
for ( i = 1; i < numpoints; i++ ) {
// twist a little...
mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
binormals[ i ].cross( tangents[ i ], normals[ i ] );
}
}
};
/**
* @author clockworkgeek / https://github.com/clockworkgeek
* @author timothypratley / https://github.com/timothypratley
*/
THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
THREE.Geometry.call( this );
radius = radius || 1;
detail = detail || 0;
var that = this;
for ( var i = 0, l = vertices.length; i < l; i ++ ) {
prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
}
var midpoints = [], p = this.vertices;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
}
this.mergeVertices();
// Apply radius
for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
this.vertices[ i ].multiplyScalar( radius );
}
// Project vector onto sphere's surface
function prepare( vector ) {
var vertex = vector.normalize().clone();
vertex.index = that.vertices.push( vertex ) - 1;
// Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
var u = azimuth( vector ) / 2 / Math.PI + 0.5;
var v = inclination( vector ) / Math.PI + 0.5;
vertex.uv = new THREE.UV( u, 1 - v );
return vertex;
}
// Approximate a curved face with recursively sub-divided triangles.
function make( v1, v2, v3, detail ) {
if ( detail < 1 ) {
var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
face.normal = face.centroid.clone().normalize();
that.faces.push( face );
var azi = azimuth( face.centroid );
that.faceVertexUvs[ 0 ].push( [
correctUV( v1.uv, v1, azi ),
correctUV( v2.uv, v2, azi ),
correctUV( v3.uv, v3, azi )
] );
} else {
detail -= 1;
// split triangle into 4 smaller triangles
make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
}
}
function midpoint( v1, v2 ) {
if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
var mid = midpoints[ v1.index ][ v2.index ];
if ( mid === undefined ) {
// generate mean point and project to surface with prepare()
midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
);
}
return mid;
}
// Angle around the Y axis, counter-clockwise when looking from above.
function azimuth( vector ) {
return Math.atan2( vector.z, -vector.x );
}
// Angle above the XZ plane.
function inclination( vector ) {
return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
}
// Texture fixing helper. Spheres have some odd behaviours.
function correctUV( uv, vector, azimuth ) {
if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
return uv;
}
this.computeCentroids();
this.boundingSphere = { radius: radius };
};
THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author timothypratley / https://github.com/timothypratley
*/
THREE.IcosahedronGeometry = function ( radius, detail ) {
var t = ( 1 + Math.sqrt( 5 ) ) / 2;
var vertices = [
[ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
[ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
[ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
];
var faces = [
[ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
[ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
[ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
[ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
];
THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
};
THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author timothypratley / https://github.com/timothypratley
*/
THREE.OctahedronGeometry = function ( radius, detail ) {
var vertices = [
[ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
];
var faces = [
[ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
];
THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
};
THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author timothypratley / https://github.com/timothypratley
*/
THREE.TetrahedronGeometry = function ( radius, detail ) {
var vertices = [
[ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
];
var faces = [
[ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
];
THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
};
THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author zz85 / https://github.com/zz85
* Parametric Surfaces Geometry
* based on the brilliant article by @prideout http://prideout.net/blog/?p=44
*
* new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
*
*/
THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
THREE.Geometry.call( this );
var verts = this.vertices;
var faces = this.faces;
var uvs = this.faceVertexUvs[ 0 ];
useTris = (useTris === undefined) ? false : useTris;
var i, il, j, p;
var u, v;
var stackCount = stacks + 1;
var sliceCount = slices + 1;
for ( i = 0; i <= stacks; i ++ ) {
v = i / stacks;
for ( j = 0; j <= slices; j ++ ) {
u = j / slices;
p = func( u, v );
verts.push( p );
}
}
var a, b, c, d;
var uva, uvb, uvc, uvd;
for ( i = 0; i < stacks; i ++ ) {
for ( j = 0; j < slices; j ++ ) {
a = i * sliceCount + j;
b = i * sliceCount + j + 1;
c = (i + 1) * sliceCount + j;
d = (i + 1) * sliceCount + j + 1;
uva = new THREE.UV( j / slices, i / stacks );
uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
if ( useTris ) {
faces.push( new THREE.Face3( a, b, c ) );
faces.push( new THREE.Face3( b, d, c ) );
uvs.push( [ uva, uvb, uvc ] );
uvs.push( [ uvb, uvd, uvc ] );
} else {
faces.push( new THREE.Face4( a, b, d, c ) );
uvs.push( [ uva, uvb, uvd, uvc ] );
}
}
}
// console.log(this);
// magic bullet
// var diff = this.mergeVertices();
// console.log('removed ', diff, ' vertices by merging');
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
};
THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author qiao / https://github.com/qiao
* @fileoverview This is a convex hull generator using the incremental method.
* The complexity is O(n^2) where n is the number of vertices.
* O(nlogn) algorithms do exist, but they are much more complicated.
*
* Benchmark:
*
* Platform: CPU: P7350 @2.00GHz Engine: V8
*
* Num Vertices Time(ms)
*
* 10 1
* 20 3
* 30 19
* 40 48
* 50 107
*/
THREE.ConvexGeometry = function( vertices ) {
THREE.Geometry.call( this );
var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
for ( var i = 3; i < vertices.length; i++ ) {
addPoint( i );
}
function addPoint( vertexId ) {
var vertex = vertices[ vertexId ].clone();
var mag = vertex.length();
vertex.x += mag * randomOffset();
vertex.y += mag * randomOffset();
vertex.z += mag * randomOffset();
var hole = [];
for ( var f = 0; f < faces.length; ) {
var face = faces[ f ];
// for each face, if the vertex can see it,
// then we try to add the face's edges into the hole.
if ( visible( face, vertex ) ) {
for ( var e = 0; e < 3; e++ ) {
var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
var boundary = true;
// remove duplicated edges.
for ( var h = 0; h < hole.length; h++ ) {
if ( equalEdge( hole[ h ], edge ) ) {
hole[ h ] = hole[ hole.length - 1 ];
hole.pop();
boundary = false;
break;
}
}
if ( boundary ) {
hole.push( edge );
}
}
// remove faces[ f ]
faces[ f ] = faces[ faces.length - 1 ];
faces.pop();
} else { // not visible
f++;
}
}
// construct the new faces formed by the edges of the hole and the vertex
for ( var h = 0; h < hole.length; h++ ) {
faces.push( [
hole[ h ][ 0 ],
hole[ h ][ 1 ],
vertexId
] );
}
}
/**
* Whether the face is visible from the vertex
*/
function visible( face, vertex ) {
var va = vertices[ face[ 0 ] ];
var vb = vertices[ face[ 1 ] ];
var vc = vertices[ face[ 2 ] ];
var n = normal( va, vb, vc );
// distance from face to origin
var dist = n.dot( va );
return n.dot( vertex ) >= dist;
}
/**
* Face normal
*/
function normal( va, vb, vc ) {
var cb = new THREE.Vector3();
var ab = new THREE.Vector3();
cb.sub( vc, vb );
ab.sub( va, vb );
cb.crossSelf( ab );
if ( !cb.isZero() ) {
cb.normalize();
}
return cb;
}
/**
* Detect whether two edges are equal.
* Note that when constructing the convex hull, two same edges can only
* be of the negative direction.
*/
function equalEdge( ea, eb ) {
return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
}
/**
* Create a random offset between -1e-6 and 1e-6.
*/
function randomOffset() {
return ( Math.random() - 0.5 ) * 2 * 1e-6;
}
/**
* XXX: Not sure if this is the correct approach. Need someone to review.
*/
function vertexUv( vertex ) {
var mag = vertex.length();
return new THREE.UV( vertex.x / mag, vertex.y / mag );
}
// Push vertices into `this.vertices`, skipping those inside the hull
var id = 0;
var newId = new Array( vertices.length ); // map from old vertex id to new id
for ( var i = 0; i < faces.length; i++ ) {
var face = faces[ i ];
for ( var j = 0; j < 3; j++ ) {
if ( newId[ face[ j ] ] === undefined ) {
newId[ face[ j ] ] = id++;
this.vertices.push( vertices[ face[ j ] ] );
}
face[ j ] = newId[ face[ j ] ];
}
}
// Convert faces into instances of THREE.Face3
for ( var i = 0; i < faces.length; i++ ) {
this.faces.push( new THREE.Face3(
faces[ i ][ 0 ],
faces[ i ][ 1 ],
faces[ i ][ 2 ]
) );
}
// Compute UVs
for ( var i = 0; i < this.faces.length; i++ ) {
var face = this.faces[ i ];
this.faceVertexUvs[ 0 ].push( [
vertexUv( this.vertices[ face.a ] ),
vertexUv( this.vertices[ face.b ] ),
vertexUv( this.vertices[ face.c ])
] );
}
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
};
THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author sroucheray / http://sroucheray.org/
* @author mrdoob / http://mrdoob.com/
*/
THREE.AxisHelper = function ( size ) {
var geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
);
geometry.colors.push(
new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
);
var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
THREE.Line.call( this, geometry, material, THREE.LinePieces );
};
THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
/**
* @author WestLangley / http://github.com/WestLangley
* @author zz85 / https://github.com/zz85
*
* Creates an arrow for visualizing directions
*
* Parameters:
* dir - Vector3
* origin - Vector3
* length - Number
* hex - color in hex value
*/
THREE.ArrowHelper = function ( dir, origin, length, hex ) {
THREE.Object3D.call( this );
if ( hex === undefined ) hex = 0xffff00;
if ( length === undefined ) length = 20;
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
this.add( this.line );
var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
this.cone.position.set( 0, 1, 0 );
this.add( this.cone );
if ( origin instanceof THREE.Vector3 ) this.position = origin;
this.setDirection( dir );
this.setLength( length );
};
THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
};
THREE.ArrowHelper.prototype.setLength = function ( length ) {
this.scale.set( length, length, length );
};
THREE.ArrowHelper.prototype.setColor = function ( hex ) {
this.line.material.color.setHex( hex );
this.cone.material.color.setHex( hex );
};
/**
* @author alteredq / http://alteredqualia.com/
*
* - shows frustum, line of sight and up of the camera
* - suitable for fast updates
* - based on frustum visualization in lightgl.js shadowmap example
* http://evanw.github.com/lightgl.js/tests/shadowmap.html
*/
THREE.CameraHelper = function ( camera ) {
THREE.Line.call( this );
var scope = this;
this.geometry = new THREE.Geometry();
this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
this.type = THREE.LinePieces;
this.matrixWorld = camera.matrixWorld;
this.matrixAutoUpdate = false;
this.pointMap = {};
// colors
var hexFrustum = 0xffaa00;
var hexCone = 0xff0000;
var hexUp = 0x00aaff;
var hexTarget = 0xffffff;
var hexCross = 0x333333;
// near
addLine( "n1", "n2", hexFrustum );
addLine( "n2", "n4", hexFrustum );
addLine( "n4", "n3", hexFrustum );
addLine( "n3", "n1", hexFrustum );
// far
addLine( "f1", "f2", hexFrustum );
addLine( "f2", "f4", hexFrustum );
addLine( "f4", "f3", hexFrustum );
addLine( "f3", "f1", hexFrustum );
// sides
addLine( "n1", "f1", hexFrustum );
addLine( "n2", "f2", hexFrustum );
addLine( "n3", "f3", hexFrustum );
addLine( "n4", "f4", hexFrustum );
// cone
addLine( "p", "n1", hexCone );
addLine( "p", "n2", hexCone );
addLine( "p", "n3", hexCone );
addLine( "p", "n4", hexCone );
// up
addLine( "u1", "u2", hexUp );
addLine( "u2", "u3", hexUp );
addLine( "u3", "u1", hexUp );
// target
addLine( "c", "t", hexTarget );
addLine( "p", "c", hexCross );
// cross
addLine( "cn1", "cn2", hexCross );
addLine( "cn3", "cn4", hexCross );
addLine( "cf1", "cf2", hexCross );
addLine( "cf3", "cf4", hexCross );
this.camera = camera;
function addLine( a, b, hex ) {
addPoint( a, hex );
addPoint( b, hex );
}
function addPoint( id, hex ) {
scope.geometry.vertices.push( new THREE.Vector3() );
scope.geometry.colors.push( new THREE.Color( hex ) );
if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
}
this.update( camera );
};
THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
THREE.CameraHelper.prototype.update = function () {
var scope = this;
var w = 1, h = 1;
// we need just camera projection matrix
// world matrix must be identity
THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
// center / target
setPoint( "c", 0, 0, -1 );
setPoint( "t", 0, 0, 1 );
// near
setPoint( "n1", -w, -h, -1 );
setPoint( "n2", w, -h, -1 );
setPoint( "n3", -w, h, -1 );
setPoint( "n4", w, h, -1 );
// far
setPoint( "f1", -w, -h, 1 );
setPoint( "f2", w, -h, 1 );
setPoint( "f3", -w, h, 1 );
setPoint( "f4", w, h, 1 );
// up
setPoint( "u1", w * 0.7, h * 1.1, -1 );
setPoint( "u2", -w * 0.7, h * 1.1, -1 );
setPoint( "u3", 0, h * 2, -1 );
// cross
setPoint( "cf1", -w, 0, 1 );
setPoint( "cf2", w, 0, 1 );
setPoint( "cf3", 0, -h, 1 );
setPoint( "cf4", 0, h, 1 );
setPoint( "cn1", -w, 0, -1 );
setPoint( "cn2", w, 0, -1 );
setPoint( "cn3", 0, -h, -1 );
setPoint( "cn4", 0, h, -1 );
function setPoint( point, x, y, z ) {
THREE.CameraHelper.__v.set( x, y, z );
THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
var points = scope.pointMap[ point ];
if ( points !== undefined ) {
for ( var i = 0, il = points.length; i < il; i ++ ) {
scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
}
}
}
this.geometry.verticesNeedUpdate = true;
};
THREE.CameraHelper.__projector = new THREE.Projector();
THREE.CameraHelper.__v = new THREE.Vector3();
THREE.CameraHelper.__c = new THREE.Camera();
/*
* @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
*
* Subdivision Geometry Modifier
* using Catmull-Clark Subdivision Surfaces
* for creating smooth geometry meshes
*
* Note: a modifier modifies vertices and faces of geometry,
* so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
*
* Readings:
* http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
* http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
* http://xrt.wikidot.com/blog:31
* "Subdivision Surfaces in Character Animation"
*
* (on boundary edges)
* http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
* https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
*
* Supports:
* Closed and Open geometries.
*
* TODO:
* crease vertex and "semi-sharp" features
* selective subdivision
*/
THREE.SubdivisionModifier = function( subdivisions ) {
this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
// Settings
this.useOldVertexColors = false;
this.supportUVs = true;
this.debug = false;
};
// Applies the "modify" pattern
THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
var repeats = this.subdivisions;
while ( repeats-- > 0 ) {
this.smooth( geometry );
}
};
/// REFACTORING THIS OUT
THREE.GeometryUtils.orderedKey = function ( a, b ) {
return Math.min( a, b ) + "_" + Math.max( a, b );
};
// Returns a hashmap - of { edge_key: face_index }
THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
var i, il, v1, v2, j, k,
face, faceIndices, faceIndex,
edge,
hash,
edgeFaceMap = {};
var orderedKey = THREE.GeometryUtils.orderedKey;
function mapEdgeHash( hash, i ) {
if ( edgeFaceMap[ hash ] === undefined ) {
edgeFaceMap[ hash ] = [];
}
edgeFaceMap[ hash ].push( i );
}
// construct vertex -> face map
for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
face = geometry.faces[ i ];
if ( face instanceof THREE.Face3 ) {
hash = orderedKey( face.a, face.b );
mapEdgeHash( hash, i );
hash = orderedKey( face.b, face.c );
mapEdgeHash( hash, i );
hash = orderedKey( face.c, face.a );
mapEdgeHash( hash, i );
} else if ( face instanceof THREE.Face4 ) {
hash = orderedKey( face.a, face.b );
mapEdgeHash( hash, i );
hash = orderedKey( face.b, face.c );
mapEdgeHash( hash, i );
hash = orderedKey( face.c, face.d );
mapEdgeHash( hash, i );
hash = orderedKey( face.d, face.a );
mapEdgeHash( hash, i );
}
}
// extract faces
// var edges = [];
//
// var numOfEdges = 0;
// for (i in edgeFaceMap) {
// numOfEdges++;
//
// edge = edgeFaceMap[i];
// edges.push(edge);
//
// }
//debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
return edgeFaceMap;
}
/////////////////////////////
// Performs an iteration of Catmull-Clark Subdivision
THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
//debug( 'running smooth' );
// New set of vertices, faces and uvs
var newVertices = [], newFaces = [], newUVs = [];
function v( x, y, z ) {
newVertices.push( new THREE.Vector3( x, y, z ) );
}
var scope = this;
var orderedKey = THREE.GeometryUtils.orderedKey;
var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
function assert() {
if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
}
function debug() {
if (scope.debug) console.log.apply(console, arguments);
}
function warn() {
if (console)
console.log.apply(console, arguments);
}
function f4( a, b, c, d, oldFace, orders, facei ) {
// TODO move vertex selection over here!
var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
if (scope.useOldVertexColors) {
newFace.vertexColors = [];
var color, tmpColor, order;
for (var i=0;i<4;i++) {
order = orders[i];
color = new THREE.Color(),
color.setRGB(0,0,0);
for (var j=0, jl=0; j<order.length;j++) {
tmpColor = oldFace.vertexColors[order[j]-1];
color.r += tmpColor.r;
color.g += tmpColor.g;
color.b += tmpColor.b;
}
color.r /= order.length;
color.g /= order.length;
color.b /= order.length;
newFace.vertexColors[i] = color;
}
}
newFaces.push( newFace );
if (scope.supportUVs) {
var aUv = [
getUV(a, ''),
getUV(b, facei),
getUV(c, facei),
getUV(d, facei)
];
if (!aUv[0]) debug('a :( ', a+':'+facei);
else if (!aUv[1]) debug('b :( ', b+':'+facei);
else if (!aUv[2]) debug('c :( ', c+':'+facei);
else if (!aUv[3]) debug('d :( ', d+':'+facei);
else
newUVs.push( aUv );
}
}
var originalPoints = oldGeometry.vertices;
var originalFaces = oldGeometry.faces;
var originalVerticesLength = originalPoints.length;
var newPoints = originalPoints.concat(); // New set of vertices to work on
var facePoints = [], // these are new points on exisiting faces
edgePoints = {}; // these are new points on exisiting edges
var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
// TODO: handle this correctly.
var uvForVertices = {}; // Stored in {vertex}:{old face} format
function debugCoreStuff() {
console.log('facePoints', facePoints, 'edgePoints', edgePoints);
console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
}
function getUV(vertexNo, oldFaceNo) {
var j,jl;
var key = vertexNo+':'+oldFaceNo;
var theUV = uvForVertices[key];
if (!theUV) {
if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
debug('face pt');
} else {
debug('edge pt');
}
warn('warning, UV not found for', key);
return null;
}
return theUV;
// Original faces -> Vertex Nos.
// new Facepoint -> Vertex Nos.
// edge Points
}
function addUV(vertexNo, oldFaceNo, value) {
var key = vertexNo+':'+oldFaceNo;
if (!(key in uvForVertices)) {
uvForVertices[key] = value;
} else {
warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
}
}
// Step 1
// For each face, add a face point
// Set each face point to be the centroid of all original points for the respective face.
// debug(oldGeometry);
var i, il, j, jl, face;
// For Uvs
var uvs = oldGeometry.faceVertexUvs[0];
var abcd = 'abcd', vertice;
debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
if (scope.supportUVs)
for (i=0, il = uvs.length; i<il; i++ ) {
for (j=0,jl=uvs[i].length;j<jl;j++) {
vertice = originalFaces[i][abcd.charAt(j)];
addUV(vertice, i, uvs[i][j]);
}
}
if (uvs.length == 0) scope.supportUVs = false;
// Additional UVs check, if we index original
var uvCount = 0;
for (var u in uvForVertices) {
uvCount++;
}
if (!uvCount) {
scope.supportUVs = false;
debug('no uvs');
}
var avgUv ;
for (i=0, il = originalFaces.length; i<il ;i++) {
face = originalFaces[ i ];
facePoints.push( face.centroid );
newPoints.push( face.centroid );
if (!scope.supportUVs) continue;
// Prepare subdivided uv
avgUv = new THREE.UV();
if ( face instanceof THREE.Face3 ) {
avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
avgUv.u /= 3;
avgUv.v /= 3;
} else if ( face instanceof THREE.Face4 ) {
avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
avgUv.u /= 4;
avgUv.v /= 4;
}
addUV(originalVerticesLength + i, '', avgUv);
}
// Step 2
// For each edge, add an edge point.
// Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
var edge, faceIndexA, faceIndexB, avg;
// debug('edgeFaceMap', edgeFaceMap);
var edgeCount = 0;
var edgeVertex, edgeVertexA, edgeVertexB;
////
var vertexEdgeMap = {}; // Gives edges connecting from each vertex
var vertexFaceMap = {}; // Gives faces connecting from each vertex
function addVertexEdgeMap(vertex, edge) {
if (vertexEdgeMap[vertex]===undefined) {
vertexEdgeMap[vertex] = [];
}
vertexEdgeMap[vertex].push(edge);
}
function addVertexFaceMap(vertex, face, edge) {
if (vertexFaceMap[vertex]===undefined) {
vertexFaceMap[vertex] = {};
}
vertexFaceMap[vertex][face] = edge;
// vertexFaceMap[vertex][face] = null;
}
// Prepares vertexEdgeMap and vertexFaceMap
for (i in edgeFaceMap) { // This is for every edge
edge = edgeFaceMap[i];
edgeVertex = i.split('_');
edgeVertexA = edgeVertex[0];
edgeVertexB = edgeVertex[1];
// Maps an edgeVertex to connecting edges
addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
for (j=0,jl=edge.length;j<jl;j++) {
face = edge[j];
addVertexFaceMap(edgeVertexA, face, i);
addVertexFaceMap(edgeVertexB, face, i);
}
// {edge vertex: { face1: edge_key, face2: edge_key.. } }
// this thing is fishy right now.
if (edge.length < 2) {
// edge is "sharp";
sharpEdges[i] = true;
sharpVertices[edgeVertexA] = true;
sharpVertices[edgeVertexB] = true;
}
}
for (i in edgeFaceMap) {
edge = edgeFaceMap[i];
faceIndexA = edge[0]; // face index a
faceIndexB = edge[1]; // face index b
edgeVertex = i.split('_');
edgeVertexA = edgeVertex[0];
edgeVertexB = edgeVertex[1];
avg = new THREE.Vector3();
//debug(i, faceIndexB,facePoints[faceIndexB]);
assert(edge.length > 0, 'an edge without faces?!');
if (edge.length==1) {
avg.addSelf(originalPoints[edgeVertexA]);
avg.addSelf(originalPoints[edgeVertexB]);
avg.multiplyScalar(0.5);
sharpVertices[newPoints.length] = true;
} else {
avg.addSelf(facePoints[faceIndexA]);
avg.addSelf(facePoints[faceIndexB]);
avg.addSelf(originalPoints[edgeVertexA]);
avg.addSelf(originalPoints[edgeVertexB]);
avg.multiplyScalar(0.25);
}
edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
newPoints.push( avg );
edgeCount ++;
if (!scope.supportUVs) {
continue;
}
// Prepare subdivided uv
avgUv = new THREE.UV();
avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
avgUv.u /= 2;
avgUv.v /= 2;
addUV(edgePoints[i], faceIndexA, avgUv);
if (edge.length>=2) {
assert(edge.length == 2, 'did we plan for more than 2 edges?');
avgUv = new THREE.UV();
avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
avgUv.u /= 2;
avgUv.v /= 2;
addUV(edgePoints[i], faceIndexB, avgUv);
}
}
debug('-- Step 2 done');
// Step 3
// For each face point, add an edge for every edge of the face,
// connecting the face point to each edge point for the face.
var facePt, currentVerticeIndex;
var hashAB, hashBC, hashCD, hashDA, hashCA;
var abc123 = ['123', '12', '2', '23'];
var bca123 = ['123', '23', '3', '31'];
var cab123 = ['123', '31', '1', '12'];
var abc1234 = ['1234', '12', '2', '23'];
var bcd1234 = ['1234', '23', '3', '34'];
var cda1234 = ['1234', '34', '4', '41'];
var dab1234 = ['1234', '41', '1', '12'];
for (i=0, il = facePoints.length; i<il ;i++) { // for every face
facePt = facePoints[i];
face = originalFaces[i];
currentVerticeIndex = originalVerticesLength+ i;
if ( face instanceof THREE.Face3 ) {
// create 3 face4s
hashAB = orderedKey( face.a, face.b );
hashBC = orderedKey( face.b, face.c );
hashCA = orderedKey( face.c, face.a );
f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
} else if ( face instanceof THREE.Face4 ) {
// create 4 face4s
hashAB = orderedKey( face.a, face.b );
hashBC = orderedKey( face.b, face.c );
hashCD = orderedKey( face.c, face.d );
hashDA = orderedKey( face.d, face.a );
f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
} else {
debug('face should be a face!', face);
}
}
newVertices = newPoints;
// Step 4
// For each original point P,
// take the average F of all n face points for faces touching P,
// and take the average R of all n edge midpoints for edges touching P,
// where each edge midpoint is the average of its two endpoint vertices.
// Move each original point to the point
var F = new THREE.Vector3();
var R = new THREE.Vector3();
var n;
for (i=0, il = originalPoints.length; i<il; i++) {
// (F + 2R + (n-3)P) / n
if (vertexEdgeMap[i]===undefined) continue;
F.set(0,0,0);
R.set(0,0,0);
var newPos = new THREE.Vector3(0,0,0);
var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
for (j in vertexFaceMap[i]) {
F.addSelf(facePoints[j]);
f++;
}
var sharpEdgeCount = 0;
n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
// Are we on the border?
var boundary_case = f != n;
// if (boundary_case) {
// console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
// }
for (j=0;j<n;j++) {
if (
sharpEdges[
orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
]) {
sharpEdgeCount++;
}
}
// if ( sharpEdgeCount==2 ) {
// continue;
// // Do not move vertex if there's 2 connecting sharp edges.
// }
/*
if (sharpEdgeCount>2) {
// TODO
}
*/
F.divideScalar(f);
var boundary_edges = 0;
if (boundary_case) {
var bb_edge;
for (j=0; j<n;j++) {
edge = vertexEdgeMap[i][j];
bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
if (bb_edge) {
var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
R.addSelf(midPt);
boundary_edges++;
}
}
R.divideScalar(4);
// console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
assert(boundary_edges == 2, 'should have only 2 boundary edges');
} else {
for (j=0; j<n;j++) {
edge = vertexEdgeMap[i][j];
var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
R.addSelf(midPt);
}
R.divideScalar(n);
}
// Sum the formula
newPos.addSelf(originalPoints[i]);
if (boundary_case) {
newPos.divideScalar(2);
newPos.addSelf(R);
} else {
newPos.multiplyScalar(n - 3);
newPos.addSelf(F);
newPos.addSelf(R.multiplyScalar(2));
newPos.divideScalar(n);
}
newVertices[i] = newPos;
}
var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
newGeometry.vertices = newVertices;
newGeometry.faces = newFaces;
newGeometry.faceVertexUvs[ 0 ] = newUVs;
delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
newGeometry.computeCentroids();
newGeometry.computeFaceNormals();
newGeometry.computeVertexNormals();
};/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ImmediateRenderObject = function ( ) {
THREE.Object3D.call( this );
this.render = function ( renderCallback ) { };
};
THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.LensFlare = function ( texture, size, distance, blending, color ) {
THREE.Object3D.call( this );
this.lensFlares = [];
this.positionScreen = new THREE.Vector3();
this.customUpdateCallback = undefined;
if( texture !== undefined ) {
this.add( texture, size, distance, blending, color );
}
};
THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
/*
* Add: adds another flare
*/
THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
if( size === undefined ) size = -1;
if( distance === undefined ) distance = 0;
if( opacity === undefined ) opacity = 1;
if( color === undefined ) color = new THREE.Color( 0xffffff );
if( blending === undefined ) blending = THREE.NormalBlending;
distance = Math.min( distance, Math.max( 0, distance ) );
this.lensFlares.push( { texture: texture, // THREE.Texture
size: size, // size in pixels (-1 = use texture.width)
distance: distance, // distance (0-1) from light source (0=at light source)
x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
scale: 1, // scale
rotation: 1, // rotation
opacity: opacity, // opacity
color: color, // color
blending: blending } ); // blending
};
/*
* Update lens flares update positions on all flares based on the screen position
* Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
*/
THREE.LensFlare.prototype.updateLensFlares = function () {
var f, fl = this.lensFlares.length;
var flare;
var vecX = -this.positionScreen.x * 2;
var vecY = -this.positionScreen.y * 2;
for( f = 0; f < fl; f ++ ) {
flare = this.lensFlares[ f ];
flare.x = this.positionScreen.x + vecX * flare.distance;
flare.y = this.positionScreen.y + vecY * flare.distance;
flare.wantedRotation = flare.x * Math.PI * 0.25;
flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MorphBlendMesh = function( geometry, material ) {
THREE.Mesh.call( this, geometry, material );
this.animationsMap = {};
this.animationsList = [];
// prepare default animation
// (all frames played together in 1 second)
var numFrames = this.geometry.morphTargets.length;
var name = "__default";
var startFrame = 0;
var endFrame = numFrames - 1;
var fps = numFrames / 1;
this.createAnimation( name, startFrame, endFrame, fps );
this.setAnimationWeight( name, 1 );
};
THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
var animation = {
startFrame: start,
endFrame: end,
length: end - start + 1,
fps: fps,
duration: ( end - start ) / fps,
lastFrame: 0,
currentFrame: 0,
active: false,
time: 0,
direction: 1,
weight: 1,
directionBackwards: false,
mirroredLoop: false
};
this.animationsMap[ name ] = animation;
this.animationsList.push( animation );
};
THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
var pattern = /([a-z]+)(\d+)/;
var firstAnimation, frameRanges = {};
var geometry = this.geometry;
for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
var morph = geometry.morphTargets[ i ];
var chunks = morph.name.match( pattern );
if ( chunks && chunks.length > 1 ) {
var name = chunks[ 1 ];
var num = chunks[ 2 ];
if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
var range = frameRanges[ name ];
if ( i < range.start ) range.start = i;
if ( i > range.end ) range.end = i;
if ( ! firstAnimation ) firstAnimation = name;
}
}
for ( var name in frameRanges ) {
var range = frameRanges[ name ];
this.createAnimation( name, range.start, range.end, fps );
}
this.firstAnimation = firstAnimation;
};
THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.direction = 1;
animation.directionBackwards = false;
}
};
THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.direction = -1;
animation.directionBackwards = true;
}
};
THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.fps = fps;
animation.duration = ( animation.end - animation.start ) / animation.fps;
}
};
THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.duration = duration;
animation.fps = ( animation.end - animation.start ) / animation.duration;
}
};
THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.weight = weight;
}
};
THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.time = time;
}
};
THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
var time = 0;
var animation = this.animationsMap[ name ];
if ( animation ) {
time = animation.time;
}
return time;
};
THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
var duration = -1;
var animation = this.animationsMap[ name ];
if ( animation ) {
duration = animation.duration;
}
return duration;
};
THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.time = 0;
animation.active = true;
} else {
console.warn( "animation[" + name + "] undefined" );
}
};
THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.active = false;
}
};
THREE.MorphBlendMesh.prototype.update = function ( delta ) {
for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
var animation = this.animationsList[ i ];
if ( ! animation.active ) continue;
var frameTime = animation.duration / animation.length;
animation.time += animation.direction * delta;
if ( animation.mirroredLoop ) {
if ( animation.time > animation.duration || animation.time < 0 ) {
animation.direction *= -1;
if ( animation.time > animation.duration ) {
animation.time = animation.duration;
animation.directionBackwards = true;
}
if ( animation.time < 0 ) {
animation.time = 0;
animation.directionBackwards = false;
}
}
} else {
animation.time = animation.time % animation.duration;
if ( animation.time < 0 ) animation.time += animation.duration;
}
var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
var weight = animation.weight;
if ( keyframe !== animation.currentFrame ) {
this.morphTargetInfluences[ animation.lastFrame ] = 0;
this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
this.morphTargetInfluences[ keyframe ] = 0;
animation.lastFrame = animation.currentFrame;
animation.currentFrame = keyframe;
}
var mix = ( animation.time % frameTime ) / frameTime;
if ( animation.directionBackwards ) mix = 1 - mix;
this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
}
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.LensFlarePlugin = function ( ) {
var _gl, _renderer, _lensFlare = {};
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
_lensFlare.vertices = new Float32Array( 8 + 8 );
_lensFlare.faces = new Uint16Array( 6 );
var i = 0;
_lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
_lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
_lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
_lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
i = 0;
_lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
_lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
// buffers
_lensFlare.vertexBuffer = _gl.createBuffer();
_lensFlare.elementBuffer = _gl.createBuffer();
_gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
// textures
_lensFlare.tempTexture = _gl.createTexture();
_lensFlare.occlusionTexture = _gl.createTexture();
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
_lensFlare.hasVertexTexture = false;
_lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
} else {
_lensFlare.hasVertexTexture = true;
_lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
}
_lensFlare.attributes = {};
_lensFlare.uniforms = {};
_lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
_lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
_lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
_lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
_lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
_lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
_lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
_lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
_lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
_lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
_lensFlare.attributesEnabled = false;
};
/*
* Render lens flares
* Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
* reads these back and calculates occlusion.
* Then _lensFlare.update_lensFlares() is called to re-position and
* update transparency of flares. Then they are rendered.
*
*/
this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
var flares = scene.__webglFlares,
nFlares = flares.length;
if ( ! nFlares ) return;
var tempPosition = new THREE.Vector3();
var invAspect = viewportHeight / viewportWidth,
halfViewportWidth = viewportWidth * 0.5,
halfViewportHeight = viewportHeight * 0.5;
var size = 16 / viewportHeight,
scale = new THREE.Vector2( size * invAspect, size );
var screenPosition = new THREE.Vector3( 1, 1, 0 ),
screenPositionPixels = new THREE.Vector2( 1, 1 );
var uniforms = _lensFlare.uniforms,
attributes = _lensFlare.attributes;
// set _lensFlare program and reset blending
_gl.useProgram( _lensFlare.program );
if ( ! _lensFlare.attributesEnabled ) {
_gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
_gl.enableVertexAttribArray( _lensFlare.attributes.uv );
_lensFlare.attributesEnabled = true;
}
// loop through all lens flares to update their occlusion and positions
// setup gl and common used attribs/unforms
_gl.uniform1i( uniforms.occlusionMap, 0 );
_gl.uniform1i( uniforms.map, 1 );
_gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
_gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
_gl.disable( _gl.CULL_FACE );
_gl.depthMask( false );
var i, j, jl, flare, sprite;
for ( i = 0; i < nFlares; i ++ ) {
size = 16 / viewportHeight;
scale.set( size * invAspect, size );
// calc object screen position
flare = flares[ i ];
tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
camera.matrixWorldInverse.multiplyVector3( tempPosition );
camera.projectionMatrix.multiplyVector3( tempPosition );
// setup arrays for gl programs
screenPosition.copy( tempPosition )
screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
// screen cull
if ( _lensFlare.hasVertexTexture || (
screenPositionPixels.x > 0 &&
screenPositionPixels.x < viewportWidth &&
screenPositionPixels.y > 0 &&
screenPositionPixels.y < viewportHeight ) ) {
// save current RGB to temp texture
_gl.activeTexture( _gl.TEXTURE1 );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
_gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
// render pink quad
_gl.uniform1i( uniforms.renderType, 0 );
_gl.uniform2f( uniforms.scale, scale.x, scale.y );
_gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
_gl.disable( _gl.BLEND );
_gl.enable( _gl.DEPTH_TEST );
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
// copy result to occlusionMap
_gl.activeTexture( _gl.TEXTURE0 );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
_gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
// restore graphics
_gl.uniform1i( uniforms.renderType, 1 );
_gl.disable( _gl.DEPTH_TEST );
_gl.activeTexture( _gl.TEXTURE1 );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
// update object positions
flare.positionScreen.copy( screenPosition )
if ( flare.customUpdateCallback ) {
flare.customUpdateCallback( flare );
} else {
flare.updateLensFlares();
}
// render flares
_gl.uniform1i( uniforms.renderType, 2 );
_gl.enable( _gl.BLEND );
for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
sprite = flare.lensFlares[ j ];
if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
screenPosition.x = sprite.x;
screenPosition.y = sprite.y;
screenPosition.z = sprite.z;
size = sprite.size * sprite.scale / viewportHeight;
scale.x = size * invAspect;
scale.y = size;
_gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
_gl.uniform2f( uniforms.scale, scale.x, scale.y );
_gl.uniform1f( uniforms.rotation, sprite.rotation );
_gl.uniform1f( uniforms.opacity, sprite.opacity );
_gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
_renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
_renderer.setTexture( sprite.texture, 1 );
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
}
}
}
}
// restore gl
_gl.enable( _gl.CULL_FACE );
_gl.enable( _gl.DEPTH_TEST );
_gl.depthMask( true );
};
function createProgram ( shader ) {
var program = _gl.createProgram();
var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
_gl.shaderSource( fragmentShader, shader.fragmentShader );
_gl.shaderSource( vertexShader, shader.vertexShader );
_gl.compileShader( fragmentShader );
_gl.compileShader( vertexShader );
_gl.attachShader( program, fragmentShader );
_gl.attachShader( program, vertexShader );
_gl.linkProgram( program );
return program;
};
};/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ShadowMapPlugin = function ( ) {
var _gl,
_renderer,
_depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
_frustum = new THREE.Frustum(),
_projScreenMatrix = new THREE.Matrix4(),
_min = new THREE.Vector3(),
_max = new THREE.Vector3();
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
var depthShader = THREE.ShaderLib[ "depthRGBA" ];
var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
_depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
_depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
_depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
_depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
_depthMaterial._shadowPass = true;
_depthMaterialMorph._shadowPass = true;
_depthMaterialSkin._shadowPass = true;
_depthMaterialMorphSkin._shadowPass = true;
};
this.render = function ( scene, camera ) {
if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
this.update( scene, camera );
};
this.update = function ( scene, camera ) {
var i, il, j, jl, n,
shadowMap, shadowMatrix, shadowCamera,
program, buffer, material,
webglObject, object, light,
renderList,
lights = [],
k = 0,
fog = null;
// set GL state for depth map
_gl.clearColor( 1, 1, 1, 1 );
_gl.disable( _gl.BLEND );
_gl.enable( _gl.CULL_FACE );
_gl.frontFace( _gl.CCW );
if ( _renderer.shadowMapCullFrontFaces ) {
_gl.cullFace( _gl.FRONT );
} else {
_gl.cullFace( _gl.BACK );
}
_renderer.setDepthTest( true );
// preprocess lights
// - skip lights that are not casting shadows
// - create virtual lights for cascaded shadow maps
for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
light = scene.__lights[ i ];
if ( ! light.castShadow ) continue;
if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
var virtualLight;
if ( ! light.shadowCascadeArray[ n ] ) {
virtualLight = createVirtualLight( light, n );
virtualLight.originalCamera = camera;
var gyro = new THREE.Gyroscope();
gyro.position = light.shadowCascadeOffset;
gyro.add( virtualLight );
gyro.add( virtualLight.target );
camera.add( gyro );
light.shadowCascadeArray[ n ] = virtualLight;
console.log( "Created virtualLight", virtualLight );
} else {
virtualLight = light.shadowCascadeArray[ n ];
}
updateVirtualLight( light, n );
lights[ k ] = virtualLight;
k ++;
}
} else {
lights[ k ] = light;
k ++;
}
}
// render depth map
for ( i = 0, il = lights.length; i < il; i ++ ) {
light = lights[ i ];
if ( ! light.shadowMap ) {
var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
light.shadowMatrix = new THREE.Matrix4();
}
if ( ! light.shadowCamera ) {
if ( light instanceof THREE.SpotLight ) {
light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
} else if ( light instanceof THREE.DirectionalLight ) {
light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
} else {
console.error( "Unsupported light type for shadow" );
continue;
}
scene.add( light.shadowCamera );
if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
}
if ( light.shadowCameraVisible && ! light.cameraHelper ) {
light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
light.shadowCamera.add( light.cameraHelper );
}
if ( light.isVirtual && virtualLight.originalCamera == camera ) {
updateShadowCamera( camera, light );
}
shadowMap = light.shadowMap;
shadowMatrix = light.shadowMatrix;
shadowCamera = light.shadowCamera;
shadowCamera.position.copy( light.matrixWorld.getPosition() );
shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
shadowCamera.updateMatrixWorld();
shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
if ( light.shadowCameraVisible ) light.cameraHelper.update();
// compute shadow matrix
shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0 );
shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
// update camera matrices and frustum
if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
_projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// render shadow map
_renderer.setRenderTarget( shadowMap );
_renderer.clear();
// set object matrices & frustum culling
renderList = scene.__webglObjects;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
webglObject.render = false;
if ( object.visible && object.castShadow ) {
if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
webglObject.render = true;
}
}
}
// render regular objects
var objectMaterial, useMorphing, useSkinning;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
// culling is overriden globally for all objects
// while rendering depth map
// need to deal with MeshFaceMaterial somehow
// in that case just use the first of geometry.materials for now
// (proper solution would require to break objects by materials
// similarly to regular rendering and then set corresponding
// depth materials per each chunk instead of just once per object)
objectMaterial = getObjectMaterial( object );
useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
if ( object.customDepthMaterial ) {
material = object.customDepthMaterial;
} else if ( useSkinning ) {
material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
} else if ( useMorphing ) {
material = _depthMaterialMorph;
} else {
material = _depthMaterial;
}
if ( buffer instanceof THREE.BufferGeometry ) {
_renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
} else {
_renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
}
}
}
// set matrices and render immediate objects
renderList = scene.__webglObjectsImmediate;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
if ( object.visible && object.castShadow ) {
object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
_renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
}
}
}
// restore GL state
var clearColor = _renderer.getClearColor(),
clearAlpha = _renderer.getClearAlpha();
_gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
_gl.enable( _gl.BLEND );
if ( _renderer.shadowMapCullFrontFaces ) {
_gl.cullFace( _gl.BACK );
}
};
function createVirtualLight( light, cascade ) {
var virtualLight = new THREE.DirectionalLight();
virtualLight.isVirtual = true;
virtualLight.onlyShadow = true;
virtualLight.castShadow = true;
virtualLight.shadowCameraNear = light.shadowCameraNear;
virtualLight.shadowCameraFar = light.shadowCameraFar;
virtualLight.shadowCameraLeft = light.shadowCameraLeft;
virtualLight.shadowCameraRight = light.shadowCameraRight;
virtualLight.shadowCameraBottom = light.shadowCameraBottom;
virtualLight.shadowCameraTop = light.shadowCameraTop;
virtualLight.shadowCameraVisible = light.shadowCameraVisible;
virtualLight.shadowDarkness = light.shadowDarkness;
virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
virtualLight.pointsWorld = [];
virtualLight.pointsFrustum = [];
var pointsWorld = virtualLight.pointsWorld,
pointsFrustum = virtualLight.pointsFrustum;
for ( var i = 0; i < 8; i ++ ) {
pointsWorld[ i ] = new THREE.Vector3();
pointsFrustum[ i ] = new THREE.Vector3();
}
var nearZ = light.shadowCascadeNearZ[ cascade ];
var farZ = light.shadowCascadeFarZ[ cascade ];
pointsFrustum[ 0 ].set( -1, -1, nearZ );
pointsFrustum[ 1 ].set( 1, -1, nearZ );
pointsFrustum[ 2 ].set( -1, 1, nearZ );
pointsFrustum[ 3 ].set( 1, 1, nearZ );
pointsFrustum[ 4 ].set( -1, -1, farZ );
pointsFrustum[ 5 ].set( 1, -1, farZ );
pointsFrustum[ 6 ].set( -1, 1, farZ );
pointsFrustum[ 7 ].set( 1, 1, farZ );
return virtualLight;
}
// Synchronize virtual light with the original light
function updateVirtualLight( light, cascade ) {
var virtualLight = light.shadowCascadeArray[ cascade ];
virtualLight.position.copy( light.position );
virtualLight.target.position.copy( light.target.position );
virtualLight.lookAt( virtualLight.target );
virtualLight.shadowCameraVisible = light.shadowCameraVisible;
virtualLight.shadowDarkness = light.shadowDarkness;
virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
var nearZ = light.shadowCascadeNearZ[ cascade ];
var farZ = light.shadowCascadeFarZ[ cascade ];
var pointsFrustum = virtualLight.pointsFrustum;
pointsFrustum[ 0 ].z = nearZ;
pointsFrustum[ 1 ].z = nearZ;
pointsFrustum[ 2 ].z = nearZ;
pointsFrustum[ 3 ].z = nearZ;
pointsFrustum[ 4 ].z = farZ;
pointsFrustum[ 5 ].z = farZ;
pointsFrustum[ 6 ].z = farZ;
pointsFrustum[ 7 ].z = farZ;
}
// Fit shadow camera's ortho frustum to camera frustum
function updateShadowCamera( camera, light ) {
var shadowCamera = light.shadowCamera,
pointsFrustum = light.pointsFrustum,
pointsWorld = light.pointsWorld;
_min.set( Infinity, Infinity, Infinity );
_max.set( -Infinity, -Infinity, -Infinity );
for ( var i = 0; i < 8; i ++ ) {
var p = pointsWorld[ i ];
p.copy( pointsFrustum[ i ] );
THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
shadowCamera.matrixWorldInverse.multiplyVector3( p );
if ( p.x < _min.x ) _min.x = p.x;
if ( p.x > _max.x ) _max.x = p.x;
if ( p.y < _min.y ) _min.y = p.y;
if ( p.y > _max.y ) _max.y = p.y;
if ( p.z < _min.z ) _min.z = p.z;
if ( p.z > _max.z ) _max.z = p.z;
}
shadowCamera.left = _min.x;
shadowCamera.right = _max.x;
shadowCamera.top = _max.y;
shadowCamera.bottom = _min.y;
// can't really fit near/far
//shadowCamera.near = _min.z;
//shadowCamera.far = _max.z;
shadowCamera.updateProjectionMatrix();
}
// For the moment just ignore objects that have multiple materials with different animation methods
// Only the first material will be taken into account for deciding which depth material to use for shadow maps
function getObjectMaterial( object ) {
return object.material instanceof THREE.MeshFaceMaterial ? object.geometry.materials[ 0 ] : object.material;
}
};
THREE.ShadowMapPlugin.__projector = new THREE.Projector();
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.SpritePlugin = function ( ) {
var _gl, _renderer, _sprite = {};
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
_sprite.vertices = new Float32Array( 8 + 8 );
_sprite.faces = new Uint16Array( 6 );
var i = 0;
_sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
_sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
_sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
_sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
_sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
_sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
_sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
_sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
i = 0;
_sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
_sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
_sprite.vertexBuffer = _gl.createBuffer();
_sprite.elementBuffer = _gl.createBuffer();
_gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
_sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
_sprite.attributes = {};
_sprite.uniforms = {};
_sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
_sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
_sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
_sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
_sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
_sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
_sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
_sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
_sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
_sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
_sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
_sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
_sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
_sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
_sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
_sprite.attributesEnabled = false;
};
this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
var sprites = scene.__webglSprites,
nSprites = sprites.length;
if ( ! nSprites ) return;
var attributes = _sprite.attributes,
uniforms = _sprite.uniforms;
var invAspect = viewportHeight / viewportWidth;
var halfViewportWidth = viewportWidth * 0.5,
halfViewportHeight = viewportHeight * 0.5;
var mergeWith3D = true;
// setup gl
_gl.useProgram( _sprite.program );
if ( ! _sprite.attributesEnabled ) {
_gl.enableVertexAttribArray( attributes.position );
_gl.enableVertexAttribArray( attributes.uv );
_sprite.attributesEnabled = true;
}
_gl.disable( _gl.CULL_FACE );
_gl.enable( _gl.BLEND );
_gl.depthMask( true );
_gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
_gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
_gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
_gl.activeTexture( _gl.TEXTURE0 );
_gl.uniform1i( uniforms.map, 0 );
// update positions and sort
var i, sprite, screenPosition, size, scale = [];
for( i = 0; i < nSprites; i ++ ) {
sprite = sprites[ i ];
if ( ! sprite.visible || sprite.opacity === 0 ) continue;
if( ! sprite.useScreenCoordinates ) {
sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
sprite.z = - sprite._modelViewMatrix.elements[14];
} else {
sprite.z = - sprite.position.z;
}
}
sprites.sort( painterSort );
// render all sprites
for( i = 0; i < nSprites; i ++ ) {
sprite = sprites[ i ];
if ( ! sprite.visible || sprite.opacity === 0 ) continue;
if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
if ( sprite.useScreenCoordinates ) {
_gl.uniform1i( uniforms.useScreenCoordinates, 1 );
_gl.uniform3f(
uniforms.screenPosition,
( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
Math.max( 0, Math.min( 1, sprite.position.z ) )
);
} else {
_gl.uniform1i( uniforms.useScreenCoordinates, 0 );
_gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
}
size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
scale[ 0 ] = size * invAspect * sprite.scale.x;
scale[ 1 ] = size * sprite.scale.y;
_gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
_gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
_gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
_gl.uniform1f( uniforms.opacity, sprite.opacity );
_gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
_gl.uniform1f( uniforms.rotation, sprite.rotation );
_gl.uniform2fv( uniforms.scale, scale );
if ( sprite.mergeWith3D && !mergeWith3D ) {
_gl.enable( _gl.DEPTH_TEST );
mergeWith3D = true;
} else if ( ! sprite.mergeWith3D && mergeWith3D ) {
_gl.disable( _gl.DEPTH_TEST );
mergeWith3D = false;
}
_renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
_renderer.setTexture( sprite.map, 0 );
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
}
}
// restore gl
_gl.enable( _gl.CULL_FACE );
_gl.enable( _gl.DEPTH_TEST );
_gl.depthMask( true );
};
function createProgram ( shader ) {
var program = _gl.createProgram();
var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
_gl.shaderSource( fragmentShader, shader.fragmentShader );
_gl.shaderSource( vertexShader, shader.vertexShader );
_gl.compileShader( fragmentShader );
_gl.compileShader( vertexShader );
_gl.attachShader( program, fragmentShader );
_gl.attachShader( program, vertexShader );
_gl.linkProgram( program );
return program;
};
function painterSort ( a, b ) {
return b.z - a.z;
};
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.DepthPassPlugin = function ( ) {
this.enabled = false;
this.renderTarget = null;
var _gl,
_renderer,
_depthMaterial, _depthMaterialMorph,
_frustum = new THREE.Frustum(),
_projScreenMatrix = new THREE.Matrix4();
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
var depthShader = THREE.ShaderLib[ "depthRGBA" ];
var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
_depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
_depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
_depthMaterial._shadowPass = true;
_depthMaterialMorph._shadowPass = true;
};
this.render = function ( scene, camera ) {
if ( ! this.enabled ) return;
this.update( scene, camera );
};
this.update = function ( scene, camera ) {
var i, il, j, jl, n,
program, buffer, material,
webglObject, object, light,
renderList,
fog = null;
// set GL state for depth map
_gl.clearColor( 1, 1, 1, 1 );
_gl.disable( _gl.BLEND );
_renderer.setDepthTest( true );
// update scene
if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
// update camera matrices and frustum
if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
_projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// render depth map
_renderer.setRenderTarget( this.renderTarget );
_renderer.clear();
// set object matrices & frustum culling
renderList = scene.__webglObjects;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
webglObject.render = false;
if ( object.visible ) {
if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
//object.matrixWorld.flattenToArray( object._modelMatrixArray );
object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
webglObject.render = true;
}
}
}
// render regular objects
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
if ( object.material ) _renderer.setMaterialFaces( object.material );
if ( object.customDepthMaterial ) {
material = object.customDepthMaterial;
} else if ( object.geometry.morphTargets.length ) {
material = _depthMaterialMorph;
} else {
material = _depthMaterial;
}
if ( buffer instanceof THREE.BufferGeometry ) {
_renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
} else {
_renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
}
}
}
// set matrices and render immediate objects
renderList = scene.__webglObjectsImmediate;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
if ( object.visible && object.castShadow ) {
/*
if ( object.matrixAutoUpdate ) {
object.matrixWorld.flattenToArray( object._modelMatrixArray );
}
*/
object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
_renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
}
}
// restore GL state
var clearColor = _renderer.getClearColor(),
clearAlpha = _renderer.getClearAlpha();
_gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
_gl.enable( _gl.BLEND );
};
};
/**
* @author mikael emtinger / http://gomo.se/
*
*/
THREE.ShaderFlares = {
'lensFlareVertexTexture': {
vertexShader: [
"uniform vec3 screenPosition;",
"uniform vec2 scale;",
"uniform float rotation;",
"uniform int renderType;",
"uniform sampler2D occlusionMap;",
"attribute vec2 position;",
"attribute vec2 uv;",
"varying vec2 vUV;",
"varying float vVisibility;",
"void main() {",
"vUV = uv;",
"vec2 pos = position;",
"if( renderType == 2 ) {",
"vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
"texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
"texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
"texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
"texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
"texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
"texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
"texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
"texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
"vVisibility = ( visibility.r / 9.0 ) *",
"( 1.0 - visibility.g / 9.0 ) *",
"( visibility.b / 9.0 ) *",
"( 1.0 - visibility.a / 9.0 );",
"pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
"pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
"}",
"gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"precision mediump float;",
"uniform sampler2D map;",
"uniform float opacity;",
"uniform int renderType;",
"uniform vec3 color;",
"varying vec2 vUV;",
"varying float vVisibility;",
"void main() {",
// pink square
"if( renderType == 0 ) {",
"gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
// restore
"} else if( renderType == 1 ) {",
"gl_FragColor = texture2D( map, vUV );",
// flare
"} else {",
"vec4 texture = texture2D( map, vUV );",
"texture.a *= opacity * vVisibility;",
"gl_FragColor = texture;",
"gl_FragColor.rgb *= color;",
"}",
"}"
].join( "\n" )
},
'lensFlare': {
vertexShader: [
"uniform vec3 screenPosition;",
"uniform vec2 scale;",
"uniform float rotation;",
"uniform int renderType;",
"attribute vec2 position;",
"attribute vec2 uv;",
"varying vec2 vUV;",
"void main() {",
"vUV = uv;",
"vec2 pos = position;",
"if( renderType == 2 ) {",
"pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
"pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
"}",
"gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"precision mediump float;",
"uniform sampler2D map;",
"uniform sampler2D occlusionMap;",
"uniform float opacity;",
"uniform int renderType;",
"uniform vec3 color;",
"varying vec2 vUV;",
"void main() {",
// pink square
"if( renderType == 0 ) {",
"gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
// restore
"} else if( renderType == 1 ) {",
"gl_FragColor = texture2D( map, vUV );",
// flare
"} else {",
"float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
"texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
"texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
"texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
"visibility = ( 1.0 - visibility / 4.0 );",
"vec4 texture = texture2D( map, vUV );",
"texture.a *= opacity * visibility;",
"gl_FragColor = texture;",
"gl_FragColor.rgb *= color;",
"}",
"}"
].join( "\n" )
}
};
/**
* @author mikael emtinger / http://gomo.se/
*
*/
THREE.ShaderSprite = {
'sprite': {
vertexShader: [
"uniform int useScreenCoordinates;",
"uniform int affectedByDistance;",
"uniform vec3 screenPosition;",
"uniform mat4 modelViewMatrix;",
"uniform mat4 projectionMatrix;",
"uniform float rotation;",
"uniform vec2 scale;",
"uniform vec2 alignment;",
"uniform vec2 uvOffset;",
"uniform vec2 uvScale;",
"attribute vec2 position;",
"attribute vec2 uv;",
"varying vec2 vUV;",
"void main() {",
"vUV = uvOffset + uv * uvScale;",
"vec2 alignedPosition = position + alignment;",
"vec2 rotatedPosition;",
"rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
"rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
"vec4 finalPosition;",
"if( useScreenCoordinates != 0 ) {",
"finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
"} else {",
"finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
"finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
"}",
"gl_Position = finalPosition;",
"}"
].join( "\n" ),
fragmentShader: [
"precision mediump float;",
"uniform vec3 color;",
"uniform sampler2D map;",
"uniform float opacity;",
"varying vec2 vUV;",
"void main() {",
"vec4 texture = texture2D( map, vUV );",
"gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
"}"
].join( "\n" )
}
};
| LaurensRietveld/cdnjs | ajax/libs/three.js/r52/three.js | JavaScript | mit | 785,469 |
/**
Address editable input.
Internally value stored as {city: "Moscow", street: "Lenina", building: "15"}
@class address
@extends abstractinput
@final
@example
<a href="#" id="address" data-type="address" data-pk="1">awesome</a>
<script>
$(function(){
$('#address').editable({
url: '/post',
title: 'Enter city, street and building #',
value: {
city: "Moscow",
street: "Lenina",
building: "15"
}
});
});
</script>
**/
(function ($) {
var Address = function (options) {
this.init('address', options, Address.defaults);
};
//inherit from Abstract input
$.fn.editableutils.inherit(Address, $.fn.editabletypes.abstractinput);
$.extend(Address.prototype, {
/**
Renders input from tpl
@method render()
**/
render: function() {
this.$input = this.$tpl.find('input');
},
/**
Default method to show value in element. Can be overwritten by display option.
@method value2html(value, element)
**/
value2html: function(value, element) {
if(!value) {
$(element).empty();
return;
}
var html = $('<div>').text(value.city).html() + ', ' + $('<div>').text(value.street).html() + ' st., bld. ' + $('<div>').text(value.building).html();
$(element).html(html);
},
/**
Gets value from element's html
@method html2value(html)
**/
html2value: function(html) {
/*
you may write parsing method to get value by element's html
e.g. "Moscow, st. Lenina, bld. 15" => {city: "Moscow", street: "Lenina", building: "15"}
but for complex structures it's not recommended.
Better set value directly via javascript, e.g.
editable({
value: {
city: "Moscow",
street: "Lenina",
building: "15"
}
});
*/
return null;
},
/**
Converts value to string.
It is used in internal comparing (not for sending to server).
@method value2str(value)
**/
value2str: function(value) {
var str = '';
if(value) {
for(var k in value) {
str = str + k + ':' + value[k] + ';';
}
}
return str;
},
/*
Converts string to value. Used for reading value from 'data-value' attribute.
@method str2value(str)
*/
str2value: function(str) {
/*
this is mainly for parsing value defined in data-value attribute.
If you will always set value by javascript, no need to overwrite it
*/
return str;
},
/**
Sets value of input.
@method value2input(value)
@param {mixed} value
**/
value2input: function(value) {
if(!value) {
return;
}
this.$input.filter('[name="city"]').val(value.city);
this.$input.filter('[name="street"]').val(value.street);
this.$input.filter('[name="building"]').val(value.building);
},
/**
Returns value of input.
@method input2value()
**/
input2value: function() {
return {
city: this.$input.filter('[name="city"]').val(),
street: this.$input.filter('[name="street"]').val(),
building: this.$input.filter('[name="building"]').val()
};
},
/**
Activates input: sets focus on the first field.
@method activate()
**/
activate: function() {
this.$input.filter('[name="city"]').focus();
},
/**
Attaches handler to submit form in case of 'showbuttons=false' mode
@method autosubmit()
**/
autosubmit: function() {
this.$input.keydown(function (e) {
if (e.which === 13) {
$(this).closest('form').submit();
}
});
}
});
Address.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
tpl: '<div class="editable-address"><label><span>City: </span><input type="text" name="city" class="input-small"></label></div>'+
'<div class="editable-address"><label><span>Street: </span><input type="text" name="street" class="input-small"></label></div>'+
'<div class="editable-address"><label><span>Building: </span><input type="text" name="building" class="input-mini"></label></div>',
inputclass: ''
});
$.fn.editabletypes.address = Address;
}(window.jQuery)); | KZeni/cdnjs | ajax/libs/x-editable/1.4.2/inputs-ext/address/address.js | JavaScript | mit | 5,116 |
webshims.register('form-number-date-api', function($, webshims, window, document, undefined, options){
"use strict";
if(!webshims.addInputType){
webshims.error("you can not call forms-ext feature after calling forms feature. call both at once instead: $.webshims.polyfill('forms forms-ext')");
}
if(!webshims.getStep){
webshims.getStep = function(elem, type){
var step = $.attr(elem, 'step');
if(step === 'any'){
return step;
}
type = type || getType(elem);
if(!typeModels[type] || !typeModels[type].step){
return step;
}
step = typeProtos.number.asNumber(step);
return ((!isNaN(step) && step > 0) ? step : typeModels[type].step) * (typeModels[type].stepScaleFactor || 1);
};
}
if(!webshims.addMinMaxNumberToCache){
webshims.addMinMaxNumberToCache = function(attr, elem, cache){
if (!(attr+'AsNumber' in cache)) {
cache[attr+'AsNumber'] = typeModels[cache.type].asNumber(elem.attr(attr));
if(isNaN(cache[attr+'AsNumber']) && (attr+'Default' in typeModels[cache.type])){
cache[attr+'AsNumber'] = typeModels[cache.type][attr+'Default'];
}
}
};
}
var nan = parseInt('NaN', 10),
doc = document,
typeModels = webshims.inputTypes,
isNumber = function(string){
return (typeof string == 'number' || (string && string == string * 1));
},
supportsType = function(type){
return ($('<input type="'+type+'" />').prop('type') === type);
},
getType = function(elem){
return (elem.getAttribute('type') || '').toLowerCase();
},
isDateTimePart = function(string){
return (string && !(isNaN(string * 1)));
},
addMinMaxNumberToCache = webshims.addMinMaxNumberToCache,
addleadingZero = function(val, len){
val = ''+val;
len = len - val.length;
for(var i = 0; i < len; i++){
val = '0'+val;
}
return val;
},
EPS = 1e-7,
typeBugs = webshims.bugs.bustedValidity
;
webshims.addValidityRule('stepMismatch', function(input, val, cache, validityState){
if(val === ''){return false;}
if(!('type' in cache)){
cache.type = getType(input[0]);
}
if(cache.type == 'week'){return false;}
var base, attrVal;
var ret = (validityState || {}).stepMismatch || false;
if(typeModels[cache.type] && typeModels[cache.type].step){
if( !('step' in cache) ){
cache.step = webshims.getStep(input[0], cache.type);
}
if(cache.step == 'any'){return false;}
if(!('valueAsNumber' in cache)){
cache.valueAsNumber = typeModels[cache.type].asNumber( val );
}
if(isNaN(cache.valueAsNumber)){return false;}
addMinMaxNumberToCache('min', input, cache);
base = cache.minAsNumber;
if(isNaN(base) && (attrVal = input.prop('defaultValue'))){
base = typeModels[cache.type].asNumber( attrVal );
}
if(isNaN(base)){
base = typeModels[cache.type].stepBase || 0;
}
ret = Math.abs((cache.valueAsNumber - base) % cache.step);
ret = !( ret <= EPS || Math.abs(ret - cache.step) <= EPS );
}
return ret;
});
[{name: 'rangeOverflow', attr: 'max', factor: 1}, {name: 'rangeUnderflow', attr: 'min', factor: -1}].forEach(function(data, i){
webshims.addValidityRule(data.name, function(input, val, cache, validityState) {
var ret = (validityState || {})[data.name] || false;
if(val === ''){return ret;}
if (!('type' in cache)) {
cache.type = getType(input[0]);
}
if (typeModels[cache.type] && typeModels[cache.type].asNumber) {
if(!('valueAsNumber' in cache)){
cache.valueAsNumber = typeModels[cache.type].asNumber( val );
}
if(isNaN(cache.valueAsNumber)){
return false;
}
addMinMaxNumberToCache(data.attr, input, cache);
if(isNaN(cache[data.attr+'AsNumber'])){
return ret;
}
ret = ( cache[data.attr+'AsNumber'] * data.factor < cache.valueAsNumber * data.factor - EPS );
}
return ret;
});
});
webshims.reflectProperties(['input'], ['max', 'min', 'step']);
//IDLs and methods, that aren't part of constrain validation, but strongly tight to it
var valueAsNumberDescriptor = webshims.defineNodeNameProperty('input', 'valueAsNumber', {
prop: {
get: function(){
var elem = this;
var type = getType(elem);
var ret = (typeModels[type] && typeModels[type].asNumber) ?
typeModels[type].asNumber($.prop(elem, 'value')) :
(valueAsNumberDescriptor.prop._supget && valueAsNumberDescriptor.prop._supget.apply(elem, arguments));
if(ret == null){
ret = nan;
}
return ret;
},
set: function(val){
var elem = this;
var type = getType(elem);
if(typeModels[type] && typeModels[type].numberToString){
//is NaN a number?
if(isNaN(val)){
$.prop(elem, 'value', '');
return;
}
var set = typeModels[type].numberToString(val);
if(set !== false){
$.prop(elem, 'value', set);
} else {
webshims.error('INVALID_STATE_ERR: DOM Exception 11');
}
} else if(valueAsNumberDescriptor.prop._supset) {
valueAsNumberDescriptor.prop._supset.apply(elem, arguments);
}
}
}
});
var valueAsDateDescriptor = webshims.defineNodeNameProperty('input', 'valueAsDate', {
prop: {
get: function(){
var elem = this;
var type = getType(elem);
return (typeModels[type] && typeModels[type].asDate && !typeModels[type].noAsDate) ?
typeModels[type].asDate($.prop(elem, 'value')) :
valueAsDateDescriptor.prop._supget && valueAsDateDescriptor.prop._supget.call(elem) || null;
},
set: function(value){
var elem = this;
var type = getType(elem);
if(typeModels[type] && typeModels[type].dateToString && !typeModels[type].noAsDate){
if(value === null){
$.prop(elem, 'value', '');
return '';
}
var set = typeModels[type].dateToString(value);
if(set !== false){
$.prop(elem, 'value', set);
return set;
} else {
webshims.error('INVALID_STATE_ERR: DOM Exception 11');
}
} else {
return valueAsDateDescriptor.prop._supset && valueAsDateDescriptor.prop._supset.apply(elem, arguments) || null;
}
}
}
});
$.each({stepUp: 1, stepDown: -1}, function(name, stepFactor){
var stepDescriptor = webshims.defineNodeNameProperty('input', name, {
prop: {
value: function(factor){
var step, val, valModStep, alignValue, cache, base, attrVal;
var type = getType(this);
if(typeModels[type] && typeModels[type].asNumber){
cache = {type: type};
if(!factor){
factor = 1;
webshims.warn("you should always use a factor for stepUp/stepDown");
}
factor *= stepFactor;
step = webshims.getStep(this, type);
if(step == 'any'){
webshims.info("step is 'any' can't apply stepUp/stepDown");
throw('invalid state error');
}
webshims.addMinMaxNumberToCache('min', $(this), cache);
webshims.addMinMaxNumberToCache('max', $(this), cache);
val = $.prop(this, 'valueAsNumber');
if(factor > 0 && !isNaN(cache.minAsNumber) && (isNaN(val) || cache.minAsNumber > val)){
$.prop(this, 'valueAsNumber', cache.minAsNumber);
return;
} else if(factor < 0 && !isNaN(cache.maxAsNumber) && (isNaN(val) || cache.maxAsNumber < val)){
$.prop(this, 'valueAsNumber', cache.maxAsNumber);
return;
}
if(isNaN(val)){
val = 0;
}
base = cache.minAsNumber;
if(isNaN(base) && (attrVal = $.prop(this, 'defaultValue'))){
base = typeModels[type].asNumber( attrVal );
}
if(!base){
base = 0;
}
step *= factor;
val = (val + step).toFixed(5) * 1;
valModStep = (val - base) % step;
if ( valModStep && (Math.abs(valModStep) > EPS) ) {
alignValue = val - valModStep;
alignValue += ( valModStep > 0 ) ? step : ( -step );
val = alignValue.toFixed(5) * 1;
}
if( (!isNaN(cache.maxAsNumber) && val > cache.maxAsNumber) || (!isNaN(cache.minAsNumber) && val < cache.minAsNumber) ){
webshims.info("max/min overflow can't apply stepUp/stepDown");
return;
}
$.prop(this, 'valueAsNumber', val);
} else if(stepDescriptor.prop && stepDescriptor.prop._supvalue){
return stepDescriptor.prop._supvalue.apply(this, arguments);
} else {
webshims.info("no step method for type: "+ type);
throw('invalid state error');
}
}
}
});
});
/*
* ToDO: WEEK
*/
// var getWeek = function(date){
// var time;
// var checkDate = new Date(date.getTime());
//
// checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
//
// time = checkDate.getTime();
// checkDate.setMonth(0);
// checkDate.setDate(1);
// return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
// };
//
// var setWeek = function(year, week){
// var date = new Date(year, 0, 1);
//
// week = (week - 1) * 86400000 * 7;
// date = new Date(date.getTime() + week);
// date.setDate(date.getDate() + 1 - (date.getDay() || 7));
// return date;
// };
var typeProtos = {
number: {
bad: function(val){
return !(isNumber(val));
},
step: 1,
//stepBase: 0, 0 = default
stepScaleFactor: 1,
asNumber: function(str){
return (isNumber(str)) ? str * 1 : nan;
},
numberToString: function(num){
return (isNumber(num)) ? num : false;
}
},
range: {
minDefault: 0,
maxDefault: 100
},
color: {
bad: (function(){
var cReg = /^\u0023[a-f0-9]{6}$/;
return function(val){
return (!val || val.length != 7 || !(cReg.test(val)));
};
})()
},
date: {
bad: function(val){
if(!val || !val.split || !(/\d$/.test(val))){return true;}
var i;
var valA = val.split(/\u002D/);
if(valA.length !== 3){return true;}
var ret = false;
if(valA[0].length < 4 || valA[1].length != 2 || valA[1] > 12 || valA[2].length != 2 || valA[2] > 33){
ret = true;
} else {
for(i = 0; i < 3; i++){
if(!isDateTimePart(valA[i])){
ret = true;
break;
}
}
}
return ret || (val !== this.dateToString( this.asDate(val, true) ) );
},
step: 1,
//stepBase: 0, 0 = default
stepScaleFactor: 86400000,
asDate: function(val, _noMismatch){
if(!_noMismatch && this.bad(val)){
return null;
}
return new Date(this.asNumber(val, true));
},
asNumber: function(str, _noMismatch){
var ret = nan;
if(_noMismatch || !this.bad(str)){
str = str.split(/\u002D/);
ret = Date.UTC(str[0], str[1] - 1, str[2]);
}
return ret;
},
numberToString: function(num){
return (isNumber(num)) ? this.dateToString(new Date( num * 1)) : false;
},
dateToString: function(date){
return (date && date.getFullYear) ? addleadingZero(date.getUTCFullYear(), 4) +'-'+ addleadingZero(date.getUTCMonth()+1, 2) +'-'+ addleadingZero(date.getUTCDate(), 2) : false;
}
},
/*
* ToDO: WEEK
*/
// week: {
// bad: function(val){
// if(!val || !val.split){return true;}
// var valA = val.split('-W');
// var ret = true;
// if(valA.length == 2 && valA[0].length > 3 && valA.length == 2){
// ret = this.dateToString(setWeek(valA[0], valA[1])) != val;
// }
// return ret;
// },
// step: 1,
// stepScaleFactor: 604800000,
// stepBase: -259200000,
// asDate: function(str, _noMismatch){
// var ret = null;
// if(_noMismatch || !this.bad(str)){
// ret = str.split('-W');
// ret = setWeek(ret[0], ret[1]);
// }
// return ret;
// },
// asNumber: function(str, _noMismatch){
// var ret = nan;
// var date = this.asDate(str, _noMismatch);
// if(date && date.getUTCFullYear){
// ret = date.getTime();
// }
// return ret;
// },
// dateToString: function(date){
// var week, checkDate;
// var ret = false;
// if(date && date.getFullYear){
// week = getWeek(date);
// if(week == 1){
// checkDate = new Date(date.getTime());
// checkDate.setDate(checkDate.getDate() + 7);
// date.setUTCFullYear(checkDate.getUTCFullYear());
// }
// ret = addleadingZero(date.getUTCFullYear(), 4) +'-W'+addleadingZero(week, 2);
// }
// return ret;
// },
// numberToString: function(num){
// return (isNumber(num)) ? this.dateToString(new Date( num * 1)) : false;
// }
// },
time: {
bad: function(val, _getParsed){
if(!val || !val.split || !(/\d$/.test(val))){return true;}
val = val.split(/\u003A/);
if(val.length < 2 || val.length > 3){return true;}
var ret = false,
sFraction;
if(val[2]){
val[2] = val[2].split(/\u002E/);
sFraction = parseInt(val[2][1], 10);
val[2] = val[2][0];
}
$.each(val, function(i, part){
if(!isDateTimePart(part) || part.length !== 2){
ret = true;
return false;
}
});
if(ret){return true;}
if(val[0] > 23 || val[0] < 0 || val[1] > 59 || val[1] < 0){
return true;
}
if(val[2] && (val[2] > 59 || val[2] < 0 )){
return true;
}
if(sFraction && isNaN(sFraction)){
return true;
}
if(sFraction){
if(sFraction < 100){
sFraction *= 100;
} else if(sFraction < 10){
sFraction *= 10;
}
}
return (_getParsed === true) ? [val, sFraction] : false;
},
step: 60,
stepBase: 0,
stepScaleFactor: 1000,
asDate: function(val){
val = new Date(this.asNumber(val));
return (isNaN(val)) ? null : val;
},
asNumber: function(val){
var ret = nan;
val = this.bad(val, true);
if(val !== true){
ret = Date.UTC('1970', 0, 1, val[0][0], val[0][1], val[0][2] || 0);
if(val[1]){
ret += val[1];
}
}
return ret;
},
dateToString: function(date){
if(date && date.getUTCHours){
var str = addleadingZero(date.getUTCHours(), 2) +':'+ addleadingZero(date.getUTCMinutes(), 2),
tmp = date.getSeconds()
;
if(tmp != "0"){
str += ':'+ addleadingZero(tmp, 2);
}
tmp = date.getUTCMilliseconds();
if(tmp != "0"){
str += '.'+ addleadingZero(tmp, 3);
}
return str;
} else {
return false;
}
}
},
month: {
bad: function(val){
return typeProtos.date.bad(val+'-01');
},
step: 1,
stepScaleFactor: false,
//stepBase: 0, 0 = default
asDate: function(val){
return new Date(typeProtos.date.asNumber(val+'-01'));
},
asNumber: function(val){
//1970-01
var ret = nan;
if(val && !this.bad(val)){
val = val.split(/\u002D/);
val[0] = (val[0] * 1) - 1970;
val[1] = (val[1] * 1) - 1;
ret = (val[0] * 12) + val[1];
}
return ret;
},
numberToString: function(num){
var mod;
var ret = false;
if(isNumber(num)){
mod = (num % 12);
num = ((num - mod) / 12) + 1970;
mod += 1;
if(mod < 1){
num -= 1;
mod += 12;
}
ret = addleadingZero(num, 4)+'-'+addleadingZero(mod, 2);
}
return ret;
},
dateToString: function(date){
if(date && date.getUTCHours){
var str = typeProtos.date.dateToString(date);
return (str.split && (str = str.split(/\u002D/))) ? str[0]+'-'+str[1] : false;
} else {
return false;
}
}
}
,'datetime-local': {
bad: function(val, _getParsed){
if(!val || !val.split || (val+'special').split(/\u0054/).length !== 2){return true;}
val = val.split(/\u0054/);
return ( typeProtos.date.bad(val[0]) || typeProtos.time.bad(val[1], _getParsed) );
},
noAsDate: true,
asDate: function(val){
val = new Date(this.asNumber(val));
return (isNaN(val)) ? null : val;
},
asNumber: function(val){
var ret = nan;
var time = this.bad(val, true);
if(time !== true){
val = val.split(/\u0054/)[0].split(/\u002D/);
ret = Date.UTC(val[0], val[1] - 1, val[2], time[0][0], time[0][1], time[0][2] || 0);
if(time[1]){
ret += time[1];
}
}
return ret;
},
dateToString: function(date, _getParsed){
return typeProtos.date.dateToString(date) +'T'+ typeProtos.time.dateToString(date, _getParsed);
}
}
};
if(typeBugs || !supportsType('range') || !supportsType('time') || !supportsType('month') || !supportsType('datetime-local')){
typeProtos.range = $.extend({}, typeProtos.number, typeProtos.range);
typeProtos.time = $.extend({}, typeProtos.date, typeProtos.time);
typeProtos.month = $.extend({}, typeProtos.date, typeProtos.month);
typeProtos['datetime-local'] = $.extend({}, typeProtos.date, typeProtos.time, typeProtos['datetime-local']);
}
//
['number', 'month', 'range', 'date', 'time', 'color', 'datetime-local'].forEach(function(type){
if(typeBugs || !supportsType(type)){
webshims.addInputType(type, typeProtos[type]);
}
});
if($('<input />').prop('labels') == null){
webshims.defineNodeNamesProperty('button, input, keygen, meter, output, progress, select, textarea', 'labels', {
prop: {
get: function(){
if(this.type == 'hidden'){return null;}
var id = this.id;
var labels = $(this)
.closest('label')
.filter(function(){
var hFor = (this.attributes['for'] || {});
return (!hFor.specified || hFor.value == id);
})
;
if(id) {
labels = labels.add('label[for="'+ id +'"]');
}
return labels.get();
},
writeable: false
}
});
}
});
;webshims.register('form-datalist', function($, webshims, window, document, undefined, options){
"use strict";
var lazyLoad = function(name){
if(!name || typeof name != 'string'){
name = 'DOM';
}
if(!lazyLoad[name+'Loaded']){
lazyLoad[name+'Loaded'] = true;
webshims.ready(name, function(){
webshims.loader.loadList(['form-datalist-lazy']);
});
}
};
var noDatalistSupport = {
submit: 1,
button: 1,
reset: 1,
hidden: 1,
range: 1,
date: 1,
month: 1
};
if(webshims.modules["form-number-date-ui"].loaded){
$.extend(noDatalistSupport, {
number: 1,
time: 1
});
}
/*
* implement propType "element" currently only used for list-attribute (will be moved to dom-extend, if needed)
*/
webshims.propTypes.element = function(descs, name){
webshims.createPropDefault(descs, 'attr');
if(descs.prop){return;}
descs.prop = {
get: function(){
var elem = $.attr(this, name);
if(elem){
elem = document.getElementById(elem);
if(elem && descs.propNodeName && !$.nodeName(elem, descs.propNodeName)){
elem = null;
}
}
return elem || null;
},
writeable: false
};
};
/*
* Implements datalist element and list attribute
*/
(function(){
var formsCFG = webshims.cfg.forms;
var listSupport = webshims.support.datalist;
if(listSupport && !formsCFG.customDatalist){return;}
var initializeDatalist = function(){
var updateDatlistAndOptions = function(){
var id;
if(!$.data(this, 'datalistWidgetData') && (id = $.prop(this, 'id'))){
$('input[list="'+ id +'"], input[data-wslist="'+ id +'"]').eq(0).attr('list', id);
} else {
$(this).triggerHandler('updateDatalist');
}
};
var inputListProto = {
//override autocomplete
autocomplete: {
attr: {
get: function(){
var elem = this;
var data = $.data(elem, 'datalistWidget');
if(data){
return data._autocomplete;
}
return ('autocomplete' in elem) ? elem.autocomplete : elem.getAttribute('autocomplete');
},
set: function(value){
var elem = this;
var data = $.data(elem, 'datalistWidget');
if(data){
data._autocomplete = value;
if(value == 'off'){
data.hideList();
}
} else {
if('autocomplete' in elem){
elem.autocomplete = value;
} else {
elem.setAttribute('autocomplete', value);
}
}
}
}
}
};
if(listSupport){
//options only return options, if option-elements are rooted: but this makes this part of HTML5 less backwards compatible
if(!($('<datalist><select><option></option></select></datalist>').prop('options') || []).length ){
webshims.defineNodeNameProperty('datalist', 'options', {
prop: {
writeable: false,
get: function(){
var options = this.options || [];
if(!options.length){
var elem = this;
var select = $('select', elem);
if(select[0] && select[0].options && select[0].options.length){
options = select[0].options;
}
}
return options;
}
}
});
}
inputListProto.list = {
attr: {
get: function(){
var val = webshims.contentAttr(this, 'list');
if(val != null){
$.data(this, 'datalistListAttr', val);
if(!noDatalistSupport[$.prop(this, 'type')] && !noDatalistSupport[$.attr(this, 'type')]){
this.removeAttribute('list');
}
} else {
val = $.data(this, 'datalistListAttr');
}
return (val == null) ? undefined : val;
},
set: function(value){
var elem = this;
$.data(elem, 'datalistListAttr', value);
if (!noDatalistSupport[$.prop(this, 'type')] && !noDatalistSupport[$.attr(this, 'type')]) {
webshims.objectCreate(shadowListProto, undefined, {
input: elem,
id: value,
datalist: $.prop(elem, 'list')
});
elem.setAttribute('data-wslist', value);
} else {
elem.setAttribute('list', value);
}
$(elem).triggerHandler('listdatalistchange');
}
},
initAttr: true,
reflect: true,
propType: 'element',
propNodeName: 'datalist'
};
} else {
webshims.defineNodeNameProperties('input', {
list: {
attr: {
get: function(){
var val = webshims.contentAttr(this, 'list');
return (val == null) ? undefined : val;
},
set: function(value){
var elem = this;
webshims.contentAttr(elem, 'list', value);
webshims.objectCreate(options.shadowListProto, undefined, {input: elem, id: value, datalist: $.prop(elem, 'list')});
$(elem).triggerHandler('listdatalistchange');
}
},
initAttr: true,
reflect: true,
propType: 'element',
propNodeName: 'datalist'
}
});
}
webshims.defineNodeNameProperties('input', inputListProto);
webshims.addReady(function(context, contextElem){
contextElem
.filter('datalist > select, datalist, datalist > option, datalist > select > option')
.closest('datalist')
.each(updateDatlistAndOptions)
;
});
};
/*
* ShadowList
*/
var shadowListProto = {
_create: function(opts){
if(noDatalistSupport[$.prop(opts.input, 'type')] || noDatalistSupport[$.attr(opts.input, 'type')]){return;}
var datalist = opts.datalist;
var data = $.data(opts.input, 'datalistWidget');
var that = this;
if(datalist && data && data.datalist !== datalist){
data.datalist = datalist;
data.id = opts.id;
$(data.datalist)
.off('updateDatalist.datalistWidget')
.on('updateDatalist.datalistWidget', $.proxy(data, '_resetListCached'))
;
data._resetListCached();
return;
} else if(!datalist){
if(data){
data.destroy();
}
return;
} else if(data && data.datalist === datalist){
return;
}
this.datalist = datalist;
this.id = opts.id;
this.hasViewableData = true;
this._autocomplete = $.attr(opts.input, 'autocomplete');
$.data(opts.input, 'datalistWidget', this);
$.data(datalist, 'datalistWidgetData', this);
lazyLoad('WINDOWLOAD');
if(webshims.isReady('form-datalist-lazy')){
if(window.QUnit){
that._lazyCreate(opts);
} else {
setTimeout(function(){
that._lazyCreate(opts);
}, 9);
}
} else {
$(opts.input).one('focus', lazyLoad);
webshims.ready('form-datalist-lazy', function(){
if(!that._destroyed){
that._lazyCreate(opts);
}
});
}
},
destroy: function(e){
var input;
var autocomplete = $.attr(this.input, 'autocomplete');
$(this.input)
.off('.datalistWidget')
.removeData('datalistWidget')
;
this.shadowList.remove();
$(document).off('.datalist'+this.id);
$(window).off('.datalist'+this.id);
if(this.input.form && this.input.id){
$(this.input.form).off('submit.datalistWidget'+this.input.id);
}
this.input.removeAttribute('aria-haspopup');
if(autocomplete === undefined){
this.input.removeAttribute('autocomplete');
} else {
$(this.input).attr('autocomplete', autocomplete);
}
if(e && e.type == 'beforeunload'){
input = this.input;
setTimeout(function(){
$.attr(input, 'list', $.attr(input, 'list'));
}, 9);
}
this._destroyed = true;
}
};
webshims.loader.addModule('form-datalist-lazy', {
noAutoCallback: true,
options: $.extend(options, {shadowListProto: shadowListProto})
});
if(!options.list){
options.list = {};
}
//init datalist update
initializeDatalist();
})();
});
| holtkamp/cdnjs | ajax/libs/webshim/1.14.4-RC3/dev/shims/combos/33.js | JavaScript | mit | 25,271 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/SansSerif/Regular/CombDiacritMarks.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({MathJax_SansSerif:{768:[[2,1,-4],[3,2,-4],[4,2,-6],[3,2,-7],[4,2,-7],[4,3,-9],[6,4,-10],[6,4,-13],[7,5,-15],[8,6,-17],[10,7,-20],[11,8,-24],[13,10,-29],[15,11,-34]],769:[[3,1,-4],[3,2,-4],[3,2,-6],[4,2,-7],[4,2,-7],[5,3,-9],[5,4,-10],[7,4,-13],[7,5,-15],[8,6,-17],[9,7,-20],[12,8,-24],[13,10,-29],[15,11,-34]],770:[[3,1,-4],[4,2,-4],[5,2,-6],[5,2,-7],[5,2,-7],[6,3,-9],[8,4,-10],[9,4,-13],[10,5,-15],[12,6,-17],[14,7,-20],[17,8,-24],[20,10,-29],[23,11,-34]],771:[[3,1,-4],[4,1,-5],[5,2,-6],[5,3,-6],[5,2,-7],[6,3,-9],[8,3,-11],[9,3,-14],[10,4,-16],[12,5,-18],[14,6,-21],[17,6,-25],[20,8,-31],[23,9,-35]],772:[[3,1,-3],[4,1,-5],[5,1,-6],[6,2,-6],[6,2,-6],[7,3,-9],[8,2,-11],[9,2,-13],[11,3,-16],[13,3,-18],[15,4,-22],[18,4,-25],[21,5,-31],[25,6,-36]],774:[[3,1,-4],[4,2,-4],[5,2,-6],[6,3,-6],[5,3,-6],[7,4,-8],[8,4,-10],[9,4,-13],[10,6,-14],[13,6,-17],[15,8,-19],[17,9,-23],[20,11,-28],[25,12,-33]],775:[[2,1,-4],[2,1,-5],[2,2,-6],[2,2,-7],[3,2,-7],[3,2,-10],[3,3,-11],[4,3,-14],[4,3,-17],[4,4,-19],[5,5,-23],[6,5,-26],[7,6,-33],[7,7,-38]],776:[[3,1,-4],[4,1,-5],[3,2,-6],[4,2,-7],[5,2,-7],[6,2,-10],[6,2,-12],[8,3,-14],[9,3,-17],[11,4,-19],[12,4,-23],[15,5,-27],[17,6,-33],[21,7,-38]],778:[[3,1,-4],[3,2,-4],[4,2,-6],[3,2,-7],[4,2,-7],[5,3,-9],[6,3,-11],[6,5,-12],[7,6,-14],[8,6,-17],[10,7,-20],[11,8,-24],[13,10,-29],[15,11,-34]],779:[[3,2,-3],[4,2,-4],[4,2,-6],[5,3,-6],[5,3,-6],[6,3,-9],[7,4,-10],[9,5,-12],[10,5,-15],[12,6,-17],[13,7,-20],[16,8,-24],[19,10,-29],[22,11,-34]],780:[[3,1,-3],[4,2,-4],[5,2,-5],[5,2,-6],[5,2,-6],[6,3,-9],[8,4,-10],[9,4,-12],[10,5,-14],[12,6,-16],[14,7,-19],[17,8,-22],[20,10,-28],[23,11,-32]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/SansSerif/Regular"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/CombDiacritMarks.js");
| narikei/cdnjs | ajax/libs/mathjax/2.3.0/fonts/HTML-CSS/TeX/png/SansSerif/Regular/CombDiacritMarks.js | JavaScript | mit | 2,224 |
/** Used to map latin-1 supplementary letters to basic latin letters. */
var deburredLetters = {
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss'
};
/**
* Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
function deburrLetter(letter) {
return deburredLetters[letter];
}
module.exports = deburrLetter;
| m1ksu/To-Do-List | node_modules/grunt-legacy-log-utils/node_modules/lodash/_deburrLetter.js | JavaScript | mit | 1,275 |
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Declaration = require('../declaration');
var GridEnd = function (_Declaration) {
_inherits(GridEnd, _Declaration);
function GridEnd() {
_classCallCheck(this, GridEnd);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not add prefix for unsupported value in IE
*/
GridEnd.prototype.check = function check(decl) {
return decl.value.indexOf('span') !== -1;
};
/**
* Return a final spec property
*/
GridEnd.prototype.normalize = function normalize(prop) {
return prop.replace(/(-span|-end)/, '');
};
/**
* Change property name for IE
*/
GridEnd.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return prefix + prop.replace('-end', '-span');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Change repeating syntax for IE
*/
GridEnd.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-') {
decl.value = decl.value.replace(/span\s/i, '');
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return GridEnd;
}(Declaration);
Object.defineProperty(GridEnd, 'names', {
enumerable: true,
writable: true,
value: ['grid-row-end', 'grid-column-end', 'grid-row-span', 'grid-column-span']
});
module.exports = GridEnd; | june111/webAppStudy | bolg-fontend/node_modules/autoprefixer/lib/hacks/grid-end.js | JavaScript | mit | 2,396 |
<?php
/**
* PHPWord
*
* Copyright (c) 2011 PHPWord
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPWord
* @package PHPWord
* @copyright Copyright (c) 010 PHPWord
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version Beta 0.6.3, 08.07.2011
*/
class PHPWord_Shared_Font
{
/**
* Calculate an (approximate) pixel size, based on a font points size
*
* @param int $fontSizeInPoints Font size (in points)
* @return int Font size (in pixels)
*/
public static function fontSizeToPixels($fontSizeInPoints = 12) {
return ((16 / 12) * $fontSizeInPoints);
}
/**
* Calculate an (approximate) pixel size, based on inch size
*
* @param int $sizeInInch Font size (in inch)
* @return int Size (in pixels)
*/
public static function inchSizeToPixels($sizeInInch = 1) {
return ($sizeInInch * 96);
}
/**
* Calculate an (approximate) pixel size, based on centimeter size
*
* @param int $sizeInCm Font size (in centimeters)
* @return int Size (in pixels)
*/
public static function centimeterSizeToPixels($sizeInCm = 1) {
return ($sizeInCm * 37.795275591);
}
public static function centimeterSizeToTwips($sizeInCm = 1) {
return ($sizeInCm * 565.217);
}
public static function inchSizeToTwips($sizeInInch = 1) {
return self::centimeterSizeToTwips($sizeInInch * 2.54);
}
public static function pixelSizeToTwips($sizeInPixel = 1) {
return self::centimeterSizeToTwips($sizeInPixel / 37.795275591);
}
}
| guoyuping/gudong.pro | web/phpword/PHPWord/Shared/Font.php | PHP | mit | 2,219 |
/**
* JQUERY-FORM-VALIDATOR
*
* @website by
* @license MIT
* @version 2.2.8
*/
!function(a){"use strict";var b=a(window),c=function(b){if(b.valAttr("error-msg-container"))return a(b.valAttr("error-msg-container"));var c=b.parent();if(!c.hasClass("form-group")&&!c.closest("form").hasClass("form-horizontal")){var d=c.closest(".form-group");if(d.length)return d.eq(0)}return c},d=function(a,b){a.addClass(b.errorElementClass).removeClass("valid"),c(a).addClass(b.inputParentClassOnError).removeClass(b.inputParentClassOnSuccess),""!==b.borderColorOnError&&a.css("border-color",b.borderColorOnError)},e=function(b,d){b.each(function(){var b=a(this);f(b,"",d,d.errorMessagePosition),b.removeClass("valid").removeClass(d.errorElementClass).css("border-color",""),c(b).removeClass(d.inputParentClassOnError).removeClass(d.inputParentClassOnSuccess).find("."+d.errorMessageClass).remove()})},f=function(d,e,f,g){var h=document.getElementById(d.attr("name")+"_err_msg"),i=function(a){b.trigger("validationErrorDisplay",[d,a]),a.html(e)};if(h)i(a(h));else if("object"==typeof g){var j=!1;if(g.find("."+f.errorMessageClass).each(function(){return this.inputReferer==d[0]?(j=a(this),!1):void 0}),j)e?i(j):j.remove();else{var k=a('<div class="'+f.errorMessageClass+'"></div>');i(k),k[0].inputReferer=d[0],g.prepend(k)}}else{var l=c(d),k=l.find("."+f.errorMessageClass+".help-block");0==k.length&&(k=a("<span></span>").addClass("help-block").addClass(f.errorMessageClass),k.appendTo(l)),i(k)}},g=function(b,c,d,e){var f,g=e.errorMessageTemplate.messages.replace(/\{errorTitle\}/g,c),h=[];a.each(d,function(a,b){h.push(e.errorMessageTemplate.field.replace(/\{msg\}/g,b))}),g=g.replace(/\{fields\}/g,h.join("")),f=e.errorMessageTemplate.container.replace(/\{errorMessageClass\}/g,e.errorMessageClass),f=f.replace(/\{messages\}/g,g),b.children().eq(0).before(f)};a.fn.validateOnBlur=function(b,c){return this.find("*[data-validation]").bind("blur.validation",function(){a(this).validateInputOnBlur(b,c,!0,"blur")}),c.validateCheckboxRadioOnClick&&this.find("input[type=checkbox][data-validation],input[type=radio][data-validation]").bind("click.validation",function(){a(this).validateInputOnBlur(b,c,!0,"click")}),this},a.fn.validateOnEvent=function(b,c){return this.find("*[data-validation-event]").each(function(){var d=a(this),e=d.valAttr("event");e&&d.unbind(e+".validation").bind(e+".validation",function(){a(this).validateInputOnBlur(b,c,!0,e)})}),this},a.fn.showHelpOnFocus=function(b){return b||(b="data-validation-help"),this.find(".has-help-txt").valAttr("has-keyup-event",!1).removeClass("has-help-txt"),this.find("textarea,input").each(function(){var c=a(this),d="jquery_form_help_"+(c.attr("name")||"").replace(/(:|\.|\[|\])/g,""),e=c.attr(b);e&&c.addClass("has-help-txt").unbind("focus.help").bind("focus.help",function(){var b=c.parent().find("."+d);0==b.length&&(b=a("<span />").addClass(d).addClass("help").addClass("help-block").text(e).hide(),c.after(b)),b.fadeIn()}).unbind("blur.help").bind("blur.help",function(){a(this).parent().find("."+d).fadeOut("slow")})}),this},a.fn.validate=function(b,c,d){var e=a.extend({},a.formUtils.LANG,d||{});this.each(function(){var d=a(this),f=d.closest("form").get(0).validationConfig||{};d.one("validation",function(a,c){"function"==typeof b&&b(c,this,a)}),d.validateInputOnBlur(e,a.extend({},f,c||{}),!0)})},a.fn.willPostponeValidation=function(){return(this.valAttr("suggestion-nr")||this.valAttr("postpone")||this.hasClass("hasDatepicker"))&&!window.postponedValidation},a.fn.validateInputOnBlur=function(b,g,h,i){if(a.formUtils.eventType=i,this.willPostponeValidation()){var j=this,k=this.valAttr("postpone")||200;return window.postponedValidation=function(){j.validateInputOnBlur(b,g,h,i),window.postponedValidation=!1},setTimeout(function(){window.postponedValidation&&window.postponedValidation()},k),this}b=a.extend({},a.formUtils.LANG,b||{}),e(this,g);var l=this,m=l.closest("form"),n=(l.attr(g.validationRuleAttribute),a.formUtils.validateInput(l,b,g,m,i));return n.isValid?n.shouldChangeDisplay&&(l.addClass("valid"),c(l).addClass(g.inputParentClassOnSuccess)):n.isValid||(d(l,g),f(l,n.errorMsg,g,g.errorMessagePosition),h&&l.unbind("keyup.validation").bind("keyup.validation",function(){a(this).validateInputOnBlur(b,g,!1,"keyup")})),this},a.fn.valAttr=function(a,b){return void 0===b?this.attr("data-validation-"+a):b===!1||null===b?this.removeAttr("data-validation-"+a):(a.length>0&&(a="-"+a),this.attr("data-validation"+a,b))},a.fn.isValid=function(h,i,j){if(a.formUtils.isLoadingModules){var k=this;return setTimeout(function(){k.isValid(h,i,j)},200),null}i=a.extend({},a.formUtils.defaultConfig(),i||{}),h=a.extend({},a.formUtils.LANG,h||{}),j=j!==!1,a.formUtils.errorDisplayPreventedWhenHalted&&(delete a.formUtils.errorDisplayPreventedWhenHalted,j=!1),a.formUtils.isValidatingEntireForm=!0,a.formUtils.haltValidation=!1;var l=function(b,c){a.inArray(b,n)<0&&n.push(b),o.push(c),c.attr("current-error",b),j&&d(c,i)},m=[],n=[],o=[],p=this,q=function(b,c){return"submit"===c||"button"===c||"reset"==c?!0:a.inArray(b,i.ignore||[])>-1};if(j&&(p.find("."+i.errorMessageClass+".alert").remove(),e(p.find("."+i.errorElementClass+",.valid"),i)),p.find("input,textarea,select").filter(':not([type="submit"],[type="button"])').each(function(){var b=a(this),d=b.attr("type"),e="radio"==d||"checkbox"==d,f=b.attr("name");if(!q(f,d)&&(!e||a.inArray(f,m)<0)){e&&m.push(f);var g=a.formUtils.validateInput(b,h,i,p,"submit");g.shouldChangeDisplay&&(g.isValid?g.isValid&&(b.valAttr("current-error",!1).addClass("valid"),c(b).addClass(i.inputParentClassOnSuccess)):l(g.errorMsg,b))}}),"function"==typeof i.onValidate){var r=i.onValidate(p);a.isArray(r)?a.each(r,function(a,b){l(b.message,b.element)}):r&&r.element&&r.message&&l(r.message,r.element)}return a.formUtils.isValidatingEntireForm=!1,!a.formUtils.haltValidation&&o.length>0?(j&&("top"===i.errorMessagePosition?g(p,h.errorTitle,n,i):"custom"===i.errorMessagePosition?"function"==typeof i.errorMessageCustom&&i.errorMessageCustom(p,h.errorTitle,n,i):a.each(o,function(a,b){f(b,b.attr("current-error"),i,i.errorMessagePosition)}),i.scrollToTopOnError&&b.scrollTop(p.offset().top-20)),!1):(!j&&a.formUtils.haltValidation&&(a.formUtils.errorDisplayPreventedWhenHalted=!0),!a.formUtils.haltValidation)},a.fn.validateForm=function(a,b){return window.console&&"function"==typeof window.console.warn&&window.console.warn("Use of deprecated function $.validateForm, use $.isValid instead"),this.isValid(a,b,!0)},a.fn.restrictLength=function(b){return new a.formUtils.lengthRestriction(this,b),this},a.fn.addSuggestions=function(b){var c=!1;return this.find("input").each(function(){var d=a(this);c=a.split(d.attr("data-suggestions")),c.length>0&&!d.hasClass("has-suggestions")&&(a.formUtils.suggest(d,c,b),d.addClass("has-suggestions"))}),this},a.split=function(b,c){if("function"!=typeof c){if(!b)return[];var d=[];return a.each(b.split(c?c:/[,|\-\s]\s*/g),function(b,c){c=a.trim(c),c.length&&d.push(c)}),d}b&&a.each(b.split(/[,|\-\s]\s*/g),function(b,d){return d=a.trim(d),d.length?c(d,b):void 0})},a.validate=function(c){var d=a.extend(a.formUtils.defaultConfig(),{form:"form",validateOnEvent:!1,validateOnBlur:!0,validateCheckboxRadioOnClick:!0,showHelpOnFocus:!0,addSuggestions:!0,modules:"",onModulesLoaded:null,language:!1,onSuccess:!1,onError:!1,onElementValidate:!1});if(c=a.extend(d,c||{}),c.lang&&"en"!=c.lang){var f="lang/"+c.lang+".js";c.modules+=c.modules.length?","+f:f}a(c.form).each(function(d,f){f.validationConfig=c;var g=a(f);b.trigger("formValidationSetup",[g,c]),g.find(".has-help-txt").unbind("focus.validation").unbind("blur.validation"),g.removeClass("has-validation-callback").unbind("submit.validation").unbind("reset.validation").find("input[data-validation],textarea[data-validation]").unbind("blur.validation"),g.bind("submit.validation",function(){var b=a(this);if(a.formUtils.haltValidation)return!1;if(a.formUtils.isLoadingModules)return setTimeout(function(){b.trigger("submit.validation")},200),!1;var d=b.isValid(c.language,c);if(a.formUtils.haltValidation)return!1;if(!d||"function"!=typeof c.onSuccess)return d||"function"!=typeof c.onError?d:(c.onError(b),!1);var e=c.onSuccess(b);return e===!1?!1:void 0}).bind("reset.validation",function(){a(this).find("."+c.errorMessageClass+".alert").remove(),e(a(this).find("."+c.errorElementClass+",.valid"),c)}).addClass("has-validation-callback"),c.showHelpOnFocus&&g.showHelpOnFocus(),c.addSuggestions&&g.addSuggestions(),c.validateOnBlur&&(g.validateOnBlur(c.language,c),g.bind("html5ValidationAttrsFound",function(){g.validateOnBlur(c.language,c)})),c.validateOnEvent&&g.validateOnEvent(c.language,c)}),""!=c.modules&&a.formUtils.loadModules(c.modules,!1,function(){"function"==typeof c.onModulesLoaded&&c.onModulesLoaded(),b.trigger("validatorsLoaded",["string"==typeof c.form?a(c.form):c.form,c])})},a.formUtils={defaultConfig:function(){return{ignore:[],errorElementClass:"error",borderColorOnError:"#b94a48",errorMessageClass:"form-error",validationRuleAttribute:"data-validation",validationErrorMsgAttribute:"data-validation-error-msg",errorMessagePosition:"element",errorMessageTemplate:{container:'<div class="{errorMessageClass} alert alert-danger">{messages}</div>',messages:"<strong>{errorTitle}</strong><ul>{fields}</ul>",field:"<li>{msg}</li>"},errorMessageCustom:g,scrollToTopOnError:!0,dateFormat:"yyyy-mm-dd",addValidClassOnAll:!1,decimalSeparator:".",inputParentClassOnError:"has-error",inputParentClassOnSuccess:"has-success",validateHiddenInputs:!1}},validators:{},_events:{load:[],valid:[],invalid:[]},haltValidation:!1,isValidatingEntireForm:!1,addValidator:function(a){var b=0===a.name.indexOf("validate_")?a.name:"validate_"+a.name;void 0===a.validateOnKeyUp&&(a.validateOnKeyUp=!0),this.validators[b]=a},isLoadingModules:!1,loadedModules:{},loadModules:function(c,d,e){if(void 0===e&&(e=!0),a.formUtils.isLoadingModules)return void setTimeout(function(){a.formUtils.loadModules(c,d,e)});var f=!1,g=function(c,d){var g=a.split(c),h=g.length,i=function(){h--,0==h&&(a.formUtils.isLoadingModules=!1,e&&f&&("function"==typeof e?e():b.trigger("validatorsLoaded")))};h>0&&(a.formUtils.isLoadingModules=!0);var j="?_="+(new Date).getTime(),k=document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0];a.each(g,function(b,c){if(c=a.trim(c),0==c.length)i();else{var e=d+c+(".js"==c.slice(-3)?"":".js"),g=document.createElement("SCRIPT");e in a.formUtils.loadedModules?i():(a.formUtils.loadedModules[e]=1,f=!0,g.type="text/javascript",g.onload=i,g.src=e+(".dev.js"==e.slice(-7)?j:""),g.onerror=function(){"console"in window&&window.console.log&&window.console.log("Unable to load form validation module "+e)},g.onreadystatechange=function(){("complete"==this.readyState||"loaded"==this.readyState)&&(i(),this.onload=null,this.onreadystatechange=null)},k.appendChild(g))}})};if(d)g(c,d);else{var h=function(){var b=!1;return a('script[src*="form-validator"]').each(function(){return b=this.src.substr(0,this.src.lastIndexOf("/"))+"/","/"==b&&(b=""),!1}),b!==!1?(g(c,b),!0):!1};h()||a(h)}},validateInput:function(b,c,d,e,f){b.trigger("beforeValidation"),d=d||a.formUtils.defaultConfig(),c=c||a.formUtils.LANG;var g=b.val()||"",h={isValid:!0,shouldChangeDisplay:!0,errorMsg:""},i=b.valAttr("optional"),j=!1,k=!1,l=!1,m=b.valAttr("if-checked");if(b.attr("disabled")||!b.is(":visible")&&!d.validateHiddenInputs)return h.shouldChangeDisplay=!1,h;null!=m&&(j=!0,l=e.find('input[name="'+m+'"]'),l.prop("checked")&&(k=!0));var n=!g&&"number"==b[0].type;if(!g&&"true"===i&&!n||j&&!k)return h.shouldChangeDisplay=d.addValidClassOnAll,h;var o=b.attr(d.validationRuleAttribute),p=!0;return o?(a.split(o,function(h){0!==h.indexOf("validate_")&&(h="validate_"+h);var i=a.formUtils.validators[h];if(!i||"function"!=typeof i.validatorFunction)throw new Error('Using undefined validator "'+h+'"');"validate_checkbox_group"==h&&(b=e.find("[name='"+b.attr("name")+"']:eq(0)"));var j=null;return("keyup"!=f||i.validateOnKeyUp)&&(j=i.validatorFunction(g,b,d,c,e)),j?void 0:(p=null,null!==j&&(p=b.attr(d.validationErrorMsgAttribute+"-"+h.replace("validate_","")),p||(p=b.attr(d.validationErrorMsgAttribute),p||(p=c[i.errorMessageKey],p||(p=i.errorMessage)))),!1)}," "),"string"==typeof p?(b.trigger("validation",!1),h.errorMsg=p,h.isValid=!1,h.shouldChangeDisplay=!0):null===p?h.shouldChangeDisplay=d.addValidClassOnAll:(b.trigger("validation",!0),h.shouldChangeDisplay=!0),"function"==typeof d.onElementValidate&&null!==p&&d.onElementValidate(h.isValid,b,e,p),h):(h.shouldChangeDisplay=d.addValidClassOnAll,h)},parseDate:function(b,c){var d,e,f,g,h=c.replace(/[a-zA-Z]/gi,"").substring(0,1),i="^",j=c.split(h||null);if(a.each(j,function(a,b){i+=(a>0?"\\"+h:"")+"(\\d{"+b.length+"})"}),i+="$",d=b.match(new RegExp(i)),null===d)return!1;var k=function(b,c,d){for(var e=0;e<c.length;e++)if(c[e].substring(0,1)===b)return a.formUtils.parseDateInt(d[e+1]);return-1};return f=k("m",j,d),e=k("d",j,d),g=k("y",j,d),2===f&&e>28&&(g%4!==0||g%100===0&&g%400!==0)||2===f&&e>29&&(g%4===0||g%100!==0&&g%400===0)||f>12||0===f?!1:this.isShortMonth(f)&&e>30||!this.isShortMonth(f)&&e>31||0===e?!1:[g,f,e]},parseDateInt:function(a){return 0===a.indexOf("0")&&(a=a.replace("0","")),parseInt(a,10)},isShortMonth:function(a){return a%2===0&&7>a||a%2!==0&&a>7},lengthRestriction:function(b,c){var d=parseInt(c.text(),10),e=0,f=function(){var a=b.val().length;if(a>d){var f=b.scrollTop();b.val(b.val().substring(0,d)),b.scrollTop(f)}e=d-a,0>e&&(e=0),c.text(e)};a(b).bind("keydown keyup keypress focus blur",f).bind("cut paste",function(){setTimeout(f,100)}),a(document).bind("ready",f)},numericRangeCheck:function(b,c){var d=a.split(c),e=parseInt(c.substr(3),10);return 1==d.length&&-1==c.indexOf("min")&&-1==c.indexOf("max")&&(d=[c,c]),2==d.length&&(b<parseInt(d[0],10)||b>parseInt(d[1],10))?["out",d[0],d[1]]:0===c.indexOf("min")&&e>b?["min",e]:0===c.indexOf("max")&&b>e?["max",e]:["ok"]},_numSuggestionElements:0,_selectedSuggestion:null,_previousTypedVal:null,suggest:function(c,d,e){var f={css:{maxHeight:"150px",background:"#FFF",lineHeight:"150%",textDecoration:"underline",overflowX:"hidden",overflowY:"auto",border:"#CCC solid 1px",borderTop:"none",cursor:"pointer"},activeSuggestionCSS:{background:"#E9E9E9"}},g=function(a,b){var c=b.offset();a.css({width:b.outerWidth(),left:c.left+"px",top:c.top+b.outerHeight()+"px"})};e&&a.extend(f,e),f.css.position="absolute",f.css["z-index"]=9999,c.attr("autocomplete","off"),0===this._numSuggestionElements&&b.bind("resize",function(){a(".jquery-form-suggestions").each(function(){var b=a(this),c=b.attr("data-suggest-container");g(b,a(".suggestions-"+c).eq(0))})}),this._numSuggestionElements++;var h=function(b){var c=b.valAttr("suggestion-nr");a.formUtils._selectedSuggestion=null,a.formUtils._previousTypedVal=null,a(".jquery-form-suggestion-"+c).fadeOut("fast")};return c.data("suggestions",d).valAttr("suggestion-nr",this._numSuggestionElements).unbind("focus.suggest").bind("focus.suggest",function(){a(this).trigger("keyup"),a.formUtils._selectedSuggestion=null}).unbind("keyup.suggest").bind("keyup.suggest",function(){var b=a(this),d=[],e=a.trim(b.val()).toLocaleLowerCase();if(e!=a.formUtils._previousTypedVal){a.formUtils._previousTypedVal=e;var i=!1,j=b.valAttr("suggestion-nr"),k=a(".jquery-form-suggestion-"+j);if(k.scrollTop(0),""!=e){var l=e.length>2;a.each(b.data("suggestions"),function(a,b){var c=b.toLocaleLowerCase();return c==e?(d.push("<strong>"+b+"</strong>"),i=!0,!1):void((0===c.indexOf(e)||l&&c.indexOf(e)>-1)&&d.push(b.replace(new RegExp(e,"gi"),"<strong>$&</strong>")))})}i||0==d.length&&k.length>0?k.hide():d.length>0&&0==k.length?(k=a("<div></div>").css(f.css).appendTo("body"),c.addClass("suggestions-"+j),k.attr("data-suggest-container",j).addClass("jquery-form-suggestions").addClass("jquery-form-suggestion-"+j)):d.length>0&&!k.is(":visible")&&k.show(),d.length>0&&e.length!=d[0].length&&(g(k,b),k.html(""),a.each(d,function(c,d){a("<div></div>").append(d).css({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"5px"}).addClass("form-suggest-element").appendTo(k).click(function(){b.focus(),b.val(a(this).text()),h(b)})}))}}).unbind("keydown.validation").bind("keydown.validation",function(b){var c,d,e=b.keyCode?b.keyCode:b.which,g=a(this);if(13==e&&null!==a.formUtils._selectedSuggestion){if(c=g.valAttr("suggestion-nr"),d=a(".jquery-form-suggestion-"+c),d.length>0){var i=d.find("div").eq(a.formUtils._selectedSuggestion).text();g.val(i),h(g),b.preventDefault()}}else{c=g.valAttr("suggestion-nr"),d=a(".jquery-form-suggestion-"+c);var j=d.children();if(j.length>0&&a.inArray(e,[38,40])>-1){38==e?(null===a.formUtils._selectedSuggestion?a.formUtils._selectedSuggestion=j.length-1:a.formUtils._selectedSuggestion--,a.formUtils._selectedSuggestion<0&&(a.formUtils._selectedSuggestion=j.length-1)):40==e&&(null===a.formUtils._selectedSuggestion?a.formUtils._selectedSuggestion=0:a.formUtils._selectedSuggestion++,a.formUtils._selectedSuggestion>j.length-1&&(a.formUtils._selectedSuggestion=0));var k=d.innerHeight(),l=d.scrollTop(),m=d.children().eq(0).outerHeight(),n=m*a.formUtils._selectedSuggestion;return(l>n||n>l+k)&&d.scrollTop(n),j.removeClass("active-suggestion").css("background","none").eq(a.formUtils._selectedSuggestion).addClass("active-suggestion").css(f.activeSuggestionCSS),b.preventDefault(),!1}}}).unbind("blur.suggest").bind("blur.suggest",function(){h(a(this))}),c},LANG:{errorTitle:"Form submission failed!",requiredFields:"You have not answered all required fields",badTime:"You have not given a correct time",badEmail:"You have not given a correct e-mail address",badTelephone:"You have not given a correct phone number",badSecurityAnswer:"You have not given a correct answer to the security question",badDate:"You have not given a correct date",lengthBadStart:"The input value must be between ",lengthBadEnd:" characters",lengthTooLongStart:"The input value is longer than ",lengthTooShortStart:"The input value is shorter than ",notConfirmed:"Input values could not be confirmed",badDomain:"Incorrect domain value",badUrl:"The input value is not a correct URL",badCustomVal:"The input value is incorrect",andSpaces:" and spaces ",badInt:"The input value was not a correct number",badSecurityNumber:"Your social security number was incorrect",badUKVatAnswer:"Incorrect UK VAT Number",badStrength:"The password isn't strong enough",badNumberOfSelectedOptionsStart:"You have to choose at least ",badNumberOfSelectedOptionsEnd:" answers",badAlphaNumeric:"The input value can only contain alphanumeric characters ",badAlphaNumericExtra:" and ",wrongFileSize:"The file you are trying to upload is too large (max %s)",wrongFileType:"Only files of type %s is allowed",groupCheckedRangeStart:"Please choose between ",groupCheckedTooFewStart:"Please choose at least ",groupCheckedTooManyStart:"Please choose a maximum of ",groupCheckedEnd:" item(s)",badCreditCard:"The credit card number is not correct",badCVV:"The CVV number was not correct",wrongFileDim:"Incorrect image dimensions,",imageTooTall:"the image can not be taller than",imageTooWide:"the image can not be wider than",imageTooSmall:"the image was too small",min:"min",max:"max",imageRatioNotAccepted:"Image ratio is not be accepted",badBrazilTelephoneAnswer:"The phone number entered is invalid",badBrazilCEPAnswer:"The CEP entered is invalid",badBrazilCPFAnswer:"The CPF entered is invalid"}},a.formUtils.addValidator({name:"email",validatorFunction:function(b){var c=b.toLowerCase().split("@"),d=c[0],e=c[1];if(d&&e){if(0==d.indexOf('"')){var f=d.length;if(d=d.replace(/\"/g,""),d.length!=f-2)return!1}return a.formUtils.validators.validate_domain.validatorFunction(c[1])&&0!=d.indexOf(".")&&"."!=d.substring(d.length-1,d.length)&&-1==d.indexOf("..")&&!/[^\w\+\.\-\#\-\_\~\!\$\&\'\(\)\*\+\,\;\=\:]/.test(d)}return!1},errorMessage:"",errorMessageKey:"badEmail"}),a.formUtils.addValidator({name:"domain",validatorFunction:function(a){return a.length>0&&a.length<=253&&!/[^a-zA-Z0-9]/.test(a.slice(-2))&&!/[^a-zA-Z0-9]/.test(a.substr(0,1))&&!/[^a-zA-Z0-9\.\-]/.test(a)&&1==a.split("..").length&&a.split(".").length>1},errorMessage:"",errorMessageKey:"badDomain"}),a.formUtils.addValidator({name:"required",validatorFunction:function(b,c,d,e,f){switch(c.attr("type")){case"checkbox":return c.is(":checked");case"radio":return f.find('input[name="'+c.attr("name")+'"]').filter(":checked").length>0;default:return""!==a.trim(b)}},errorMessage:"",errorMessageKey:"requiredFields"}),a.formUtils.addValidator({name:"length",validatorFunction:function(b,c,d,e){var f=c.valAttr("length"),g=c.attr("type");if(void 0==f)return alert('Please add attribute "data-validation-length" to '+c[0].nodeName+" named "+c.attr("name")),!0;var h,i="file"==g&&void 0!==c.get(0).files?c.get(0).files.length:b.length,j=a.formUtils.numericRangeCheck(i,f);switch(j[0]){case"out":this.errorMessage=e.lengthBadStart+f+e.lengthBadEnd,h=!1;break;case"min":this.errorMessage=e.lengthTooShortStart+j[1]+e.lengthBadEnd,h=!1;break;case"max":this.errorMessage=e.lengthTooLongStart+j[1]+e.lengthBadEnd,h=!1;break;default:h=!0}return h},errorMessage:"",errorMessageKey:""}),a.formUtils.addValidator({name:"url",validatorFunction:function(b){var c=/^(https?|ftp):\/\/((((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])(\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])(\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/(((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|\[|\]|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#(((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;if(c.test(b)){var d=b.split("://")[1],e=d.indexOf("/");return e>-1&&(d=d.substr(0,e)),a.formUtils.validators.validate_domain.validatorFunction(d)}return!1},errorMessage:"",errorMessageKey:"badUrl"}),a.formUtils.addValidator({name:"number",validatorFunction:function(a,b,c){if(""!==a){var d,e,f=b.valAttr("allowing")||"",g=b.valAttr("decimal-separator")||c.decimalSeparator,h=!1,i=b.valAttr("step")||"",j=!1;if(-1==f.indexOf("number")&&(f+=",number"),-1==f.indexOf("negative")&&0===a.indexOf("-"))return!1;if(f.indexOf("range")>-1&&(d=parseFloat(f.substring(f.indexOf("[")+1,f.indexOf(";"))),e=parseFloat(f.substring(f.indexOf(";")+1,f.indexOf("]"))),h=!0),""!=i&&(j=!0),","==g){if(a.indexOf(".")>-1)return!1;a=a.replace(",",".")}if(f.indexOf("number")>-1&&""===a.replace(/[0-9-]/g,"")&&(!h||a>=d&&e>=a)&&(!j||a%i==0))return!0;if(f.indexOf("float")>-1&&null!==a.match(new RegExp("^([0-9-]+)\\.([0-9]+)$"))&&(!h||a>=d&&e>=a)&&(!j||a%i==0))return!0}return!1},errorMessage:"",errorMessageKey:"badInt"}),a.formUtils.addValidator({name:"alphanumeric",validatorFunction:function(b,c,d,e){var f="^([a-zA-Z0-9",g="]+)$",h=c.valAttr("allowing"),i="";if(h){i=f+h+g;var j=h.replace(/\\/g,"");j.indexOf(" ")>-1&&(j=j.replace(" ",""),j+=e.andSpaces||a.formUtils.LANG.andSpaces),this.errorMessage=e.badAlphaNumeric+e.badAlphaNumericExtra+j}else i=f+g,this.errorMessage=e.badAlphaNumeric;return new RegExp(i).test(b)},errorMessage:"",errorMessageKey:""}),a.formUtils.addValidator({name:"custom",validatorFunction:function(a,b){var c=new RegExp(b.valAttr("regexp"));return c.test(a)},errorMessage:"",errorMessageKey:"badCustomVal"}),a.formUtils.addValidator({name:"date",validatorFunction:function(b,c,d){var e=c.valAttr("format")||d.dateFormat||"yyyy-mm-dd";return a.formUtils.parseDate(b,e)!==!1},errorMessage:"",errorMessageKey:"badDate"}),a.formUtils.addValidator({name:"checkbox_group",validatorFunction:function(b,c,d,e,f){var g=!0,h=c.attr("name"),i=a("input[type=checkbox][name^='"+h+"']",f),j=i.filter(":checked").length,k=c.valAttr("qty");if(void 0==k){var l=c.get(0).nodeName;alert('Attribute "data-validation-qty" is missing from '+l+" named "+c.attr("name"))}var m=a.formUtils.numericRangeCheck(j,k);switch(m[0]){case"out":this.errorMessage=e.groupCheckedRangeStart+k+e.groupCheckedEnd,g=!1;break;case"min":this.errorMessage=e.groupCheckedTooFewStart+m[1]+e.groupCheckedEnd,g=!1;break;case"max":this.errorMessage=e.groupCheckedTooManyStart+m[1]+e.groupCheckedEnd,g=!1;break;default:g=!0}if(!g){var n=function(){i.unbind("click",n),i.filter("*[data-validation]").validateInputOnBlur(e,d,!1,"blur")};i.bind("click",n)}return g}})}(jQuery); | Amomo/cdnjs | ajax/libs/jquery-form-validator/2.2.8/jquery.form-validator.min.js | JavaScript | mit | 25,054 |
/*!
* Stylus - Compiler
* Copyright(c) 2010 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Visitor = require('./')
, nodes = require('../nodes')
, utils = require('../utils')
, fs = require('fs');
/**
* Initialize a new `Compiler` with the given `root` Node
* and the following `options`.
*
* Options:
*
* - `compress` Compress the css output, defaults to false
*
* @param {Node} root
* @api public
*/
var Compiler = module.exports = function Compiler(root, options) {
options = options || {};
this.compress = options.compress;
this.firebug = options.firebug;
this.linenos = options.linenos;
this.spaces = options['indent spaces'] || 2;
this.includeCSS = options['include css'];
this.indents = 1;
Visitor.call(this, root);
this.stack = [];
this.js = '';
};
/**
* Inherit from `Visitor.prototype`.
*/
Compiler.prototype.__proto__ = Visitor.prototype;
/**
* Compile to css, and return a string of CSS.
*
* @return {String}
* @api private
*/
Compiler.prototype.compile = function(){
return this.visit(this.root);
};
/**
* Return indentation string.
*
* @return {String}
* @api private
*/
Compiler.prototype.__defineGetter__('indent', function(){
if (this.compress) return '';
return new Array(this.indents).join(Array(this.spaces + 1).join(' '));
});
/**
* Visit Root.
*/
Compiler.prototype.visitRoot = function(block){
this.buf = '';
for (var i = 0, len = block.nodes.length; i < len; ++i) {
var node = block.nodes[i];
if (this.linenos || this.firebug) this.debugInfo(node);
var ret = this.visit(node);
if (ret) this.buf += ret + '\n';
}
return this.buf;
};
/**
* Visit Block.
*/
Compiler.prototype.visitBlock = function(block){
var node;
if (block.hasProperties) {
var arr = [this.compress ? '{' : ' {'];
++this.indents;
for (var i = 0, len = block.nodes.length; i < len; ++i) {
this.last = len - 1 == i;
node = block.nodes[i];
switch (node.nodeName) {
case 'null':
case 'expression':
case 'function':
case 'jsliteral':
case 'group':
case 'unit':
continue;
case 'media':
// Prevent double-writing the @media declaration when
// nested inside of a function/mixin
if (node.block.parent.scope) {
continue;
}
default:
arr.push(this.visit(node));
}
}
--this.indents;
arr.push(this.indent + '}');
this.buf += arr.join(this.compress ? '' : '\n');
this.buf += '\n';
}
// Nesting
for (var i = 0, len = block.nodes.length; i < len; ++i) {
node = block.nodes[i];
switch (node.nodeName) {
case 'group':
case 'print':
case 'page':
case 'block':
case 'keyframes':
if (this.linenos || this.firebug) this.debugInfo(node);
this.visit(node);
break;
case 'media':
case 'mozdocument':
case 'import':
case 'fontface':
this.visit(node);
break;
case 'comment':
// only show comments inside when outside of scope and unsuppressed
if (!block.scope && !node.suppress) {
this.buf += this.visit(node) + '\n';
}
break;
case 'literal':
this.buf += this.visit(node) + '\n';
break;
}
}
};
/**
* Visit Keyframes.
*/
Compiler.prototype.visitKeyframes = function(node){
var comma = this.compress ? ',' : ', ';
var prefix = 'official' == node.prefix
? ''
: '-' + node.prefix + '-';
this.buf += '@' + prefix + 'keyframes '
+ this.visit(node.name)
+ (this.compress ? '{' : ' {');
++this.indents;
node.frames.forEach(function(frame){
if (!this.compress) this.buf += '\n ';
this.buf += this.visit(frame.pos.join(comma));
this.visit(frame.block);
}, this);
--this.indents;
this.buf += '}' + (this.compress ? '' : '\n');
};
/**
* Visit Media.
*/
Compiler.prototype.visitMedia = function(media){
this.buf += '@media ' + media.val;
this.buf += this.compress ? '{' : ' {\n';
++this.indents;
this.visit(media.block);
--this.indents;
this.buf += '}' + (this.compress ? '' : '\n');
};
/**
* Visit MozDocument.
*/
Compiler.prototype.visitMozDocument = function(mozdocument){
this.buf += '@-moz-document ' + mozdocument.val;
this.buf += this.compress ? '{' : ' {\n';
++this.indents;
this.visit(mozdocument.block);
--this.indents;
this.buf += '}' + (this.compress ? '' : '\n');
};
/**
* Visit Page.
*/
Compiler.prototype.visitPage = function(page){
this.buf += this.indent + '@page';
this.buf += page.selector ? ' ' + page.selector : '';
this.visit(page.block);
};
/**
* Visit Import.
*/
Compiler.prototype.visitImport = function(imported){
this.buf += '@import ' + this.visit(imported.path) + ';\n';
};
/**
* Visit FontFace.
*/
Compiler.prototype.visitFontFace = function(face){
this.buf += this.indent + '@font-face';
this.visit(face.block);
};
/**
* Visit JSLiteral.
*/
Compiler.prototype.visitJSLiteral = function(js){
this.js += '\n' + js.val.replace(/@selector/g, '"' + this.selector + '"');
return '';
};
/**
* Visit Comment.
*/
Compiler.prototype.visitComment = function(comment){
return this.compress
? comment.suppress
? ''
: comment.str
: comment.str;
};
/**
* Visit Function.
*/
Compiler.prototype.visitFunction = function(fn){
return fn.name;
};
/**
* Visit Variable.
*/
Compiler.prototype.visitVariable = function(variable){
return '';
};
/**
* Visit Charset.
*/
Compiler.prototype.visitCharset = function(charset){
return '@charset ' + this.visit(charset.val) + ';';
};
/**
* Visit Literal.
*/
Compiler.prototype.visitLiteral = function(lit){
var val = lit.val.trim();
if (!this.includeCSS) val = val.replace(/^ /gm, '');
return val;
};
/**
* Visit Boolean.
*/
Compiler.prototype.visitBoolean = function(bool){
return bool.toString();
};
/**
* Visit RGBA.
*/
Compiler.prototype.visitRGBA = function(rgba){
return rgba.toString();
};
/**
* Visit HSLA.
*/
Compiler.prototype.visitHSLA = function(hsla){
return hsla.rgba.toString();
};
/**
* Visit Unit.
*/
Compiler.prototype.visitUnit = function(unit){
var type = unit.type || ''
, n = unit.val
, float = n != (n | 0);
// Compress
if (this.compress) {
// Zero is always '0', unless when
// a percentage, this is required by keyframes
if ('%' != type && 0 == n) return '0';
// Omit leading '0' on floats
if (float && n < 1 && n > -1) {
return n.toString().replace('0.', '.') + type;
}
}
return n.toString() + type;
};
/**
* Visit Group.
*/
Compiler.prototype.visitGroup = function(group){
var stack = this.stack;
stack.push(group.nodes);
// selectors
if (group.block.hasProperties) {
var selectors = this.compileSelectors(stack);
this.buf += (this.selector = selectors.join(this.compress ? ',' : ',\n'));
}
// output block
this.visit(group.block);
stack.pop();
};
/**
* Visit Ident.
*/
Compiler.prototype.visitIdent = function(ident){
return ident.name;
};
/**
* Visit String.
*/
Compiler.prototype.visitString = function(string){
return this.isURL
? string.val
: string.toString();
};
/**
* Visit Null.
*/
Compiler.prototype.visitNull = function(node){
return '';
};
/**
* Visit Call.
*/
Compiler.prototype.visitCall = function(call){
this.isURL = 'url' == call.name;
var args = call.args.nodes.map(function(arg){
return this.visit(arg);
}, this).join(this.compress ? ',' : ', ');
if (this.isURL) args = '"' + args + '"';
this.isURL = false;
return call.name + '(' + args + ')';
};
/**
* Visit Expression.
*/
Compiler.prototype.visitExpression = function(expr){
var buf = []
, self = this
, len = expr.nodes.length
, nodes = expr.nodes.map(function(node){ return self.visit(node); });
nodes.forEach(function(node, i){
var last = i == len - 1;
buf.push(node);
if ('/' == nodes[i + 1] || '/' == node) return;
if (last) return;
buf.push(expr.isList
? (self.compress ? ',' : ', ')
: (self.isURL ? '' : ' '));
});
return buf.join('');
};
/**
* Visit Arguments.
*/
Compiler.prototype.visitArguments = Compiler.prototype.visitExpression;
/**
* Visit Property.
*/
Compiler.prototype.visitProperty = function(prop){
var self = this
, val = this.visit(prop.expr).trim();
return this.indent + (prop.name || prop.segments.join(''))
+ (this.compress ? ':' + val : ': ' + val)
+ (this.compress
? (this.last ? '' : ';')
: ';');
};
/**
* Compile selector strings in `arr` from the bottom-up
* to produce the selector combinations. For example
* the following Stylus:
*
* ul
* li
* p
* a
* color: red
*
* Would return:
*
* [ 'ul li a', 'ul p a' ]
*
* @param {Array} arr
* @return {Array}
* @api private
*/
Compiler.prototype.compileSelectors = function(arr){
var stack = this.stack
, self = this
, selectors = []
, buf = [];
function interpolateParent(selector, buf) {
var str = selector.val.trim();
if (buf.length) {
for (var i = 0, len = buf.length; i < len; ++i) {
if (~buf[i].indexOf('&')) {
str = buf[i].replace(/&/g, str).trim();
} else {
str += ' ' + buf[i].trim();
}
}
}
return str;
}
function compile(arr, i) {
if (i) {
arr[i].forEach(function(selector){
if (selector.inherits) {
buf.unshift(selector.val);
compile(arr, i - 1);
buf.shift();
} else {
selectors.push(interpolateParent(selector, buf));
}
});
} else {
arr[0].forEach(function(selector){
var str = interpolateParent(selector, buf);
selectors.push(self.indent + str.trimRight());
});
}
}
compile(arr, arr.length - 1);
return selectors;
};
/**
* Debug info.
*/
Compiler.prototype.debugInfo = function(node){
var path = node.filename == 'stdin' ? 'stdin' : fs.realpathSync(node.filename)
, line = node.nodes ? node.nodes[0].lineno : node.lineno;
if (this.linenos){
this.buf += '\n/* ' + 'line ' + line + ' : ' + path + ' */\n';
}
if (this.firebug){
// debug info for firebug, the crazy formatting is needed
path = 'file\\\:\\\/\\\/' + path.replace(/(\/|\.)/g, '\\$1');
line = '\\00003' + line;
this.buf += '\n@media -stylus-debug-info'
+ '{filename{font-family:' + path
+ '}line{font-family:' + line + '}}\n';
}
}
| SlothHacks-2014/tryridr | node_modules/derby/node_modules/stylus/lib/visitor/compiler.js | JavaScript | mit | 10,644 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 98);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ }),
/***/ 1:
/***/ (function(module, exports) {
module.exports = {Foundation: window.Foundation};
/***/ }),
/***/ 2:
/***/ (function(module, exports) {
module.exports = {Plugin: window.Foundation.Plugin};
/***/ }),
/***/ 32:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__foundation_core__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_toggler__ = __webpack_require__(62);
__WEBPACK_IMPORTED_MODULE_0__foundation_core__["Foundation"].plugin(__WEBPACK_IMPORTED_MODULE_1__foundation_toggler__["a" /* Toggler */], 'Toggler');
/***/ }),
/***/ 4:
/***/ (function(module, exports) {
module.exports = {Motion: window.Foundation.Motion, Move: window.Foundation.Move};
/***/ }),
/***/ 62:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Toggler; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_plugin__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_plugin___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__foundation_plugin__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_triggers__ = __webpack_require__(7);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Toggler module.
* @module foundation.toggler
* @requires foundation.util.motion
* @requires foundation.util.triggers
*/
var Toggler = function (_Plugin) {
_inherits(Toggler, _Plugin);
function Toggler() {
_classCallCheck(this, Toggler);
return _possibleConstructorReturn(this, (Toggler.__proto__ || Object.getPrototypeOf(Toggler)).apply(this, arguments));
}
_createClass(Toggler, [{
key: '_setup',
/**
* Creates a new instance of Toggler.
* @class
* @fires Toggler#init
* @param {Object} element - jQuery object to add the trigger to.
* @param {Object} options - Overrides to the default plugin settings.
*/
value: function _setup(element, options) {
this.$element = element;
this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Toggler.defaults, element.data(), options);
this.className = '';
// Triggers init is idempotent, just need to make sure it is initialized
__WEBPACK_IMPORTED_MODULE_3__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a);
this._init();
this._events();
}
/**
* Initializes the Toggler plugin by parsing the toggle class from data-toggler, or animation classes from data-animate.
* @function
* @private
*/
}, {
key: '_init',
value: function _init() {
var input;
// Parse animation classes if they were set
if (this.options.animate) {
input = this.options.animate.split(' ');
this.animationIn = input[0];
this.animationOut = input[1] || null;
}
// Otherwise, parse toggle class
else {
input = this.$element.data('toggler');
// Allow for a . at the beginning of the string
this.className = input[0] === '.' ? input.slice(1) : input;
}
// Add ARIA attributes to triggers
var id = this.$element[0].id;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-open="' + id + '"], [data-close="' + id + '"], [data-toggle="' + id + '"]').attr('aria-controls', id);
// If the target is hidden, add aria-hidden
this.$element.attr('aria-expanded', this.$element.is(':hidden') ? false : true);
}
/**
* Initializes events for the toggle trigger.
* @function
* @private
*/
}, {
key: '_events',
value: function _events() {
this.$element.off('toggle.zf.trigger').on('toggle.zf.trigger', this.toggle.bind(this));
}
/**
* Toggles the target class on the target element. An event is fired from the original trigger depending on if the resultant state was "on" or "off".
* @function
* @fires Toggler#on
* @fires Toggler#off
*/
}, {
key: 'toggle',
value: function toggle() {
this[this.options.animate ? '_toggleAnimate' : '_toggleClass']();
}
}, {
key: '_toggleClass',
value: function _toggleClass() {
this.$element.toggleClass(this.className);
var isOn = this.$element.hasClass(this.className);
if (isOn) {
/**
* Fires if the target element has the class after a toggle.
* @event Toggler#on
*/
this.$element.trigger('on.zf.toggler');
} else {
/**
* Fires if the target element does not have the class after a toggle.
* @event Toggler#off
*/
this.$element.trigger('off.zf.toggler');
}
this._updateARIA(isOn);
this.$element.find('[data-mutate]').trigger('mutateme.zf.trigger');
}
}, {
key: '_toggleAnimate',
value: function _toggleAnimate() {
var _this = this;
if (this.$element.is(':hidden')) {
__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__["Motion"].animateIn(this.$element, this.animationIn, function () {
_this._updateARIA(true);
this.trigger('on.zf.toggler');
this.find('[data-mutate]').trigger('mutateme.zf.trigger');
});
} else {
__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__["Motion"].animateOut(this.$element, this.animationOut, function () {
_this._updateARIA(false);
this.trigger('off.zf.toggler');
this.find('[data-mutate]').trigger('mutateme.zf.trigger');
});
}
}
}, {
key: '_updateARIA',
value: function _updateARIA(isOn) {
this.$element.attr('aria-expanded', isOn ? true : false);
}
/**
* Destroys the instance of Toggler on the element.
* @function
*/
}, {
key: '_destroy',
value: function _destroy() {
this.$element.off('.zf.toggler');
}
}]);
return Toggler;
}(__WEBPACK_IMPORTED_MODULE_2__foundation_plugin__["Plugin"]);
Toggler.defaults = {
/**
* Tells the plugin if the element should animated when toggled.
* @option
* @type {boolean}
* @default false
*/
animate: false
};
/***/ }),
/***/ 7:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Triggers; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__);
var MutationObserver = function () {
var prefixes = ['WebKit', 'Moz', 'O', 'Ms', ''];
for (var i = 0; i < prefixes.length; i++) {
if (prefixes[i] + 'MutationObserver' in window) {
return window[prefixes[i] + 'MutationObserver'];
}
}
return false;
}();
var triggers = function (el, type) {
el.data(type).split(' ').forEach(function (id) {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id)[type === 'close' ? 'trigger' : 'triggerHandler'](type + '.zf.trigger', [el]);
});
};
var Triggers = {
Listeners: {
Basic: {},
Global: {}
},
Initializers: {}
};
Triggers.Listeners.Basic = {
openListener: function () {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'open');
},
closeListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('close');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'close');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('close.zf.trigger');
}
},
toggleListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'toggle');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('toggle.zf.trigger');
}
},
closeableListener: function (e) {
e.stopPropagation();
var animation = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('closable');
if (animation !== '') {
Foundation.Motion.animateOut(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), animation, function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('closed.zf');
});
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).fadeOut().trigger('closed.zf');
}
},
toggleFocusListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle-focus');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id).triggerHandler('toggle.zf.trigger', [__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)]);
}
};
// Elements with [data-open] will reveal a plugin that supports it when clicked.
Triggers.Initializers.addOpenListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.openListener);
$elem.on('click.zf.trigger', '[data-open]', Triggers.Listeners.Basic.openListener);
};
// Elements with [data-close] will close a plugin that supports it when clicked.
// If used without a value on [data-close], the event will bubble, allowing it to close a parent component.
Triggers.Initializers.addCloseListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.closeListener);
$elem.on('click.zf.trigger', '[data-close]', Triggers.Listeners.Basic.closeListener);
};
// Elements with [data-toggle] will toggle a plugin that supports it when clicked.
Triggers.Initializers.addToggleListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.toggleListener);
$elem.on('click.zf.trigger', '[data-toggle]', Triggers.Listeners.Basic.toggleListener);
};
// Elements with [data-closable] will respond to close.zf.trigger events.
Triggers.Initializers.addCloseableListener = function ($elem) {
$elem.off('close.zf.trigger', Triggers.Listeners.Basic.closeableListener);
$elem.on('close.zf.trigger', '[data-closeable]', Triggers.Listeners.Basic.closeableListener);
};
// Elements with [data-toggle-focus] will respond to coming in and out of focus
Triggers.Initializers.addToggleFocusListener = function ($elem) {
$elem.off('focus.zf.trigger blur.zf.trigger', Triggers.Listeners.Basic.toggleFocusListener);
$elem.on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', Triggers.Listeners.Basic.toggleFocusListener);
};
// More Global/complex listeners and triggers
Triggers.Listeners.Global = {
resizeListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('resizeme.zf.trigger');
});
}
//trigger all listening elements and signal a resize event
$nodes.attr('data-events', "resize");
},
scrollListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('scrollme.zf.trigger');
});
}
//trigger all listening elements and signal a scroll event
$nodes.attr('data-events', "scroll");
},
closeMeListener: function (e, pluginId) {
var plugin = e.namespace.split('.')[0];
var plugins = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + plugin + ']').not('[data-yeti-box="' + pluginId + '"]');
plugins.each(function () {
var _this = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this);
_this.triggerHandler('close.zf.trigger', [_this]);
});
}
};
// Global, parses whole document.
Triggers.Initializers.addClosemeListener = function (pluginName) {
var yetiBoxes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-yeti-box]'),
plugNames = ['dropdown', 'tooltip', 'reveal'];
if (pluginName) {
if (typeof pluginName === 'string') {
plugNames.push(pluginName);
} else if (typeof pluginName === 'object' && typeof pluginName[0] === 'string') {
plugNames.concat(pluginName);
} else {
console.error('Plugin names must be strings');
}
}
if (yetiBoxes.length) {
var listeners = plugNames.map(function (name) {
return 'closeme.zf.' + name;
}).join(' ');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(listeners).on(listeners, Triggers.Listeners.Global.closeMeListener);
}
};
function debounceGlobalListener(debounce, trigger, listener) {
var timer = void 0,
args = Array.prototype.slice.call(arguments, 3);
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(trigger).on(trigger, function (e) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
listener.apply(null, args);
}, debounce || 10); //default time to emit scroll event
});
}
Triggers.Initializers.addResizeListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-resize]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'resize.zf.trigger', Triggers.Listeners.Global.resizeListener, $nodes);
}
};
Triggers.Initializers.addScrollListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-scroll]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'scroll.zf.trigger', Triggers.Listeners.Global.scrollListener, $nodes);
}
};
Triggers.Initializers.addMutationEventsListener = function ($elem) {
if (!MutationObserver) {
return false;
}
var $nodes = $elem.find('[data-resize], [data-scroll], [data-mutate]');
//element callback
var listeningElementsMutation = function (mutationRecordsList) {
var $target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(mutationRecordsList[0].target);
//trigger the event handler for the element depending on type
switch (mutationRecordsList[0].type) {
case "attributes":
if ($target.attr("data-events") === "scroll" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]);
}
if ($target.attr("data-events") === "resize" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('resizeme.zf.trigger', [$target]);
}
if (mutationRecordsList[0].attributeName === "style") {
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
}
break;
case "childList":
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
break;
default:
return false;
//nothing
}
};
if ($nodes.length) {
//for each element that needs to listen for resizing, scrolling, or mutation add a single observer
for (var i = 0; i <= $nodes.length - 1; i++) {
var elementObserver = new MutationObserver(listeningElementsMutation);
elementObserver.observe($nodes[i], { attributes: true, childList: true, characterData: false, subtree: true, attributeFilter: ["data-events", "style"] });
}
}
};
Triggers.Initializers.addSimpleListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addOpenListener($document);
Triggers.Initializers.addCloseListener($document);
Triggers.Initializers.addToggleListener($document);
Triggers.Initializers.addCloseableListener($document);
Triggers.Initializers.addToggleFocusListener($document);
};
Triggers.Initializers.addGlobalListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addMutationEventsListener($document);
Triggers.Initializers.addResizeListener();
Triggers.Initializers.addScrollListener();
Triggers.Initializers.addClosemeListener();
};
Triggers.init = function ($, Foundation) {
if (typeof $.triggersInitialized === 'undefined') {
var $document = $(document);
if (document.readyState === "complete") {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
} else {
$(window).on('load', function () {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
});
}
$.triggersInitialized = true;
}
if (Foundation) {
Foundation.Triggers = Triggers;
// Legacy included to be backwards compatible for now.
Foundation.IHearYou = Triggers.Initializers.addGlobalListeners;
}
};
/***/ }),
/***/ 98:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(32);
/***/ })
/******/ }); | extend1994/cdnjs | ajax/libs/foundation/6.4.0-rc3/js/plugins/foundation.toggler.js | JavaScript | mit | 22,218 |
/*
AngularJS v1.3.11
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
(function(){'use strict';function d(b){return function(){var c=arguments[0],e;e="["+(b?b+":":"")+c+"] http://errors.angularjs.org/1.3.11/"+(b?b+"/":"")+c;for(c=1;c<arguments.length;c++){e=e+(1==c?"?":"&")+"p"+(c-1)+"=";var d=encodeURIComponent,a;a=arguments[c];a="function"==typeof a?a.toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof a?"undefined":"string"!=typeof a?JSON.stringify(a):a;e+=d(a)}return Error(e)}}(function(b){function c(a,c,b){return a[c]||(a[c]=b())}var e=d("$injector"),n=d("ng");
b=c(b,"angular",Object);b.$$minErr=b.$$minErr||d;return c(b,"module",function(){var a={};return function(b,d,g){if("hasOwnProperty"===b)throw n("badname","module");d&&a.hasOwnProperty(b)&&(a[b]=null);return c(a,b,function(){function a(b,d,e,f){f||(f=c);return function(){f[e||"push"]([b,d,arguments]);return h}}if(!d)throw e("nomod",b);var c=[],k=[],l=[],m=a("$injector","invoke","push",k),h={_invokeQueue:c,_configBlocks:k,_runBlocks:l,requires:d,name:b,provider:a("$provide","provider"),factory:a("$provide",
"factory"),service:a("$provide","service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),animation:a("$animateProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider","directive"),config:m,run:function(a){l.push(a);return this}};g&&m(g);return h})}})})(window)})(window);
//# sourceMappingURL=angular-loader.min.js.map
| barcadictni/cdnjs | ajax/libs/angular.js/1.3.11/angular-loader.min.js | JavaScript | mit | 1,534 |
/*!
* QUnit 1.13.0
* http://qunitjs.com/
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-01-04T17:09Z
*/#qunit-tests,#qunit-header,#qunit-banner,#qunit-testrunner-toolbar,#qunit-userAgent,#qunit-testresult{font-family:"Helvetica Neue Light","HelveticaNeue-Light","Helvetica Neue",Calibri,Helvetica,Arial,sans-serif}#qunit-testrunner-toolbar,#qunit-userAgent,#qunit-testresult,#qunit-tests li{font-size:small}#qunit-tests{font-size:smaller}#qunit-tests,#qunit-header,#qunit-banner,#qunit-userAgent,#qunit-testresult,#qunit-modulefilter{margin:0;padding:0}#qunit-header{padding:.5em 0 .5em 1em;color:#8699a4;background-color:#0d3349;font-size:1.5em;line-height:1em;font-weight:normal;border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;-webkit-border-top-right-radius:5px;-webkit-border-top-left-radius:5px}#qunit-header a{text-decoration:none;color:#c2ccd1}#qunit-header a:hover,#qunit-header a:focus{color:#fff}#qunit-testrunner-toolbar label{display:inline-block;padding:0 .5em 0 .1em}#qunit-banner{height:5px}#qunit-testrunner-toolbar{padding:.5em 0 .5em 2em;color:#5e740b;background-color:#eee;overflow:hidden}#qunit-userAgent{padding:.5em 0 .5em 2.5em;background-color:#2b81af;color:#fff;text-shadow:rgba(0,0,0,0.5) 2px 2px 1px}#qunit-modulefilter-container{float:right}#qunit-tests{list-style-position:inside}#qunit-tests li{padding:.4em .5em .4em 2.5em;border-bottom:1px solid #fff;list-style-position:inside}#qunit-tests.hidepass li.pass,#qunit-tests.hidepass li.running{display:none}#qunit-tests li strong{cursor:pointer}#qunit-tests li a{padding:.5em;color:#c2ccd1;text-decoration:none}#qunit-tests li a:hover,#qunit-tests li a:focus{color:#000}#qunit-tests li .runtime{float:right;font-size:smaller}.qunit-assert-list{margin-top:.5em;padding:.5em;background-color:#fff;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px}.qunit-collapsed{display:none}#qunit-tests table{border-collapse:collapse;margin-top:.2em}#qunit-tests th{text-align:right;vertical-align:top;padding:0 .5em 0 0}#qunit-tests td{vertical-align:top}#qunit-tests pre{margin:0;white-space:pre-wrap;word-wrap:break-word}#qunit-tests del{background-color:#e0f2be;color:#374e0c;text-decoration:none}#qunit-tests ins{background-color:#ffcaca;color:#500;text-decoration:none}#qunit-tests b.counts{color:black}#qunit-tests b.passed{color:#5e740b}#qunit-tests b.failed{color:#710909}#qunit-tests li li{padding:5px;background-color:#fff;border-bottom:0;list-style-position:inside}#qunit-tests li li.pass{color:#3c510c;background-color:#fff;border-left:10px solid #c6e746}#qunit-tests .pass{color:#528ce0;background-color:#d2e0e6}#qunit-tests .pass .test-name{color:#366097}#qunit-tests .pass .test-actual,#qunit-tests .pass .test-expected{color:#999}#qunit-banner.qunit-pass{background-color:#c6e746}#qunit-tests li li.fail{color:#710909;background-color:#fff;border-left:10px solid #ee5757;white-space:pre}#qunit-tests>li:last-child{border-radius:0 0 5px 5px;-moz-border-radius:0 0 5px 5px;-webkit-border-bottom-right-radius:5px;-webkit-border-bottom-left-radius:5px}#qunit-tests .fail{color:#000;background-color:#ee5757}#qunit-tests .fail .test-name,#qunit-tests .fail .module-name{color:#000}#qunit-tests .fail .test-actual{color:#ee5757}#qunit-tests .fail .test-expected{color:green}#qunit-banner.qunit-fail{background-color:#ee5757}#qunit-testresult{padding:.5em .5em .5em 2.5em;color:#2b81af;background-color:#d2e0e6;border-bottom:1px solid white}#qunit-testresult .module-name{font-weight:bold}#qunit-fixture{position:absolute;top:-10000px;left:-10000px;width:1000px;height:1000px} | nareshs435/cdnjs | ajax/libs/qunit/1.13.0/qunit.min.css | CSS | mit | 3,674 |
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Protocol/WFS.js
*/
/**
* Class: OpenLayers.Protocol.WFS.v1
* Abstract class for for v1.0.0 and v1.1.0 protocol.
*
* Inherits from:
* - <OpenLayers.Protocol>
*/
OpenLayers.Protocol.WFS.v1 = OpenLayers.Class(OpenLayers.Protocol, {
/**
* Property: version
* {String} WFS version number.
*/
version: null,
/**
* Property: srsName
* {String} Name of spatial reference system. Default is "EPSG:4326".
*/
srsName: "EPSG:4326",
/**
* Property: featureType
* {String} Local feature typeName.
*/
featureType: null,
/**
* Property: featureNS
* {String} Feature namespace.
*/
featureNS: null,
/**
* Property: geometryName
* {String} Name of the geometry attribute for features. Default is
* "the_geom" for WFS <version> 1.0, and null for higher versions.
*/
geometryName: "the_geom",
/**
* Property: schema
* {String} Optional schema location that will be included in the
* schemaLocation attribute value. Note that the feature type schema
* is required for a strict XML validator (on transactions with an
* insert for example), but is *not* required by the WFS specification
* (since the server is supposed to know about feature type schemas).
*/
schema: null,
/**
* Property: featurePrefix
* {String} Namespace alias for feature type. Default is "feature".
*/
featurePrefix: "feature",
/**
* Property: formatOptions
* {Object} Optional options for the format. If a format is not provided,
* this property can be used to extend the default format options.
*/
formatOptions: null,
/**
* Property: readFormat
* {<OpenLayers.Format>} For WFS requests it is possible to get a
* different output format than GML. In that case, we cannot parse
* the response with the default format (WFST) and we need a different
* format for reading.
*/
readFormat: null,
/**
* Property: readOptions
* {Object} Optional object to pass to format's read.
*/
readOptions: null,
/**
* Constructor: OpenLayers.Protocol.WFS
* A class for giving layers WFS protocol.
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*
* Valid options properties:
* url - {String} URL to send requests to (required).
* featureType - {String} Local (without prefix) feature typeName (required).
* featureNS - {String} Feature namespace (required, but can be autodetected
* during the first query if GML is used as readFormat and
* featurePrefix is provided and matches the prefix used by the server
* for this featureType).
* featurePrefix - {String} Feature namespace alias (optional - only used
* for writing if featureNS is provided). Default is 'feature'.
* geometryName - {String} Name of geometry attribute. The default is
* 'the_geom' for WFS <version> 1.0, and null for higher versions. If
* null, it will be set to the name of the first geometry found in the
* first read operation.
* multi - {Boolean} If set to true, geometries will be casted to Multi
* geometries before they are written in a transaction. No casting will
* be done when reading features.
*/
initialize: function(options) {
OpenLayers.Protocol.prototype.initialize.apply(this, [options]);
if(!options.format) {
this.format = OpenLayers.Format.WFST(OpenLayers.Util.extend({
version: this.version,
featureType: this.featureType,
featureNS: this.featureNS,
featurePrefix: this.featurePrefix,
geometryName: this.geometryName,
srsName: this.srsName,
schema: this.schema
}, this.formatOptions));
}
if (!options.geometryName && parseFloat(this.format.version) > 1.0) {
this.setGeometryName(null);
}
},
/**
* APIMethod: destroy
* Clean up the protocol.
*/
destroy: function() {
if(this.options && !this.options.format) {
this.format.destroy();
}
this.format = null;
OpenLayers.Protocol.prototype.destroy.apply(this);
},
/**
* APIMethod: read
* Construct a request for reading new features. Since WFS splits the
* basic CRUD operations into GetFeature requests (for read) and
* Transactions (for all others), this method does not make use of the
* format's read method (that is only about reading transaction
* responses).
*
* Parameters:
* options - {Object} Options for the read operation, in addition to the
* options set on the instance (options set here will take precedence).
*
* To use a configured protocol to get e.g. a WFS hit count, applications
* could do the following:
*
* (code)
* protocol.read({
* readOptions: {output: "object"},
* resultType: "hits",
* maxFeatures: null,
* callback: function(resp) {
* // process resp.numberOfFeatures here
* }
* });
* (end)
*
* To use a configured protocol to use WFS paging (if supported by the
* server), applications could do the following:
*
* (code)
* protocol.read({
* startIndex: 0,
* count: 50
* });
* (end)
*
* To limit the attributes returned by the GetFeature request, applications
* can use the propertyNames option to specify the properties to include in
* the response:
*
* (code)
* protocol.read({
* propertyNames: ["DURATION", "INTENSITY"]
* });
* (end)
*/
read: function(options) {
OpenLayers.Protocol.prototype.read.apply(this, arguments);
options = OpenLayers.Util.extend({}, options);
OpenLayers.Util.applyDefaults(options, this.options || {});
var response = new OpenLayers.Protocol.Response({requestType: "read"});
var data = OpenLayers.Format.XML.prototype.write.apply(
this.format, [this.format.writeNode("wfs:GetFeature", options)]
);
response.priv = OpenLayers.Request.POST({
url: options.url,
callback: this.createCallback(this.handleRead, response, options),
params: options.params,
headers: options.headers,
data: data
});
return response;
},
/**
* APIMethod: setFeatureType
* Change the feature type on the fly.
*
* Parameters:
* featureType - {String} Local (without prefix) feature typeName.
*/
setFeatureType: function(featureType) {
this.featureType = featureType;
this.format.featureType = featureType;
},
/**
* APIMethod: setGeometryName
* Sets the geometryName option after instantiation.
*
* Parameters:
* geometryName - {String} Name of geometry attribute.
*/
setGeometryName: function(geometryName) {
this.geometryName = geometryName;
this.format.geometryName = geometryName;
},
/**
* Method: handleRead
* Deal with response from the read request.
*
* Parameters:
* response - {<OpenLayers.Protocol.Response>} The response object to pass
* to the user callback.
* options - {Object} The user options passed to the read call.
*/
handleRead: function(response, options) {
options = OpenLayers.Util.extend({}, options);
OpenLayers.Util.applyDefaults(options, this.options);
if(options.callback) {
var request = response.priv;
if(request.status >= 200 && request.status < 300) {
// success
var result = this.parseResponse(request, options.readOptions);
if (result && result.success !== false) {
if (options.readOptions && options.readOptions.output == "object") {
OpenLayers.Util.extend(response, result);
} else {
response.features = result;
}
response.code = OpenLayers.Protocol.Response.SUCCESS;
} else {
// failure (service exception)
response.code = OpenLayers.Protocol.Response.FAILURE;
response.error = result;
}
} else {
// failure
response.code = OpenLayers.Protocol.Response.FAILURE;
}
options.callback.call(options.scope, response);
}
},
/**
* Method: parseResponse
* Read HTTP response body and return features
*
* Parameters:
* request - {XMLHttpRequest} The request object
* options - {Object} Optional object to pass to format's read
*
* Returns:
* {Object} or {Array({<OpenLayers.Feature.Vector>})} or
* {<OpenLayers.Feature.Vector>}
* An object with a features property, an array of features or a single
* feature.
*/
parseResponse: function(request, options) {
var doc = request.responseXML;
if(!doc || !doc.documentElement) {
doc = request.responseText;
}
if(!doc || doc.length <= 0) {
return null;
}
var result = (this.readFormat !== null) ? this.readFormat.read(doc) :
this.format.read(doc, options);
if (!this.featureNS) {
var format = this.readFormat || this.format;
this.featureNS = format.featureNS;
// no need to auto-configure again on subsequent reads
format.autoConfig = false;
if (!this.geometryName) {
this.setGeometryName(format.geometryName);
}
}
return result;
},
/**
* Method: commit
* Given a list of feature, assemble a batch request for update, create,
* and delete transactions. A commit call on the prototype amounts
* to writing a WFS transaction - so the write method on the format
* is used.
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>)}
* options - {Object}
*
* Valid options properties:
* nativeElements - {Array({Object})} Array of objects with information for writing
* out <Native> elements, these objects have vendorId, safeToIgnore and
* value properties. The <Native> element is intended to allow access to
* vendor specific capabilities of any particular web feature server or
* datastore.
*
* Returns:
* {<OpenLayers.Protocol.Response>} A response object with a features
* property containing any insertIds and a priv property referencing
* the XMLHttpRequest object.
*/
commit: function(features, options) {
options = OpenLayers.Util.extend({}, options);
OpenLayers.Util.applyDefaults(options, this.options);
var response = new OpenLayers.Protocol.Response({
requestType: "commit",
reqFeatures: features
});
response.priv = OpenLayers.Request.POST({
url: options.url,
headers: options.headers,
data: this.format.write(features, options),
callback: this.createCallback(this.handleCommit, response, options)
});
return response;
},
/**
* Method: handleCommit
* Called when the commit request returns.
*
* Parameters:
* response - {<OpenLayers.Protocol.Response>} The response object to pass
* to the user callback.
* options - {Object} The user options passed to the commit call.
*/
handleCommit: function(response, options) {
if(options.callback) {
var request = response.priv;
// ensure that we have an xml doc
var data = request.responseXML;
if(!data || !data.documentElement) {
data = request.responseText;
}
var obj = this.format.read(data) || {};
response.insertIds = obj.insertIds || [];
if (obj.success) {
response.code = OpenLayers.Protocol.Response.SUCCESS;
} else {
response.code = OpenLayers.Protocol.Response.FAILURE;
response.error = obj;
}
options.callback.call(options.scope, response);
}
},
/**
* Method: filterDelete
* Send a request that deletes all features by their filter.
*
* Parameters:
* filter - {OpenLayers.Filter} filter
*/
filterDelete: function(filter, options) {
options = OpenLayers.Util.extend({}, options);
OpenLayers.Util.applyDefaults(options, this.options);
var response = new OpenLayers.Protocol.Response({
requestType: "commit"
});
var root = this.format.createElementNSPlus("wfs:Transaction", {
attributes: {
service: "WFS",
version: this.version
}
});
var deleteNode = this.format.createElementNSPlus("wfs:Delete", {
attributes: {
typeName: (options.featureNS ? this.featurePrefix + ":" : "") +
options.featureType
}
});
if(options.featureNS) {
deleteNode.setAttribute("xmlns:" + this.featurePrefix, options.featureNS);
}
var filterNode = this.format.writeNode("ogc:Filter", filter);
deleteNode.appendChild(filterNode);
root.appendChild(deleteNode);
var data = OpenLayers.Format.XML.prototype.write.apply(
this.format, [root]
);
return OpenLayers.Request.POST({
url: this.url,
callback : options.callback || function(){},
data: data
});
},
/**
* Method: abort
* Abort an ongoing request, the response object passed to
* this method must come from this protocol (as a result
* of a read, or commit operation).
*
* Parameters:
* response - {<OpenLayers.Protocol.Response>}
*/
abort: function(response) {
if (response) {
response.priv.abort();
}
},
CLASS_NAME: "OpenLayers.Protocol.WFS.v1"
});
| ppoffice/cdnjs | ajax/libs/openlayers/2.11/lib/OpenLayers/Protocol/WFS/v1.js | JavaScript | mit | 15,117 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var weinre_protocol = location.protocol
var weinre_host = location.hostname
var weinre_port = location.port
var weinre_pathname = location.pathname
var weinre_id = "anonymous"
function doReplacements() {
var hash = location.href.split("#")[1]
if (hash) {
weinre_id = hash
}
replaceURL("url-client-ui", buildHttpURL("client/#" + weinre_id))
replaceURL("url-interfaces", buildHttpURL("interfaces/interfaces.html"))
replaceURL("url-target-demo", buildHttpURL("demo/weinre-demo.html#" + weinre_id))
replaceURL("url-target-demo-min", buildHttpURL("demo/weinre-demo-min.html#" + weinre_id))
replaceURL("url-target-script", buildHttpURL("target/target-script-min.js#" + weinre_id))
replaceURL("url-target-bookmarklet", getTargetBookmarklet(), "weinre target debug")
replaceURL("url-target-documentation", buildHttpURL("doc/"))
replaceText("version-weinre", Weinre.Versions.weinre)
replaceText("version-build", Weinre.Versions.build)
replaceText("target-bookmarklet-src-pre", getTargetBookmarklet())
replaceText("target-bookmarklet-src-text-area", getTargetBookmarklet())
replaceText("url-target-script-raw", buildHttpURL("target/target-script-min.js#" + weinre_id))
}
doReplacements();
window.onhashchange = doReplacements;
//---------------------------------------------------------------------
function buildHttpURL(uri) {
var port = weinre_port
var pathname = weinre_pathname
if (pathname == "/index.html") pathname = "/"
if (weinre_protocol == "file:") {
return uri
}
else if (weinre_protocol == "http:") {
if (port != "") port = ":" + port
return weinre_protocol + "//" + weinre_host + port + pathname + uri
}
else if (weinre_protocol == "https:") {
if (port != "") port = ":" + port
return weinre_protocol + "//" + weinre_host + port + pathname + uri
}
}
//-----------------------------------------------------------------------------
function targetBookmarkletFunction(e){
e.setAttribute("src","???");
document.getElementsByTagName("body")[0].appendChild(e);
}
//-----------------------------------------------------------------------------
function getTargetBookmarklet() {
var script = targetBookmarkletFunction.toString();
script = script.replace(/\n/g, "")
script = script.replace("targetBookmarkletFunction","")
script = script.replace(/\s*/g, "")
script = script.replace("???", buildHttpURL("target/target-script-min.js#" + weinre_id))
script = "(" + script + ')(document.createElement("script"));void(0);'
return 'javascript:' + script
}
//---------------------------------------------------------------------
function replaceURL(id, url, linkText) {
if (!linkText) linkText = url
replaceText(id, "<a href='" + url + "'>" + linkText + "</a>");
}
//---------------------------------------------------------------------
function replaceText(id, text) {
var element = document.getElementById(id)
if (null == element) {
// alert("error: can't find element with id '" + id + "'")
return
}
element.innerHTML = text
}
| Badacadabra/Harmoneezer | node_modules/browser-sync/node_modules/browser-sync-ui/node_modules/weinre/web/index.js | JavaScript | mit | 4,057 |
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
| thoughtbit/node-web-starter | express-rest-api/node_modules/function-bind/implementation.js | JavaScript | mit | 1,415 |
/**
* mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill
* v1.2.1
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*
* Date: 2014-05-14
*/
/**
* Compiled inline version. (Library mode)
*/
/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
/*globals $code */
(function(exports, undefined) {
"use strict";
var modules = {};
function require(ids, callback) {
var module, defs = [];
for (var i = 0; i < ids.length; ++i) {
module = modules[ids[i]] || resolve(ids[i]);
if (!module) {
throw 'module definition dependecy not found: ' + ids[i];
}
defs.push(module);
}
callback.apply(null, defs);
}
function define(id, dependencies, definition) {
if (typeof id !== 'string') {
throw 'invalid module definition, module id must be defined and be a string';
}
if (dependencies === undefined) {
throw 'invalid module definition, dependencies must be specified';
}
if (definition === undefined) {
throw 'invalid module definition, definition function must be specified';
}
require(dependencies, function() {
modules[id] = definition.apply(null, arguments);
});
}
function defined(id) {
return !!modules[id];
}
function resolve(id) {
var target = exports;
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length; ++fi) {
if (!target[fragments[fi]]) {
return;
}
target = target[fragments[fi]];
}
return target;
}
function expose(ids) {
for (var i = 0; i < ids.length; i++) {
var target = exports;
var id = ids[i];
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length - 1; ++fi) {
if (target[fragments[fi]] === undefined) {
target[fragments[fi]] = {};
}
target = target[fragments[fi]];
}
target[fragments[fragments.length - 1]] = modules[id];
}
}
// Included from: src/javascript/core/utils/Basic.js
/**
* Basic.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Basic', [], function() {
/**
Gets the true type of the built-in object (better version of typeof).
@author Angus Croll (http://javascriptweblog.wordpress.com/)
@method typeOf
@for Utils
@static
@param {Object} o Object to check.
@return {String} Object [[Class]]
*/
var typeOf = function(o) {
var undef;
if (o === undef) {
return 'undefined';
} else if (o === null) {
return 'null';
} else if (o.nodeType) {
return 'node';
}
// the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8
return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
};
/**
Extends the specified object with another object.
@method extend
@static
@param {Object} target Object to extend.
@param {Object} [obj]* Multiple objects to extend with.
@return {Object} Same as target, the extended object.
*/
var extend = function(target) {
var undef;
each(arguments, function(arg, i) {
if (i > 0) {
each(arg, function(value, key) {
if (value !== undef) {
if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) {
extend(target[key], value);
} else {
target[key] = value;
}
}
});
}
});
return target;
};
/**
Executes the callback function for each item in array/object. If you return false in the
callback it will break the loop.
@method each
@static
@param {Object} obj Object to iterate.
@param {function} callback Callback function to execute for each item.
*/
var each = function(obj, callback) {
var length, key, i, undef;
if (obj) {
try {
length = obj.length;
} catch(ex) {
length = undef;
}
if (length === undef) {
// Loop object items
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (callback(obj[key], key) === false) {
return;
}
}
}
} else {
// Loop array items
for (i = 0; i < length; i++) {
if (callback(obj[i], i) === false) {
return;
}
}
}
}
};
/**
Checks if object is empty.
@method isEmptyObj
@static
@param {Object} o Object to check.
@return {Boolean}
*/
var isEmptyObj = function(obj) {
var prop;
if (!obj || typeOf(obj) !== 'object') {
return true;
}
for (prop in obj) {
return false;
}
return true;
};
/**
Recieve an array of functions (usually async) to call in sequence, each function
receives a callback as first argument that it should call, when it completes. Finally,
after everything is complete, main callback is called. Passing truthy value to the
callback as a first argument will interrupt the sequence and invoke main callback
immediately.
@method inSeries
@static
@param {Array} queue Array of functions to call in sequence
@param {Function} cb Main callback that is called in the end, or in case of error
*/
var inSeries = function(queue, cb) {
var i = 0, length = queue.length;
if (typeOf(cb) !== 'function') {
cb = function() {};
}
if (!queue || !queue.length) {
cb();
}
function callNext(i) {
if (typeOf(queue[i]) === 'function') {
queue[i](function(error) {
/*jshint expr:true */
++i < length && !error ? callNext(i) : cb(error);
});
}
}
callNext(i);
};
/**
Recieve an array of functions (usually async) to call in parallel, each function
receives a callback as first argument that it should call, when it completes. After
everything is complete, main callback is called. Passing truthy value to the
callback as a first argument will interrupt the process and invoke main callback
immediately.
@method inParallel
@static
@param {Array} queue Array of functions to call in sequence
@param {Function} cb Main callback that is called in the end, or in case of erro
*/
var inParallel = function(queue, cb) {
var count = 0, num = queue.length, cbArgs = new Array(num);
each(queue, function(fn, i) {
fn(function(error) {
if (error) {
return cb(error);
}
var args = [].slice.call(arguments);
args.shift(); // strip error - undefined or not
cbArgs[i] = args;
count++;
if (count === num) {
cbArgs.unshift(null);
cb.apply(this, cbArgs);
}
});
});
};
/**
Find an element in array and return it's index if present, otherwise return -1.
@method inArray
@static
@param {Mixed} needle Element to find
@param {Array} array
@return {Int} Index of the element, or -1 if not found
*/
var inArray = function(needle, array) {
if (array) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(array, needle);
}
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === needle) {
return i;
}
}
}
return -1;
};
/**
Returns elements of first array if they are not present in second. And false - otherwise.
@private
@method arrayDiff
@param {Array} needles
@param {Array} array
@return {Array|Boolean}
*/
var arrayDiff = function(needles, array) {
var diff = [];
if (typeOf(needles) !== 'array') {
needles = [needles];
}
if (typeOf(array) !== 'array') {
array = [array];
}
for (var i in needles) {
if (inArray(needles[i], array) === -1) {
diff.push(needles[i]);
}
}
return diff.length ? diff : false;
};
/**
Find intersection of two arrays.
@private
@method arrayIntersect
@param {Array} array1
@param {Array} array2
@return {Array} Intersection of two arrays or null if there is none
*/
var arrayIntersect = function(array1, array2) {
var result = [];
each(array1, function(item) {
if (inArray(item, array2) !== -1) {
result.push(item);
}
});
return result.length ? result : null;
};
/**
Forces anything into an array.
@method toArray
@static
@param {Object} obj Object with length field.
@return {Array} Array object containing all items.
*/
var toArray = function(obj) {
var i, arr = [];
for (i = 0; i < obj.length; i++) {
arr[i] = obj[i];
}
return arr;
};
/**
Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers.
The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages
to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique.
It's more probable for the earth to be hit with an ansteriod. Y
@method guid
@static
@param {String} prefix to prepend (by default 'o' will be prepended).
@method guid
@return {String} Virtually unique id.
*/
var guid = (function() {
var counter = 0;
return function(prefix) {
var guid = new Date().getTime().toString(32), i;
for (i = 0; i < 5; i++) {
guid += Math.floor(Math.random() * 65535).toString(32);
}
return (prefix || 'o_') + guid + (counter++).toString(32);
};
}());
/**
Trims white spaces around the string
@method trim
@static
@param {String} str
@return {String}
*/
var trim = function(str) {
if (!str) {
return str;
}
return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, '');
};
/**
Parses the specified size string into a byte value. For example 10kb becomes 10240.
@method parseSizeStr
@static
@param {String/Number} size String to parse or number to just pass through.
@return {Number} Size in bytes.
*/
var parseSizeStr = function(size) {
if (typeof(size) !== 'string') {
return size;
}
var muls = {
t: 1099511627776,
g: 1073741824,
m: 1048576,
k: 1024
},
mul;
size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, ''));
mul = size[2];
size = +size[1];
if (muls.hasOwnProperty(mul)) {
size *= muls[mul];
}
return size;
};
return {
guid: guid,
typeOf: typeOf,
extend: extend,
each: each,
isEmptyObj: isEmptyObj,
inSeries: inSeries,
inParallel: inParallel,
inArray: inArray,
arrayDiff: arrayDiff,
arrayIntersect: arrayIntersect,
toArray: toArray,
trim: trim,
parseSizeStr: parseSizeStr
};
});
// Included from: src/javascript/core/I18n.js
/**
* I18n.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/I18n", [
"moxie/core/utils/Basic"
], function(Basic) {
var i18n = {};
return {
/**
* Extends the language pack object with new items.
*
* @param {Object} pack Language pack items to add.
* @return {Object} Extended language pack object.
*/
addI18n: function(pack) {
return Basic.extend(i18n, pack);
},
/**
* Translates the specified string by checking for the english string in the language pack lookup.
*
* @param {String} str String to look for.
* @return {String} Translated string or the input string if it wasn't found.
*/
translate: function(str) {
return i18n[str] || str;
},
/**
* Shortcut for translate function
*
* @param {String} str String to look for.
* @return {String} Translated string or the input string if it wasn't found.
*/
_: function(str) {
return this.translate(str);
},
/**
* Pseudo sprintf implementation - simple way to replace tokens with specified values.
*
* @param {String} str String with tokens
* @return {String} String with replaced tokens
*/
sprintf: function(str) {
var args = [].slice.call(arguments, 1);
return str.replace(/%[a-z]/g, function() {
var value = args.shift();
return Basic.typeOf(value) !== 'undefined' ? value : '';
});
}
};
});
// Included from: src/javascript/core/utils/Mime.js
/**
* Mime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/utils/Mime", [
"moxie/core/utils/Basic",
"moxie/core/I18n"
], function(Basic, I18n) {
var mimeData = "" +
"application/msword,doc dot," +
"application/pdf,pdf," +
"application/pgp-signature,pgp," +
"application/postscript,ps ai eps," +
"application/rtf,rtf," +
"application/vnd.ms-excel,xls xlb," +
"application/vnd.ms-powerpoint,ppt pps pot," +
"application/zip,zip," +
"application/x-shockwave-flash,swf swfl," +
"application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," +
"application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," +
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," +
"application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," +
"application/vnd.openxmlformats-officedocument.presentationml.template,potx," +
"application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," +
"application/x-javascript,js," +
"application/json,json," +
"audio/mpeg,mp3 mpga mpega mp2," +
"audio/x-wav,wav," +
"audio/x-m4a,m4a," +
"audio/ogg,oga ogg," +
"audio/aiff,aiff aif," +
"audio/flac,flac," +
"audio/aac,aac," +
"audio/ac3,ac3," +
"audio/x-ms-wma,wma," +
"image/bmp,bmp," +
"image/gif,gif," +
"image/jpeg,jpg jpeg jpe," +
"image/photoshop,psd," +
"image/png,png," +
"image/svg+xml,svg svgz," +
"image/tiff,tiff tif," +
"text/plain,asc txt text diff log," +
"text/html,htm html xhtml," +
"text/css,css," +
"text/csv,csv," +
"text/rtf,rtf," +
"video/mpeg,mpeg mpg mpe m2v," +
"video/quicktime,qt mov," +
"video/mp4,mp4," +
"video/x-m4v,m4v," +
"video/x-flv,flv," +
"video/x-ms-wmv,wmv," +
"video/avi,avi," +
"video/webm,webm," +
"video/3gpp,3gpp 3gp," +
"video/3gpp2,3g2," +
"video/vnd.rn-realvideo,rv," +
"video/ogg,ogv," +
"video/x-matroska,mkv," +
"application/vnd.oasis.opendocument.formula-template,otf," +
"application/octet-stream,exe";
var Mime = {
mimes: {},
extensions: {},
// Parses the default mime types string into a mimes and extensions lookup maps
addMimeType: function (mimeData) {
var items = mimeData.split(/,/), i, ii, ext;
for (i = 0; i < items.length; i += 2) {
ext = items[i + 1].split(/ /);
// extension to mime lookup
for (ii = 0; ii < ext.length; ii++) {
this.mimes[ext[ii]] = items[i];
}
// mime to extension lookup
this.extensions[items[i]] = ext;
}
},
extList2mimes: function (filters, addMissingExtensions) {
var self = this, ext, i, ii, type, mimes = [];
// convert extensions to mime types list
for (i = 0; i < filters.length; i++) {
ext = filters[i].extensions.split(/\s*,\s*/);
for (ii = 0; ii < ext.length; ii++) {
// if there's an asterisk in the list, then accept attribute is not required
if (ext[ii] === '*') {
return [];
}
type = self.mimes[ext[ii]];
if (!type) {
if (addMissingExtensions && /^\w+$/.test(ext[ii])) {
mimes.push('.' + ext[ii]);
} else {
return []; // accept all
}
} else if (Basic.inArray(type, mimes) === -1) {
mimes.push(type);
}
}
}
return mimes;
},
mimes2exts: function(mimes) {
var self = this, exts = [];
Basic.each(mimes, function(mime) {
if (mime === '*') {
exts = [];
return false;
}
// check if this thing looks like mime type
var m = mime.match(/^(\w+)\/(\*|\w+)$/);
if (m) {
if (m[2] === '*') {
// wildcard mime type detected
Basic.each(self.extensions, function(arr, mime) {
if ((new RegExp('^' + m[1] + '/')).test(mime)) {
[].push.apply(exts, self.extensions[mime]);
}
});
} else if (self.extensions[mime]) {
[].push.apply(exts, self.extensions[mime]);
}
}
});
return exts;
},
mimes2extList: function(mimes) {
var accept = [], exts = [];
if (Basic.typeOf(mimes) === 'string') {
mimes = Basic.trim(mimes).split(/\s*,\s*/);
}
exts = this.mimes2exts(mimes);
accept.push({
title: I18n.translate('Files'),
extensions: exts.length ? exts.join(',') : '*'
});
// save original mimes string
accept.mimes = mimes;
return accept;
},
getFileExtension: function(fileName) {
var matches = fileName && fileName.match(/\.([^.]+)$/);
if (matches) {
return matches[1].toLowerCase();
}
return '';
},
getFileMime: function(fileName) {
return this.mimes[this.getFileExtension(fileName)] || '';
}
};
Mime.addMimeType(mimeData);
return Mime;
});
// Included from: src/javascript/core/utils/Env.js
/**
* Env.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/utils/Env", [
"moxie/core/utils/Basic"
], function(Basic) {
// UAParser.js v0.6.2
// Lightweight JavaScript-based User-Agent string parser
// https://github.com/faisalman/ua-parser-js
//
// Copyright © 2012-2013 Faisalman <fyzlman@gmail.com>
// Dual licensed under GPLv2 & MIT
var UAParser = (function (undefined) {
//////////////
// Constants
/////////////
var EMPTY = '',
UNKNOWN = '?',
FUNC_TYPE = 'function',
UNDEF_TYPE = 'undefined',
OBJ_TYPE = 'object',
MAJOR = 'major',
MODEL = 'model',
NAME = 'name',
TYPE = 'type',
VENDOR = 'vendor',
VERSION = 'version',
ARCHITECTURE= 'architecture',
CONSOLE = 'console',
MOBILE = 'mobile',
TABLET = 'tablet';
///////////
// Helper
//////////
var util = {
has : function (str1, str2) {
return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
},
lowerize : function (str) {
return str.toLowerCase();
}
};
///////////////
// Map helper
//////////////
var mapper = {
rgx : function () {
// loop through all regexes maps
for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) {
var regex = args[i], // even sequence (0,2,4,..)
props = args[i + 1]; // odd sequence (1,3,5,..)
// construct object barebones
if (typeof(result) === UNDEF_TYPE) {
result = {};
for (p in props) {
q = props[p];
if (typeof(q) === OBJ_TYPE) {
result[q[0]] = undefined;
} else {
result[q] = undefined;
}
}
}
// try matching uastring with regexes
for (j = k = 0; j < regex.length; j++) {
matches = regex[j].exec(this.getUA());
if (!!matches) {
for (p = 0; p < props.length; p++) {
match = matches[++k];
q = props[p];
// check if given property is actually array
if (typeof(q) === OBJ_TYPE && q.length > 0) {
if (q.length == 2) {
if (typeof(q[1]) == FUNC_TYPE) {
// assign modified match
result[q[0]] = q[1].call(this, match);
} else {
// assign given value, ignore regex match
result[q[0]] = q[1];
}
} else if (q.length == 3) {
// check whether function or regex
if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) {
// call function (usually string mapper)
result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
} else {
// sanitize match using given regex
result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
}
} else if (q.length == 4) {
result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
}
} else {
result[q] = match ? match : undefined;
}
}
break;
}
}
if(!!matches) break; // break the loop immediately if match found
}
return result;
},
str : function (str, map) {
for (var i in map) {
// check if array
if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) {
for (var j = 0; j < map[i].length; j++) {
if (util.has(map[i][j], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
} else if (util.has(map[i], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
return str;
}
};
///////////////
// String map
//////////////
var maps = {
browser : {
oldsafari : {
major : {
'1' : ['/8', '/1', '/3'],
'2' : '/4',
'?' : '/'
},
version : {
'1.0' : '/8',
'1.2' : '/1',
'1.3' : '/3',
'2.0' : '/412',
'2.0.2' : '/416',
'2.0.3' : '/417',
'2.0.4' : '/419',
'?' : '/'
}
}
},
device : {
sprint : {
model : {
'Evo Shift 4G' : '7373KT'
},
vendor : {
'HTC' : 'APA',
'Sprint' : 'Sprint'
}
}
},
os : {
windows : {
version : {
'ME' : '4.90',
'NT 3.11' : 'NT3.51',
'NT 4.0' : 'NT4.0',
'2000' : 'NT 5.0',
'XP' : ['NT 5.1', 'NT 5.2'],
'Vista' : 'NT 6.0',
'7' : 'NT 6.1',
'8' : 'NT 6.2',
'8.1' : 'NT 6.3',
'RT' : 'ARM'
}
}
}
};
//////////////
// Regex map
/////////////
var regexes = {
browser : [[
// Presto based
/(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini
/(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet
/(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80
/(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80
], [NAME, VERSION, MAJOR], [
/\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit
], [[NAME, 'Opera'], VERSION, MAJOR], [
// Mixed
/(kindle)\/((\d+)?[\w\.]+)/i, // Kindle
/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i,
// Lunascape/Maxthon/Netfront/Jasmine/Blazer
// Trident based
/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i,
// Avant/IEMobile/SlimBrowser/Baidu
/(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer
// Webkit/KHTML based
/(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq
/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i
// Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron
], [NAME, VERSION, MAJOR], [
/(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11
], [[NAME, 'IE'], VERSION, MAJOR], [
/(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex
], [[NAME, 'Yandex'], VERSION, MAJOR], [
/(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon
], [[NAME, /_/g, ' '], VERSION, MAJOR], [
/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i
// Chrome/OmniWeb/Arora/Tizen/Nokia
], [NAME, VERSION, MAJOR], [
/(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin
], [[NAME, 'Dolphin'], VERSION, MAJOR], [
/((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS
], [[NAME, 'Chrome'], VERSION, MAJOR], [
/((?:android.+))version\/((\d+)?[\w\.]+)\smobile\ssafari/i // Android Browser
], [[NAME, 'Android Browser'], VERSION, MAJOR], [
/version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari
], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [
/version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile
], [VERSION, MAJOR, NAME], [
/webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0
], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [
/(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror
/(webkit|khtml)\/((\d+)?[\w\.]+)/i
], [NAME, VERSION, MAJOR], [
// Gecko based
/(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape
], [[NAME, 'Netscape'], VERSION, MAJOR], [
/(swiftfox)/i, // Swiftfox
/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i,
// IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i,
// Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
/(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla
// Other
/(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i,
// UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser
/(links)\s\(((\d+)?[\w\.]+)/i, // Links
/(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser
/(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser
/(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic
], [NAME, VERSION, MAJOR]
],
engine : [[
/(presto)\/([\w\.]+)/i, // Presto
/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links
/(icab)[\/\s]([23]\.[\d\.]+)/i // iCab
], [NAME, VERSION], [
/rv\:([\w\.]+).*(gecko)/i // Gecko
], [VERSION, NAME]
],
os : [[
// Windows based
/(windows)\snt\s6\.2;\s(arm)/i, // Windows RT
/(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [
// Mobile/Embedded OS
/\((bb)(10);/i // BlackBerry 10
], [[NAME, 'BlackBerry'], VERSION], [
/(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry
/(tizen)\/([\w\.]+)/i, // Tizen
/(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i
// Android/WebOS/Palm/QNX/Bada/RIM/MeeGo
], [NAME, VERSION], [
/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian
], [[NAME, 'Symbian'], VERSION],[
/mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS
], [[NAME, 'Firefox OS'], VERSION], [
// Console
/(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation
// GNU/Linux based
/(mint)[\/\s\(]?(\w+)*/i, // Mint
/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i,
// Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
// Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk
/(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux
/(gnu)\s?([\w\.]+)*/i // GNU
], [NAME, VERSION], [
/(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS
], [[NAME, 'Chromium OS'], VERSION],[
// Solaris
/(sunos)\s?([\w\.]+\d)*/i // Solaris
], [[NAME, 'Solaris'], VERSION], [
// BSD based
/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
], [NAME, VERSION],[
/(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS
], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [
/(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS
], [NAME, [VERSION, /_/g, '.']], [
// Other
/(haiku)\s(\w+)/i, // Haiku
/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX
/(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i,
// Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS
/(unix)\s?([\w\.]+)*/i // UNIX
], [NAME, VERSION]
]
};
/////////////////
// Constructor
////////////////
var UAParser = function (uastring) {
var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
this.getBrowser = function () {
return mapper.rgx.apply(this, regexes.browser);
};
this.getEngine = function () {
return mapper.rgx.apply(this, regexes.engine);
};
this.getOS = function () {
return mapper.rgx.apply(this, regexes.os);
};
this.getResult = function() {
return {
ua : this.getUA(),
browser : this.getBrowser(),
engine : this.getEngine(),
os : this.getOS()
};
};
this.getUA = function () {
return ua;
};
this.setUA = function (uastring) {
ua = uastring;
return this;
};
this.setUA(ua);
};
return new UAParser().getResult();
})();
function version_compare(v1, v2, operator) {
// From: http://phpjs.org/functions
// + original by: Philippe Jausions (http://pear.php.net/user/jausions)
// + original by: Aidan Lister (http://aidanlister.com/)
// + reimplemented by: Kankrelune (http://www.webfaktory.info/)
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Scott Baker
// + improved by: Theriault
// * example 1: version_compare('8.2.5rc', '8.2.5a');
// * returns 1: 1
// * example 2: version_compare('8.2.50', '8.2.52', '<');
// * returns 2: true
// * example 3: version_compare('5.3.0-dev', '5.3.0');
// * returns 3: -1
// * example 4: version_compare('4.1.0.52','4.01.0.51');
// * returns 4: 1
// Important: compare must be initialized at 0.
var i = 0,
x = 0,
compare = 0,
// vm maps textual PHP versions to negatives so they're less than 0.
// PHP currently defines these as CASE-SENSITIVE. It is important to
// leave these as negatives so that they can come before numerical versions
// and as if no letters were there to begin with.
// (1alpha is < 1 and < 1.1 but > 1dev1)
// If a non-numerical value can't be mapped to this table, it receives
// -7 as its value.
vm = {
'dev': -6,
'alpha': -5,
'a': -5,
'beta': -4,
'b': -4,
'RC': -3,
'rc': -3,
'#': -2,
'p': 1,
'pl': 1
},
// This function will be called to prepare each version argument.
// It replaces every _, -, and + with a dot.
// It surrounds any nonsequence of numbers/dots with dots.
// It replaces sequences of dots with a single dot.
// version_compare('4..0', '4.0') == 0
// Important: A string of 0 length needs to be converted into a value
// even less than an unexisting value in vm (-7), hence [-8].
// It's also important to not strip spaces because of this.
// version_compare('', ' ') == 1
prepVersion = function (v) {
v = ('' + v).replace(/[_\-+]/g, '.');
v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
return (!v.length ? [-8] : v.split('.'));
},
// This converts a version component to a number.
// Empty component becomes 0.
// Non-numerical component becomes a negative number.
// Numerical component becomes itself as an integer.
numVersion = function (v) {
return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
};
v1 = prepVersion(v1);
v2 = prepVersion(v2);
x = Math.max(v1.length, v2.length);
for (i = 0; i < x; i++) {
if (v1[i] == v2[i]) {
continue;
}
v1[i] = numVersion(v1[i]);
v2[i] = numVersion(v2[i]);
if (v1[i] < v2[i]) {
compare = -1;
break;
} else if (v1[i] > v2[i]) {
compare = 1;
break;
}
}
if (!operator) {
return compare;
}
// Important: operator is CASE-SENSITIVE.
// "No operator" seems to be treated as "<."
// Any other values seem to make the function return null.
switch (operator) {
case '>':
case 'gt':
return (compare > 0);
case '>=':
case 'ge':
return (compare >= 0);
case '<=':
case 'le':
return (compare <= 0);
case '==':
case '=':
case 'eq':
return (compare === 0);
case '<>':
case '!=':
case 'ne':
return (compare !== 0);
case '':
case '<':
case 'lt':
return (compare < 0);
default:
return null;
}
}
var can = (function() {
var caps = {
define_property: (function() {
/* // currently too much extra code required, not exactly worth it
try { // as of IE8, getters/setters are supported only on DOM elements
var obj = {};
if (Object.defineProperty) {
Object.defineProperty(obj, 'prop', {
enumerable: true,
configurable: true
});
return true;
}
} catch(ex) {}
if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
return true;
}*/
return false;
}()),
create_canvas: (function() {
// On the S60 and BB Storm, getContext exists, but always returns undefined
// so we actually have to call getContext() to verify
// github.com/Modernizr/Modernizr/issues/issue/97/
var el = document.createElement('canvas');
return !!(el.getContext && el.getContext('2d'));
}()),
return_response_type: function(responseType) {
try {
if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) {
return true;
} else if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
xhr.open('get', '/'); // otherwise Gecko throws an exception
if ('responseType' in xhr) {
xhr.responseType = responseType;
// as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?)
if (xhr.responseType !== responseType) {
return false;
}
return true;
}
}
} catch (ex) {}
return false;
},
// ideas for this heavily come from Modernizr (http://modernizr.com/)
use_data_uri: (function() {
var du = new Image();
du.onload = function() {
caps.use_data_uri = (du.width === 1 && du.height === 1);
};
setTimeout(function() {
du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
}, 1);
return false;
}()),
use_data_uri_over32kb: function() { // IE8
return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9);
},
use_data_uri_of: function(bytes) {
return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb());
},
use_fileinput: function() {
var el = document.createElement('input');
el.setAttribute('type', 'file');
return !el.disabled;
}
};
return function(cap) {
var args = [].slice.call(arguments);
args.shift(); // shift of cap
return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap];
};
}());
var Env = {
can: can,
browser: UAParser.browser.name,
version: parseFloat(UAParser.browser.major),
os: UAParser.os.name, // everybody intuitively types it in a lowercase for some reason
osVersion: UAParser.os.version,
verComp: version_compare,
swf_url: "../flash/Moxie.swf",
xap_url: "../silverlight/Moxie.xap",
global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent"
};
// for backward compatibility
// @deprecated Use `Env.os` instead
Env.OS = Env.os;
return Env;
});
// Included from: src/javascript/core/utils/Dom.js
/**
* Dom.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) {
/**
Get DOM Element by it's id.
@method get
@for Utils
@param {String} id Identifier of the DOM Element
@return {DOMElement}
*/
var get = function(id) {
if (typeof id !== 'string') {
return id;
}
return document.getElementById(id);
};
/**
Checks if specified DOM element has specified class.
@method hasClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var hasClass = function(obj, name) {
if (!obj.className) {
return false;
}
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
return regExp.test(obj.className);
};
/**
Adds specified className to specified DOM element.
@method addClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var addClass = function(obj, name) {
if (!hasClass(obj, name)) {
obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name;
}
};
/**
Removes specified className from specified DOM element.
@method removeClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var removeClass = function(obj, name) {
if (obj.className) {
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
obj.className = obj.className.replace(regExp, function($0, $1, $2) {
return $1 === ' ' && $2 === ' ' ? ' ' : '';
});
}
};
/**
Returns a given computed style of a DOM element.
@method getStyle
@static
@param {Object} obj DOM element like object.
@param {String} name Style you want to get from the DOM element
*/
var getStyle = function(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
} else if (window.getComputedStyle) {
return window.getComputedStyle(obj, null)[name];
}
};
/**
Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
@method getPos
@static
@param {Element} node HTML element or element id to get x, y position from.
@param {Element} root Optional root element to stop calculations at.
@return {object} Absolute position of the specified element object with x, y fields.
*/
var getPos = function(node, root) {
var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;
node = node;
root = root || doc.body;
// Returns the x, y cordinate for an element on IE 6 and IE 7
function getIEPos(node) {
var bodyElm, rect, x = 0, y = 0;
if (node) {
rect = node.getBoundingClientRect();
bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
x = rect.left + bodyElm.scrollLeft;
y = rect.top + bodyElm.scrollTop;
}
return {
x : x,
y : y
};
}
// Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) {
nodeRect = getIEPos(node);
rootRect = getIEPos(root);
return {
x : nodeRect.x - rootRect.x,
y : nodeRect.y - rootRect.y
};
}
parent = node;
while (parent && parent != root && parent.nodeType) {
x += parent.offsetLeft || 0;
y += parent.offsetTop || 0;
parent = parent.offsetParent;
}
parent = node.parentNode;
while (parent && parent != root && parent.nodeType) {
x -= parent.scrollLeft || 0;
y -= parent.scrollTop || 0;
parent = parent.parentNode;
}
return {
x : x,
y : y
};
};
/**
Returns the size of the specified node in pixels.
@method getSize
@static
@param {Node} node Node to get the size of.
@return {Object} Object with a w and h property.
*/
var getSize = function(node) {
return {
w : node.offsetWidth || node.clientWidth,
h : node.offsetHeight || node.clientHeight
};
};
return {
get: get,
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
getStyle: getStyle,
getPos: getPos,
getSize: getSize
};
});
// Included from: src/javascript/core/Exceptions.js
/**
* Exceptions.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/Exceptions', [
'moxie/core/utils/Basic'
], function(Basic) {
function _findKey(obj, value) {
var key;
for (key in obj) {
if (obj[key] === value) {
return key;
}
}
return null;
}
return {
RuntimeError: (function() {
var namecodes = {
NOT_INIT_ERR: 1,
NOT_SUPPORTED_ERR: 9,
JS_ERR: 4
};
function RuntimeError(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": RuntimeError " + this.code;
}
Basic.extend(RuntimeError, namecodes);
RuntimeError.prototype = Error.prototype;
return RuntimeError;
}()),
OperationNotAllowedException: (function() {
function OperationNotAllowedException(code) {
this.code = code;
this.name = 'OperationNotAllowedException';
}
Basic.extend(OperationNotAllowedException, {
NOT_ALLOWED_ERR: 1
});
OperationNotAllowedException.prototype = Error.prototype;
return OperationNotAllowedException;
}()),
ImageError: (function() {
var namecodes = {
WRONG_FORMAT: 1,
MAX_RESOLUTION_ERR: 2
};
function ImageError(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": ImageError " + this.code;
}
Basic.extend(ImageError, namecodes);
ImageError.prototype = Error.prototype;
return ImageError;
}()),
FileException: (function() {
var namecodes = {
NOT_FOUND_ERR: 1,
SECURITY_ERR: 2,
ABORT_ERR: 3,
NOT_READABLE_ERR: 4,
ENCODING_ERR: 5,
NO_MODIFICATION_ALLOWED_ERR: 6,
INVALID_STATE_ERR: 7,
SYNTAX_ERR: 8
};
function FileException(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": FileException " + this.code;
}
Basic.extend(FileException, namecodes);
FileException.prototype = Error.prototype;
return FileException;
}()),
DOMException: (function() {
var namecodes = {
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10,
INVALID_STATE_ERR: 11,
SYNTAX_ERR: 12,
INVALID_MODIFICATION_ERR: 13,
NAMESPACE_ERR: 14,
INVALID_ACCESS_ERR: 15,
VALIDATION_ERR: 16,
TYPE_MISMATCH_ERR: 17,
SECURITY_ERR: 18,
NETWORK_ERR: 19,
ABORT_ERR: 20,
URL_MISMATCH_ERR: 21,
QUOTA_EXCEEDED_ERR: 22,
TIMEOUT_ERR: 23,
INVALID_NODE_TYPE_ERR: 24,
DATA_CLONE_ERR: 25
};
function DOMException(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": DOMException " + this.code;
}
Basic.extend(DOMException, namecodes);
DOMException.prototype = Error.prototype;
return DOMException;
}()),
EventException: (function() {
function EventException(code) {
this.code = code;
this.name = 'EventException';
}
Basic.extend(EventException, {
UNSPECIFIED_EVENT_TYPE_ERR: 0
});
EventException.prototype = Error.prototype;
return EventException;
}())
};
});
// Included from: src/javascript/core/EventTarget.js
/**
* EventTarget.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/EventTarget', [
'moxie/core/Exceptions',
'moxie/core/utils/Basic'
], function(x, Basic) {
/**
Parent object for all event dispatching components and objects
@class EventTarget
@constructor EventTarget
*/
function EventTarget() {
// hash of event listeners by object uid
var eventpool = {};
Basic.extend(this, {
/**
Unique id of the event dispatcher, usually overriden by children
@property uid
@type String
*/
uid: null,
/**
Can be called from within a child in order to acquire uniqie id in automated manner
@method init
*/
init: function() {
if (!this.uid) {
this.uid = Basic.guid('uid_');
}
},
/**
Register a handler to a specific event dispatched by the object
@method addEventListener
@param {String} type Type or basically a name of the event to subscribe to
@param {Function} fn Callback function that will be called when event happens
@param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
@param {Object} [scope=this] A scope to invoke event handler in
*/
addEventListener: function(type, fn, priority, scope) {
var self = this, list;
type = Basic.trim(type);
if (/\s/.test(type)) {
// multiple event types were passed for one handler
Basic.each(type.split(/\s+/), function(type) {
self.addEventListener(type, fn, priority, scope);
});
return;
}
type = type.toLowerCase();
priority = parseInt(priority, 10) || 0;
list = eventpool[this.uid] && eventpool[this.uid][type] || [];
list.push({fn : fn, priority : priority, scope : scope || this});
if (!eventpool[this.uid]) {
eventpool[this.uid] = {};
}
eventpool[this.uid][type] = list;
},
/**
Check if any handlers were registered to the specified event
@method hasEventListener
@param {String} type Type or basically a name of the event to check
@return {Mixed} Returns a handler if it was found and false, if - not
*/
hasEventListener: function(type) {
return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid];
},
/**
Unregister the handler from the event, or if former was not specified - unregister all handlers
@method removeEventListener
@param {String} type Type or basically a name of the event
@param {Function} [fn] Handler to unregister
*/
removeEventListener: function(type, fn) {
type = type.toLowerCase();
var list = eventpool[this.uid] && eventpool[this.uid][type], i;
if (list) {
if (fn) {
for (i = list.length - 1; i >= 0; i--) {
if (list[i].fn === fn) {
list.splice(i, 1);
break;
}
}
} else {
list = [];
}
// delete event list if it has become empty
if (!list.length) {
delete eventpool[this.uid][type];
// and object specific entry in a hash if it has no more listeners attached
if (Basic.isEmptyObj(eventpool[this.uid])) {
delete eventpool[this.uid];
}
}
}
},
/**
Remove all event handlers from the object
@method removeAllEventListeners
*/
removeAllEventListeners: function() {
if (eventpool[this.uid]) {
delete eventpool[this.uid];
}
},
/**
Dispatch the event
@method dispatchEvent
@param {String/Object} Type of event or event object to dispatch
@param {Mixed} [...] Variable number of arguments to be passed to a handlers
@return {Boolean} true by default and false if any handler returned false
*/
dispatchEvent: function(type) {
var uid, list, args, tmpEvt, evt = {}, result = true, undef;
if (Basic.typeOf(type) !== 'string') {
// we can't use original object directly (because of Silverlight)
tmpEvt = type;
if (Basic.typeOf(tmpEvt.type) === 'string') {
type = tmpEvt.type;
if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event
evt.total = tmpEvt.total;
evt.loaded = tmpEvt.loaded;
}
evt.async = tmpEvt.async || false;
} else {
throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR);
}
}
// check if event is meant to be dispatched on an object having specific uid
if (type.indexOf('::') !== -1) {
(function(arr) {
uid = arr[0];
type = arr[1];
}(type.split('::')));
} else {
uid = this.uid;
}
type = type.toLowerCase();
list = eventpool[uid] && eventpool[uid][type];
if (list) {
// sort event list by prority
list.sort(function(a, b) { return b.priority - a.priority; });
args = [].slice.call(arguments);
// first argument will be pseudo-event object
args.shift();
evt.type = type;
args.unshift(evt);
// Dispatch event to all listeners
var queue = [];
Basic.each(list, function(handler) {
// explicitly set the target, otherwise events fired from shims do not get it
args[0].target = handler.scope;
// if event is marked as async, detach the handler
if (evt.async) {
queue.push(function(cb) {
setTimeout(function() {
cb(handler.fn.apply(handler.scope, args) === false);
}, 1);
});
} else {
queue.push(function(cb) {
cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation
});
}
});
if (queue.length) {
Basic.inSeries(queue, function(err) {
result = !err;
});
}
}
return result;
},
/**
Alias for addEventListener
@method bind
@protected
*/
bind: function() {
this.addEventListener.apply(this, arguments);
},
/**
Alias for removeEventListener
@method unbind
@protected
*/
unbind: function() {
this.removeEventListener.apply(this, arguments);
},
/**
Alias for removeAllEventListeners
@method unbindAll
@protected
*/
unbindAll: function() {
this.removeAllEventListeners.apply(this, arguments);
},
/**
Alias for dispatchEvent
@method trigger
@protected
*/
trigger: function() {
return this.dispatchEvent.apply(this, arguments);
},
/**
Converts properties of on[event] type to corresponding event handlers,
is used to avoid extra hassle around the process of calling them back
@method convertEventPropsToHandlers
@private
*/
convertEventPropsToHandlers: function(handlers) {
var h;
if (Basic.typeOf(handlers) !== 'array') {
handlers = [handlers];
}
for (var i = 0; i < handlers.length; i++) {
h = 'on' + handlers[i];
if (Basic.typeOf(this[h]) === 'function') {
this.addEventListener(handlers[i], this[h]);
} else if (Basic.typeOf(this[h]) === 'undefined') {
this[h] = null; // object must have defined event properties, even if it doesn't make use of them
}
}
}
});
}
EventTarget.instance = new EventTarget();
return EventTarget;
});
// Included from: src/javascript/core/utils/Encode.js
/**
* Encode.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Encode', [], function() {
/**
Encode string with UTF-8
@method utf8_encode
@for Utils
@static
@param {String} str String to encode
@return {String} UTF-8 encoded string
*/
var utf8_encode = function(str) {
return unescape(encodeURIComponent(str));
};
/**
Decode UTF-8 encoded string
@method utf8_decode
@static
@param {String} str String to decode
@return {String} Decoded string
*/
var utf8_decode = function(str_data) {
return decodeURIComponent(escape(str_data));
};
/**
Decode Base64 encoded string (uses browser's default method if available),
from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js
@method atob
@static
@param {String} data String to decode
@return {String} Decoded string
*/
var atob = function(data, utf8) {
if (typeof(window.atob) === 'function') {
return utf8 ? utf8_decode(window.atob(data)) : window.atob(data);
}
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Thunder.m
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
// * returns 1: 'Kevin van Zonneveld'
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window.atob == 'function') {
// return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return utf8 ? utf8_decode(dec) : dec;
};
/**
Base64 encode string (uses browser's default method if available),
from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js
@method btoa
@static
@param {String} data String to encode
@return {String} Base64 encoded string
*/
var btoa = function(data, utf8) {
if (utf8) {
utf8_encode(data);
}
if (typeof(window.btoa) === 'function') {
return window.btoa(data);
}
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafał Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
};
return {
utf8_encode: utf8_encode,
utf8_decode: utf8_decode,
atob: atob,
btoa: btoa
};
});
// Included from: src/javascript/runtime/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/Runtime', [
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/EventTarget"
], function(Basic, Dom, EventTarget) {
var runtimeConstructors = {}, runtimes = {};
/**
Common set of methods and properties for every runtime instance
@class Runtime
@param {Object} options
@param {String} type Sanitized name of the runtime
@param {Object} [caps] Set of capabilities that differentiate specified runtime
@param {Object} [modeCaps] Set of capabilities that do require specific operational mode
@param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested
*/
function Runtime(options, type, caps, modeCaps, preferredMode) {
/**
Dispatched when runtime is initialized and ready.
Results in RuntimeInit on a connected component.
@event Init
*/
/**
Dispatched when runtime fails to initialize.
Results in RuntimeError on a connected component.
@event Error
*/
var self = this
, _shim
, _uid = Basic.guid(type + '_')
, defaultMode = preferredMode || 'browser'
;
options = options || {};
// register runtime in private hash
runtimes[_uid] = this;
/**
Default set of capabilities, which can be redifined later by specific runtime
@private
@property caps
@type Object
*/
caps = Basic.extend({
// Runtime can:
// provide access to raw binary data of the file
access_binary: false,
// provide access to raw binary data of the image (image extension is optional)
access_image_binary: false,
// display binary data as thumbs for example
display_media: false,
// make cross-domain requests
do_cors: false,
// accept files dragged and dropped from the desktop
drag_and_drop: false,
// filter files in selection dialog by their extensions
filter_by_extension: true,
// resize image (and manipulate it raw data of any file in general)
resize_image: false,
// periodically report how many bytes of total in the file were uploaded (loaded)
report_upload_progress: false,
// provide access to the headers of http response
return_response_headers: false,
// support response of specific type, which should be passed as an argument
// e.g. runtime.can('return_response_type', 'blob')
return_response_type: false,
// return http status code of the response
return_status_code: true,
// send custom http header with the request
send_custom_headers: false,
// pick up the files from a dialog
select_file: false,
// select whole folder in file browse dialog
select_folder: false,
// select multiple files at once in file browse dialog
select_multiple: true,
// send raw binary data, that is generated after image resizing or manipulation of other kind
send_binary_string: false,
// send cookies with http request and therefore retain session
send_browser_cookies: true,
// send data formatted as multipart/form-data
send_multipart: true,
// slice the file or blob to smaller parts
slice_blob: false,
// upload file without preloading it to memory, stream it out directly from disk
stream_upload: false,
// programmatically trigger file browse dialog
summon_file_dialog: false,
// upload file of specific size, size should be passed as argument
// e.g. runtime.can('upload_filesize', '500mb')
upload_filesize: true,
// initiate http request with specific http method, method should be passed as argument
// e.g. runtime.can('use_http_method', 'put')
use_http_method: true
}, caps);
// default to the mode that is compatible with preferred caps
if (options.preferred_caps) {
defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode);
}
// small extension factory here (is meant to be extended with actual extensions constructors)
_shim = (function() {
var objpool = {};
return {
exec: function(uid, comp, fn, args) {
if (_shim[comp]) {
if (!objpool[uid]) {
objpool[uid] = {
context: this,
instance: new _shim[comp]()
};
}
if (objpool[uid].instance[fn]) {
return objpool[uid].instance[fn].apply(this, args);
}
}
},
removeInstance: function(uid) {
delete objpool[uid];
},
removeAllInstances: function() {
var self = this;
Basic.each(objpool, function(obj, uid) {
if (Basic.typeOf(obj.instance.destroy) === 'function') {
obj.instance.destroy.call(obj.context);
}
self.removeInstance(uid);
});
}
};
}());
// public methods
Basic.extend(this, {
/**
Specifies whether runtime instance was initialized or not
@property initialized
@type {Boolean}
@default false
*/
initialized: false, // shims require this flag to stop initialization retries
/**
Unique ID of the runtime
@property uid
@type {String}
*/
uid: _uid,
/**
Runtime type (e.g. flash, html5, etc)
@property type
@type {String}
*/
type: type,
/**
Runtime (not native one) may operate in browser or client mode.
@property mode
@private
@type {String|Boolean} current mode or false, if none possible
*/
mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode),
/**
id of the DOM container for the runtime (if available)
@property shimid
@type {String}
*/
shimid: _uid + '_container',
/**
Number of connected clients. If equal to zero, runtime can be destroyed
@property clients
@type {Number}
*/
clients: 0,
/**
Runtime initialization options
@property options
@type {Object}
*/
options: options,
/**
Checks if the runtime has specific capability
@method can
@param {String} cap Name of capability to check
@param {Mixed} [value] If passed, capability should somehow correlate to the value
@param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set)
@return {Boolean} true if runtime has such capability and false, if - not
*/
can: function(cap, value) {
var refCaps = arguments[2] || caps;
// if cap var is a comma-separated list of caps, convert it to object (key/value)
if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') {
cap = Runtime.parseCaps(cap);
}
if (Basic.typeOf(cap) === 'object') {
for (var key in cap) {
if (!this.can(key, cap[key], refCaps)) {
return false;
}
}
return true;
}
// check the individual cap
if (Basic.typeOf(refCaps[cap]) === 'function') {
return refCaps[cap].call(this, value);
} else {
return (value === refCaps[cap]);
}
},
/**
Returns container for the runtime as DOM element
@method getShimContainer
@return {DOMElement}
*/
getShimContainer: function() {
var container, shimContainer = Dom.get(this.shimid);
// if no container for shim, create one
if (!shimContainer) {
container = this.options.container ? Dom.get(this.options.container) : document.body;
// create shim container and insert it at an absolute position into the outer container
shimContainer = document.createElement('div');
shimContainer.id = this.shimid;
shimContainer.className = 'moxie-shim moxie-shim-' + this.type;
Basic.extend(shimContainer.style, {
position: 'absolute',
top: '0px',
left: '0px',
width: '1px',
height: '1px',
overflow: 'hidden'
});
container.appendChild(shimContainer);
container = null;
}
return shimContainer;
},
/**
Returns runtime as DOM element (if appropriate)
@method getShim
@return {DOMElement}
*/
getShim: function() {
return _shim;
},
/**
Invokes a method within the runtime itself (might differ across the runtimes)
@method shimExec
@param {Mixed} []
@protected
@return {Mixed} Depends on the action and component
*/
shimExec: function(component, action) {
var args = [].slice.call(arguments, 2);
return self.getShim().exec.call(this, this.uid, component, action, args);
},
/**
Operaional interface that is used by components to invoke specific actions on the runtime
(is invoked in the scope of component)
@method exec
@param {Mixed} []*
@protected
@return {Mixed} Depends on the action and component
*/
exec: function(component, action) { // this is called in the context of component, not runtime
var args = [].slice.call(arguments, 2);
if (self[component] && self[component][action]) {
return self[component][action].apply(this, args);
}
return self.shimExec.apply(this, arguments);
},
/**
Destroys the runtime (removes all events and deletes DOM structures)
@method destroy
*/
destroy: function() {
if (!self) {
return; // obviously already destroyed
}
var shimContainer = Dom.get(this.shimid);
if (shimContainer) {
shimContainer.parentNode.removeChild(shimContainer);
}
if (_shim) {
_shim.removeAllInstances();
}
this.unbindAll();
delete runtimes[this.uid];
this.uid = null; // mark this runtime as destroyed
_uid = self = _shim = shimContainer = null;
}
});
// once we got the mode, test against all caps
if (this.mode && options.required_caps && !this.can(options.required_caps)) {
this.mode = false;
}
}
/**
Default order to try different runtime types
@property order
@type String
@static
*/
Runtime.order = 'html5,flash,silverlight,html4';
/**
Retrieves runtime from private hash by it's uid
@method getRuntime
@private
@static
@param {String} uid Unique identifier of the runtime
@return {Runtime|Boolean} Returns runtime, if it exists and false, if - not
*/
Runtime.getRuntime = function(uid) {
return runtimes[uid] ? runtimes[uid] : false;
};
/**
Register constructor for the Runtime of new (or perhaps modified) type
@method addConstructor
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@param {Function} construct Constructor for the Runtime type
*/
Runtime.addConstructor = function(type, constructor) {
constructor.prototype = EventTarget.instance;
runtimeConstructors[type] = constructor;
};
/**
Get the constructor for the specified type.
method getConstructor
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@return {Function} Constructor for the Runtime type
*/
Runtime.getConstructor = function(type) {
return runtimeConstructors[type] || null;
};
/**
Get info about the runtime (uid, type, capabilities)
@method getInfo
@static
@param {String} uid Unique identifier of the runtime
@return {Mixed} Info object or null if runtime doesn't exist
*/
Runtime.getInfo = function(uid) {
var runtime = Runtime.getRuntime(uid);
if (runtime) {
return {
uid: runtime.uid,
type: runtime.type,
mode: runtime.mode,
can: function() {
return runtime.can.apply(runtime, arguments);
}
};
}
return null;
};
/**
Convert caps represented by a comma-separated string to the object representation.
@method parseCaps
@static
@param {String} capStr Comma-separated list of capabilities
@return {Object}
*/
Runtime.parseCaps = function(capStr) {
var capObj = {};
if (Basic.typeOf(capStr) !== 'string') {
return capStr || {};
}
Basic.each(capStr.split(','), function(key) {
capObj[key] = true; // we assume it to be - true
});
return capObj;
};
/**
Test the specified runtime for specific capabilities.
@method can
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@param {String|Object} caps Set of capabilities to check
@return {Boolean} Result of the test
*/
Runtime.can = function(type, caps) {
var runtime
, constructor = Runtime.getConstructor(type)
, mode
;
if (constructor) {
runtime = new constructor({
required_caps: caps
});
mode = runtime.mode;
runtime.destroy();
return !!mode;
}
return false;
};
/**
Figure out a runtime that supports specified capabilities.
@method thatCan
@static
@param {String|Object} caps Set of capabilities to check
@param {String} [runtimeOrder] Comma-separated list of runtimes to check against
@return {String} Usable runtime identifier or null
*/
Runtime.thatCan = function(caps, runtimeOrder) {
var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/);
for (var i in types) {
if (Runtime.can(types[i], caps)) {
return types[i];
}
}
return null;
};
/**
Figure out an operational mode for the specified set of capabilities.
@method getMode
@static
@param {Object} modeCaps Set of capabilities that depend on particular runtime mode
@param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for
@param {String|Boolean} [defaultMode='browser'] Default mode to use
@return {String|Boolean} Compatible operational mode
*/
Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) {
var mode = null;
if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified
defaultMode = 'browser';
}
if (requiredCaps && !Basic.isEmptyObj(modeCaps)) {
// loop over required caps and check if they do require the same mode
Basic.each(requiredCaps, function(value, cap) {
if (modeCaps.hasOwnProperty(cap)) {
var capMode = modeCaps[cap](value);
// make sure we always have an array
if (typeof(capMode) === 'string') {
capMode = [capMode];
}
if (!mode) {
mode = capMode;
} else if (!(mode = Basic.arrayIntersect(mode, capMode))) {
// if cap requires conflicting mode - runtime cannot fulfill required caps
return (mode = false);
}
}
});
if (mode) {
return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0];
} else if (mode === false) {
return false;
}
}
return defaultMode;
};
/**
Capability check that always returns true
@private
@static
@return {True}
*/
Runtime.capTrue = function() {
return true;
};
/**
Capability check that always returns false
@private
@static
@return {False}
*/
Runtime.capFalse = function() {
return false;
};
/**
Evaluate the expression to boolean value and create a function that always returns it.
@private
@static
@param {Mixed} expr Expression to evaluate
@return {Function} Function returning the result of evaluation
*/
Runtime.capTest = function(expr) {
return function() {
return !!expr;
};
};
return Runtime;
});
// Included from: src/javascript/runtime/RuntimeClient.js
/**
* RuntimeClient.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/RuntimeClient', [
'moxie/core/Exceptions',
'moxie/core/utils/Basic',
'moxie/runtime/Runtime'
], function(x, Basic, Runtime) {
/**
Set of methods and properties, required by a component to acquire ability to connect to a runtime
@class RuntimeClient
*/
return function RuntimeClient() {
var runtime;
Basic.extend(this, {
/**
Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
Increments number of clients connected to the specified runtime.
@method connectRuntime
@param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
*/
connectRuntime: function(options) {
var comp = this, ruid;
function initialize(items) {
var type, constructor;
// if we ran out of runtimes
if (!items.length) {
comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
runtime = null;
return;
}
type = items.shift();
constructor = Runtime.getConstructor(type);
if (!constructor) {
initialize(items);
return;
}
// try initializing the runtime
runtime = new constructor(options);
runtime.bind('Init', function() {
// mark runtime as initialized
runtime.initialized = true;
// jailbreak ...
setTimeout(function() {
runtime.clients++;
// this will be triggered on component
comp.trigger('RuntimeInit', runtime);
}, 1);
});
runtime.bind('Error', function() {
runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
initialize(items);
});
/*runtime.bind('Exception', function() { });*/
// check if runtime managed to pick-up operational mode
if (!runtime.mode) {
runtime.trigger('Error');
return;
}
runtime.init();
}
// check if a particular runtime was requested
if (Basic.typeOf(options) === 'string') {
ruid = options;
} else if (Basic.typeOf(options.ruid) === 'string') {
ruid = options.ruid;
}
if (ruid) {
runtime = Runtime.getRuntime(ruid);
if (runtime) {
runtime.clients++;
return runtime;
} else {
// there should be a runtime and there's none - weird case
throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
}
}
// initialize a fresh one, that fits runtime list and required features best
initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
},
/**
Returns the runtime to which the client is currently connected.
@method getRuntime
@return {Runtime} Runtime or null if client is not connected
*/
getRuntime: function() {
if (runtime && runtime.uid) {
return runtime;
}
runtime = null; // make sure we do not leave zombies rambling around
return null;
},
/**
Disconnects from the runtime. Decrements number of clients connected to the specified runtime.
@method disconnectRuntime
*/
disconnectRuntime: function() {
if (runtime && --runtime.clients <= 0) {
runtime.destroy();
runtime = null;
}
}
});
};
});
// Included from: src/javascript/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/Blob', [
'moxie/core/utils/Basic',
'moxie/core/utils/Encode',
'moxie/runtime/RuntimeClient'
], function(Basic, Encode, RuntimeClient) {
var blobpool = {};
/**
@class Blob
@constructor
@param {String} ruid Unique id of the runtime, to which this blob belongs to
@param {Object} blob Object "Native" blob object, as it is represented in the runtime
*/
function Blob(ruid, blob) {
function _sliceDetached(start, end, type) {
var blob, data = blobpool[this.uid];
if (Basic.typeOf(data) !== 'string' || !data.length) {
return null; // or throw exception
}
blob = new Blob(null, {
type: type,
size: end - start
});
blob.detach(data.substr(start, blob.size));
return blob;
}
RuntimeClient.call(this);
if (ruid) {
this.connectRuntime(ruid);
}
if (!blob) {
blob = {};
} else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string
blob = { data: blob };
}
Basic.extend(this, {
/**
Unique id of the component
@property uid
@type {String}
*/
uid: blob.uid || Basic.guid('uid_'),
/**
Unique id of the connected runtime, if falsy, then runtime will have to be initialized
before this Blob can be used, modified or sent
@property ruid
@type {String}
*/
ruid: ruid,
/**
Size of blob
@property size
@type {Number}
@default 0
*/
size: blob.size || 0,
/**
Mime type of blob
@property type
@type {String}
@default ''
*/
type: blob.type || '',
/**
@method slice
@param {Number} [start=0]
*/
slice: function(start, end, type) {
if (this.isDetached()) {
return _sliceDetached.apply(this, arguments);
}
return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type);
},
/**
Returns "native" blob object (as it is represented in connected runtime) or null if not found
@method getSource
@return {Blob} Returns "native" blob object or null if not found
*/
getSource: function() {
if (!blobpool[this.uid]) {
return null;
}
return blobpool[this.uid];
},
/**
Detaches blob from any runtime that it depends on and initialize with standalone value
@method detach
@protected
@param {DOMString} [data=''] Standalone value
*/
detach: function(data) {
if (this.ruid) {
this.getRuntime().exec.call(this, 'Blob', 'destroy');
this.disconnectRuntime();
this.ruid = null;
}
data = data || '';
// if dataUrl, convert to binary string
var matches = data.match(/^data:([^;]*);base64,/);
if (matches) {
this.type = matches[1];
data = Encode.atob(data.substring(data.indexOf('base64,') + 7));
}
this.size = data.length;
blobpool[this.uid] = data;
},
/**
Checks if blob is standalone (detached of any runtime)
@method isDetached
@protected
@return {Boolean}
*/
isDetached: function() {
return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string';
},
/**
Destroy Blob and free any resources it was using
@method destroy
*/
destroy: function() {
this.detach();
delete blobpool[this.uid];
}
});
if (blob.data) {
this.detach(blob.data); // auto-detach if payload has been passed
} else {
blobpool[this.uid] = blob;
}
}
return Blob;
});
// Included from: src/javascript/file/File.js
/**
* File.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/File', [
'moxie/core/utils/Basic',
'moxie/core/utils/Mime',
'moxie/file/Blob'
], function(Basic, Mime, Blob) {
/**
@class File
@extends Blob
@constructor
@param {String} ruid Unique id of the runtime, to which this blob belongs to
@param {Object} file Object "Native" file object, as it is represented in the runtime
*/
function File(ruid, file) {
var name, type;
if (!file) { // avoid extra errors in case we overlooked something
file = {};
}
// figure out the type
if (file.type && file.type !== '') {
type = file.type;
} else {
type = Mime.getFileMime(file.name);
}
// sanitize file name or generate new one
if (file.name) {
name = file.name.replace(/\\/g, '/');
name = name.substr(name.lastIndexOf('/') + 1);
} else {
var prefix = type.split('/')[0];
name = Basic.guid((prefix !== '' ? prefix : 'file') + '_');
if (Mime.extensions[type]) {
name += '.' + Mime.extensions[type][0]; // append proper extension if possible
}
}
Blob.apply(this, arguments);
Basic.extend(this, {
/**
File mime type
@property type
@type {String}
@default ''
*/
type: type || '',
/**
File name
@property name
@type {String}
@default UID
*/
name: name || Basic.guid('file_'),
/**
Relative path to the file inside a directory
@property relativePath
@type {String}
@default ''
*/
relativePath: '',
/**
Date of last modification
@property lastModifiedDate
@type {String}
@default now
*/
lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
});
}
File.prototype = Blob.prototype;
return File;
});
// Included from: src/javascript/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileInput', [
'moxie/core/utils/Basic',
'moxie/core/utils/Mime',
'moxie/core/utils/Dom',
'moxie/core/Exceptions',
'moxie/core/EventTarget',
'moxie/core/I18n',
'moxie/file/File',
'moxie/runtime/Runtime',
'moxie/runtime/RuntimeClient'
], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) {
/**
Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click,
converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory
with _FileReader_ or uploaded to a server through _XMLHttpRequest_.
@class FileInput
@constructor
@extends EventTarget
@uses RuntimeClient
@param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_.
@param {String|DOMElement} options.browse_button DOM Element to turn into file picker.
@param {Array} [options.accept] Array of mime types to accept. By default accepts all.
@param {String} [options.file='file'] Name of the file field (not the filename).
@param {Boolean} [options.multiple=false] Enable selection of multiple files.
@param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time).
@param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode
for _browse\_button_.
@param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support.
@example
<div id="container">
<a id="file-picker" href="javascript:;">Browse...</a>
</div>
<script>
var fileInput = new mOxie.FileInput({
browse_button: 'file-picker', // or document.getElementById('file-picker')
container: 'container',
accept: [
{title: "Image files", extensions: "jpg,gif,png"} // accept only images
],
multiple: true // allow multiple file selection
});
fileInput.onchange = function(e) {
// do something to files array
console.info(e.target.files); // or this.files or fileInput.files
};
fileInput.init(); // initialize
</script>
*/
var dispatches = [
/**
Dispatched when runtime is connected and file-picker is ready to be used.
@event ready
@param {Object} event
*/
'ready',
/**
Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked.
Check [corresponding documentation entry](#method_refresh) for more info.
@event refresh
@param {Object} event
*/
/**
Dispatched when selection of files in the dialog is complete.
@event change
@param {Object} event
*/
'change',
'cancel', // TODO: might be useful
/**
Dispatched when mouse cursor enters file-picker area. Can be used to style element
accordingly.
@event mouseenter
@param {Object} event
*/
'mouseenter',
/**
Dispatched when mouse cursor leaves file-picker area. Can be used to style element
accordingly.
@event mouseleave
@param {Object} event
*/
'mouseleave',
/**
Dispatched when functional mouse button is pressed on top of file-picker area.
@event mousedown
@param {Object} event
*/
'mousedown',
/**
Dispatched when functional mouse button is released on top of file-picker area.
@event mouseup
@param {Object} event
*/
'mouseup'
];
function FileInput(options) {
var self = this,
container, browseButton, defaults;
// if flat argument passed it should be browse_button id
if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) {
options = { browse_button : options };
}
// this will help us to find proper default container
browseButton = Dom.get(options.browse_button);
if (!browseButton) {
// browse button is required
throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
}
// figure out the options
defaults = {
accept: [{
title: I18n.translate('All Files'),
extensions: '*'
}],
name: 'file',
multiple: false,
required_caps: false,
container: browseButton.parentNode || document.body
};
options = Basic.extend({}, defaults, options);
// convert to object representation
if (typeof(options.required_caps) === 'string') {
options.required_caps = Runtime.parseCaps(options.required_caps);
}
// normalize accept option (could be list of mime types or array of title/extensions pairs)
if (typeof(options.accept) === 'string') {
options.accept = Mime.mimes2extList(options.accept);
}
container = Dom.get(options.container);
// make sure we have container
if (!container) {
container = document.body;
}
// make container relative, if it's not
if (Dom.getStyle(container, 'position') === 'static') {
container.style.position = 'relative';
}
container = browseButton = null; // IE
RuntimeClient.call(self);
Basic.extend(self, {
/**
Unique id of the component
@property uid
@protected
@readOnly
@type {String}
@default UID
*/
uid: Basic.guid('uid_'),
/**
Unique id of the connected runtime, if any.
@property ruid
@protected
@type {String}
*/
ruid: null,
/**
Unique id of the runtime container. Useful to get hold of it for various manipulations.
@property shimid
@protected
@type {String}
*/
shimid: null,
/**
Array of selected mOxie.File objects
@property files
@type {Array}
@default null
*/
files: null,
/**
Initializes the file-picker, connects it to runtime and dispatches event ready when done.
@method init
*/
init: function() {
self.convertEventPropsToHandlers(dispatches);
self.bind('RuntimeInit', function(e, runtime) {
self.ruid = runtime.uid;
self.shimid = runtime.shimid;
self.bind("Ready", function() {
self.trigger("Refresh");
}, 999);
self.bind("Change", function() {
var files = runtime.exec.call(self, 'FileInput', 'getFiles');
self.files = [];
Basic.each(files, function(file) {
// ignore empty files (IE10 for example hangs if you try to send them via XHR)
if (file.size === 0) {
return true;
}
self.files.push(new File(self.ruid, file));
});
}, 999);
// re-position and resize shim container
self.bind('Refresh', function() {
var pos, size, browseButton, shimContainer;
browseButton = Dom.get(options.browse_button);
shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist
if (browseButton) {
pos = Dom.getPos(browseButton, Dom.get(options.container));
size = Dom.getSize(browseButton);
if (shimContainer) {
Basic.extend(shimContainer.style, {
top : pos.y + 'px',
left : pos.x + 'px',
width : size.w + 'px',
height : size.h + 'px'
});
}
}
shimContainer = browseButton = null;
});
runtime.exec.call(self, 'FileInput', 'init', options);
});
// runtime needs: options.required_features, options.runtime_order and options.container
self.connectRuntime(Basic.extend({}, options, {
required_caps: {
select_file: true
}
}));
},
/**
Disables file-picker element, so that it doesn't react to mouse clicks.
@method disable
@param {Boolean} [state=true] Disable component if - true, enable if - false
*/
disable: function(state) {
var runtime = this.getRuntime();
if (runtime) {
runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state);
}
},
/**
Reposition and resize dialog trigger to match the position and size of browse_button element.
@method refresh
*/
refresh: function() {
self.trigger("Refresh");
},
/**
Destroy component.
@method destroy
*/
destroy: function() {
var runtime = this.getRuntime();
if (runtime) {
runtime.exec.call(this, 'FileInput', 'destroy');
this.disconnectRuntime();
}
if (Basic.typeOf(this.files) === 'array') {
// no sense in leaving associated files behind
Basic.each(this.files, function(file) {
file.destroy();
});
}
this.files = null;
}
});
}
FileInput.prototype = EventTarget.instance;
return FileInput;
});
// Included from: src/javascript/runtime/RuntimeTarget.js
/**
* RuntimeTarget.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/RuntimeTarget', [
'moxie/core/utils/Basic',
'moxie/runtime/RuntimeClient',
"moxie/core/EventTarget"
], function(Basic, RuntimeClient, EventTarget) {
/**
Instance of this class can be used as a target for the events dispatched by shims,
when allowing them onto components is for either reason inappropriate
@class RuntimeTarget
@constructor
@protected
@extends EventTarget
*/
function RuntimeTarget() {
this.uid = Basic.guid('uid_');
RuntimeClient.call(this);
this.destroy = function() {
this.disconnectRuntime();
this.unbindAll();
};
}
RuntimeTarget.prototype = EventTarget.instance;
return RuntimeTarget;
});
// Included from: src/javascript/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileReader', [
'moxie/core/utils/Basic',
'moxie/core/utils/Encode',
'moxie/core/Exceptions',
'moxie/core/EventTarget',
'moxie/file/Blob',
'moxie/file/File',
'moxie/runtime/RuntimeTarget'
], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) {
/**
Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader)
interface. Where possible uses native FileReader, where - not falls back to shims.
@class FileReader
@constructor FileReader
@extends EventTarget
@uses RuntimeClient
*/
var dispatches = [
/**
Dispatched when the read starts.
@event loadstart
@param {Object} event
*/
'loadstart',
/**
Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total).
@event progress
@param {Object} event
*/
'progress',
/**
Dispatched when the read has successfully completed.
@event load
@param {Object} event
*/
'load',
/**
Dispatched when the read has been aborted. For instance, by invoking the abort() method.
@event abort
@param {Object} event
*/
'abort',
/**
Dispatched when the read has failed.
@event error
@param {Object} event
*/
'error',
/**
Dispatched when the request has completed (either in success or failure).
@event loadend
@param {Object} event
*/
'loadend'
];
function FileReader() {
var self = this, _fr;
Basic.extend(this, {
/**
UID of the component instance.
@property uid
@type {String}
*/
uid: Basic.guid('uid_'),
/**
Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING
and FileReader.DONE.
@property readyState
@type {Number}
@default FileReader.EMPTY
*/
readyState: FileReader.EMPTY,
/**
Result of the successful read operation.
@property result
@type {String}
*/
result: null,
/**
Stores the error of failed asynchronous read operation.
@property error
@type {DOMError}
*/
error: null,
/**
Initiates reading of File/Blob object contents to binary string.
@method readAsBinaryString
@param {Blob|File} blob Object to preload
*/
readAsBinaryString: function(blob) {
_read.call(this, 'readAsBinaryString', blob);
},
/**
Initiates reading of File/Blob object contents to dataURL string.
@method readAsDataURL
@param {Blob|File} blob Object to preload
*/
readAsDataURL: function(blob) {
_read.call(this, 'readAsDataURL', blob);
},
/**
Initiates reading of File/Blob object contents to string.
@method readAsText
@param {Blob|File} blob Object to preload
*/
readAsText: function(blob) {
_read.call(this, 'readAsText', blob);
},
/**
Aborts preloading process.
@method abort
*/
abort: function() {
this.result = null;
if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) {
return;
} else if (this.readyState === FileReader.LOADING) {
this.readyState = FileReader.DONE;
}
if (_fr) {
_fr.getRuntime().exec.call(this, 'FileReader', 'abort');
}
this.trigger('abort');
this.trigger('loadend');
},
/**
Destroy component and release resources.
@method destroy
*/
destroy: function() {
this.abort();
if (_fr) {
_fr.getRuntime().exec.call(this, 'FileReader', 'destroy');
_fr.disconnectRuntime();
}
self = _fr = null;
}
});
function _read(op, blob) {
_fr = new RuntimeTarget();
function error(err) {
self.readyState = FileReader.DONE;
self.error = err;
self.trigger('error');
loadEnd();
}
function loadEnd() {
_fr.destroy();
_fr = null;
self.trigger('loadend');
}
function exec(runtime) {
_fr.bind('Error', function(e, err) {
error(err);
});
_fr.bind('Progress', function(e) {
self.result = runtime.exec.call(_fr, 'FileReader', 'getResult');
self.trigger(e);
});
_fr.bind('Load', function(e) {
self.readyState = FileReader.DONE;
self.result = runtime.exec.call(_fr, 'FileReader', 'getResult');
self.trigger(e);
loadEnd();
});
runtime.exec.call(_fr, 'FileReader', 'read', op, blob);
}
this.convertEventPropsToHandlers(dispatches);
if (this.readyState === FileReader.LOADING) {
return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR));
}
this.readyState = FileReader.LOADING;
this.trigger('loadstart');
// if source is o.Blob/o.File
if (blob instanceof Blob) {
if (blob.isDetached()) {
var src = blob.getSource();
switch (op) {
case 'readAsText':
case 'readAsBinaryString':
this.result = src;
break;
case 'readAsDataURL':
this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src);
break;
}
this.readyState = FileReader.DONE;
this.trigger('load');
loadEnd();
} else {
exec(_fr.connectRuntime(blob.ruid));
}
} else {
error(new x.DOMException(x.DOMException.NOT_FOUND_ERR));
}
}
}
/**
Initial FileReader state
@property EMPTY
@type {Number}
@final
@static
@default 0
*/
FileReader.EMPTY = 0;
/**
FileReader switches to this state when it is preloading the source
@property LOADING
@type {Number}
@final
@static
@default 1
*/
FileReader.LOADING = 1;
/**
Preloading is complete, this is a final state
@property DONE
@type {Number}
@final
@static
@default 2
*/
FileReader.DONE = 2;
FileReader.prototype = EventTarget.instance;
return FileReader;
});
// Included from: src/javascript/core/utils/Url.js
/**
* Url.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Url', [], function() {
/**
Parse url into separate components and fill in absent parts with parts from current url,
based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js
@method parseUrl
@for Utils
@static
@param {String} url Url to parse (defaults to empty string if undefined)
@return {Object} Hash containing extracted uri components
*/
var parseUrl = function(url, currentUrl) {
var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment']
, i = key.length
, ports = {
http: 80,
https: 443
}
, uri = {}
, regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/
, m = regex.exec(url || '')
;
while (i--) {
if (m[i]) {
uri[key[i]] = m[i];
}
}
// when url is relative, we set the origin and the path ourselves
if (!uri.scheme) {
// come up with defaults
if (!currentUrl || typeof(currentUrl) === 'string') {
currentUrl = parseUrl(currentUrl || document.location.href);
}
uri.scheme = currentUrl.scheme;
uri.host = currentUrl.host;
uri.port = currentUrl.port;
var path = '';
// for urls without trailing slash we need to figure out the path
if (/^[^\/]/.test(uri.path)) {
path = currentUrl.path;
// if path ends with a filename, strip it
if (!/(\/|\/[^\.]+)$/.test(path)) {
path = path.replace(/\/[^\/]+$/, '/');
} else {
path += '/';
}
}
uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir
}
if (!uri.port) {
uri.port = ports[uri.scheme] || 80;
}
uri.port = parseInt(uri.port, 10);
if (!uri.path) {
uri.path = "/";
}
delete uri.source;
return uri;
};
/**
Resolve url - among other things will turn relative url to absolute
@method resolveUrl
@static
@param {String} url Either absolute or relative
@return {String} Resolved, absolute url
*/
var resolveUrl = function(url) {
var ports = { // we ignore default ports
http: 80,
https: 443
}
, urlp = parseUrl(url)
;
return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : '');
};
/**
Check if specified url has the same origin as the current document
@method hasSameOrigin
@param {String|Object} url
@return {Boolean}
*/
var hasSameOrigin = function(url) {
function origin(url) {
return [url.scheme, url.host, url.port].join('/');
}
if (typeof url === 'string') {
url = parseUrl(url);
}
return origin(parseUrl()) === origin(url);
};
return {
parseUrl: parseUrl,
resolveUrl: resolveUrl,
hasSameOrigin: hasSameOrigin
};
});
// Included from: src/javascript/file/FileReaderSync.js
/**
* FileReaderSync.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileReaderSync', [
'moxie/core/utils/Basic',
'moxie/runtime/RuntimeClient',
'moxie/core/utils/Encode'
], function(Basic, RuntimeClient, Encode) {
/**
Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here
it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be,
but probably < 1mb). Not meant to be used directly by user.
@class FileReaderSync
@private
@constructor
*/
return function() {
RuntimeClient.call(this);
Basic.extend(this, {
uid: Basic.guid('uid_'),
readAsBinaryString: function(blob) {
return _read.call(this, 'readAsBinaryString', blob);
},
readAsDataURL: function(blob) {
return _read.call(this, 'readAsDataURL', blob);
},
/*readAsArrayBuffer: function(blob) {
return _read.call(this, 'readAsArrayBuffer', blob);
},*/
readAsText: function(blob) {
return _read.call(this, 'readAsText', blob);
}
});
function _read(op, blob) {
if (blob.isDetached()) {
var src = blob.getSource();
switch (op) {
case 'readAsBinaryString':
return src;
case 'readAsDataURL':
return 'data:' + blob.type + ';base64,' + Encode.btoa(src);
case 'readAsText':
var txt = '';
for (var i = 0, length = src.length; i < length; i++) {
txt += String.fromCharCode(src[i]);
}
return txt;
}
} else {
var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob);
this.disconnectRuntime();
return result;
}
}
};
});
// Included from: src/javascript/xhr/FormData.js
/**
* FormData.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/xhr/FormData", [
"moxie/core/Exceptions",
"moxie/core/utils/Basic",
"moxie/file/Blob"
], function(x, Basic, Blob) {
/**
FormData
@class FormData
@constructor
*/
function FormData() {
var _blob, _fields = [];
Basic.extend(this, {
/**
Append another key-value pair to the FormData object
@method append
@param {String} name Name for the new field
@param {String|Blob|Array|Object} value Value for the field
*/
append: function(name, value) {
var self = this, valueType = Basic.typeOf(value);
// according to specs value might be either Blob or String
if (value instanceof Blob) {
_blob = {
name: name,
value: value // unfortunately we can only send single Blob in one FormData
};
} else if ('array' === valueType) {
name += '[]';
Basic.each(value, function(value) {
self.append(name, value);
});
} else if ('object' === valueType) {
Basic.each(value, function(value, key) {
self.append(name + '[' + key + ']', value);
});
} else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) {
self.append(name, "false");
} else {
_fields.push({
name: name,
value: value.toString()
});
}
},
/**
Checks if FormData contains Blob.
@method hasBlob
@return {Boolean}
*/
hasBlob: function() {
return !!this.getBlob();
},
/**
Retrieves blob.
@method getBlob
@return {Object} Either Blob if found or null
*/
getBlob: function() {
return _blob && _blob.value || null;
},
/**
Retrieves blob field name.
@method getBlobName
@return {String} Either Blob field name or null
*/
getBlobName: function() {
return _blob && _blob.name || null;
},
/**
Loop over the fields in FormData and invoke the callback for each of them.
@method each
@param {Function} cb Callback to call for each field
*/
each: function(cb) {
Basic.each(_fields, function(field) {
cb(field.value, field.name);
});
if (_blob) {
cb(_blob.value, _blob.name);
}
},
destroy: function() {
_blob = null;
_fields = [];
}
});
}
return FormData;
});
// Included from: src/javascript/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/xhr/XMLHttpRequest", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/core/EventTarget",
"moxie/core/utils/Encode",
"moxie/core/utils/Url",
"moxie/runtime/Runtime",
"moxie/runtime/RuntimeTarget",
"moxie/file/Blob",
"moxie/file/FileReaderSync",
"moxie/xhr/FormData",
"moxie/core/utils/Env",
"moxie/core/utils/Mime"
], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) {
var httpCode = {
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi-Status',
226: 'IM Used',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
306: 'Reserved',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
422: 'Unprocessable Entity',
423: 'Locked',
424: 'Failed Dependency',
426: 'Upgrade Required',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates',
507: 'Insufficient Storage',
510: 'Not Extended'
};
function XMLHttpRequestUpload() {
this.uid = Basic.guid('uid_');
}
XMLHttpRequestUpload.prototype = EventTarget.instance;
/**
Implementation of XMLHttpRequest
@class XMLHttpRequest
@constructor
@uses RuntimeClient
@extends EventTarget
*/
var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons)
var NATIVE = 1, RUNTIME = 2;
function XMLHttpRequest() {
var self = this,
// this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible
props = {
/**
The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout.
@property timeout
@type Number
@default 0
*/
timeout: 0,
/**
Current state, can take following values:
UNSENT (numeric value 0)
The object has been constructed.
OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
LOADING (numeric value 3)
The response entity body is being received.
DONE (numeric value 4)
@property readyState
@type Number
@default 0 (UNSENT)
*/
readyState: XMLHttpRequest.UNSENT,
/**
True when user credentials are to be included in a cross-origin request. False when they are to be excluded
in a cross-origin request and when cookies are to be ignored in its response. Initially false.
@property withCredentials
@type Boolean
@default false
*/
withCredentials: false,
/**
Returns the HTTP status code.
@property status
@type Number
@default 0
*/
status: 0,
/**
Returns the HTTP status text.
@property statusText
@type String
*/
statusText: "",
/**
Returns the response type. Can be set to change the response type. Values are:
the empty string (default), "arraybuffer", "blob", "document", "json", and "text".
@property responseType
@type String
*/
responseType: "",
/**
Returns the document response entity body.
Throws an "InvalidStateError" exception if responseType is not the empty string or "document".
@property responseXML
@type Document
*/
responseXML: null,
/**
Returns the text response entity body.
Throws an "InvalidStateError" exception if responseType is not the empty string or "text".
@property responseText
@type String
*/
responseText: null,
/**
Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body).
Can become: ArrayBuffer, Blob, Document, JSON, Text
@property response
@type Mixed
*/
response: null
},
_async = true,
_url,
_method,
_headers = {},
_user,
_password,
_encoding = null,
_mimeType = null,
// flags
_sync_flag = false,
_send_flag = false,
_upload_events_flag = false,
_upload_complete_flag = false,
_error_flag = false,
_same_origin_flag = false,
// times
_start_time,
_timeoutset_time,
_finalMime = null,
_finalCharset = null,
_options = {},
_xhr,
_responseHeaders = '',
_responseHeadersBag
;
Basic.extend(this, props, {
/**
Unique id of the component
@property uid
@type String
*/
uid: Basic.guid('uid_'),
/**
Target for Upload events
@property upload
@type XMLHttpRequestUpload
*/
upload: new XMLHttpRequestUpload(),
/**
Sets the request method, request URL, synchronous flag, request username, and request password.
Throws a "SyntaxError" exception if one of the following is true:
method is not a valid HTTP method.
url cannot be resolved.
url contains the "user:password" format in the userinfo production.
Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.
Throws an "InvalidAccessError" exception if one of the following is true:
Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin.
There is an associated XMLHttpRequest document and either the timeout attribute is not zero,
the withCredentials attribute is true, or the responseType attribute is not the empty string.
@method open
@param {String} method HTTP method to use on request
@param {String} url URL to request
@param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default.
@param {String} [user] Username to use in HTTP authentication process on server-side
@param {String} [password] Password to use in HTTP authentication process on server-side
*/
open: function(method, url, async, user, password) {
var urlp;
// first two arguments are required
if (!method || !url) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method
if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3
if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) {
_method = method.toUpperCase();
}
// 4 - allowing these methods poses a security risk
if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) {
throw new x.DOMException(x.DOMException.SECURITY_ERR);
}
// 5
url = Encode.utf8_encode(url);
// 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError".
urlp = Url.parseUrl(url);
_same_origin_flag = Url.hasSameOrigin(urlp);
// 7 - manually build up absolute url
_url = Url.resolveUrl(url);
// 9-10, 12-13
if ((user || password) && !_same_origin_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
_user = user || urlp.user;
_password = password || urlp.pass;
// 11
_async = async || true;
if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 14 - terminate abort()
// 15 - terminate send()
// 18
_sync_flag = !_async;
_send_flag = false;
_headers = {};
_reset.call(this);
// 19
_p('readyState', XMLHttpRequest.OPENED);
// 20
this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers
this.dispatchEvent('readystatechange');
},
/**
Appends an header to the list of author request headers, or if header is already
in the list of author request headers, combines its value with value.
Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value
is not a valid HTTP header field value.
@method setRequestHeader
@param {String} header
@param {String|Number} value
*/
setRequestHeader: function(header, value) {
var uaHeaders = [ // these headers are controlled by the user agent
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"cookie",
"cookie2",
"content-transfer-encoding",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
"via"
];
// 1-2
if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 4
/* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values
if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}*/
header = Basic.trim(header).toLowerCase();
// setting of proxy-* and sec-* headers is prohibited by spec
if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) {
return false;
}
// camelize
// browsers lowercase header names (at least for custom ones)
// header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); });
if (!_headers[header]) {
_headers[header] = value;
} else {
// http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph)
_headers[header] += ', ' + value;
}
return true;
},
/**
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
@method getAllResponseHeaders
@return {String} reponse headers or empty string
*/
getAllResponseHeaders: function() {
return _responseHeaders || '';
},
/**
Returns the header field value from the response of which the field name matches header,
unless the field name is Set-Cookie or Set-Cookie2.
@method getResponseHeader
@param {String} header
@return {String} value(s) for the specified header or null
*/
getResponseHeader: function(header) {
header = header.toLowerCase();
if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) {
return null;
}
if (_responseHeaders && _responseHeaders !== '') {
// if we didn't parse response headers until now, do it and keep for later
if (!_responseHeadersBag) {
_responseHeadersBag = {};
Basic.each(_responseHeaders.split(/\r\n/), function(line) {
var pair = line.split(/:\s+/);
if (pair.length === 2) { // last line might be empty, omit
pair[0] = Basic.trim(pair[0]); // just in case
_responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form
header: pair[0],
value: Basic.trim(pair[1])
};
}
});
}
if (_responseHeadersBag.hasOwnProperty(header)) {
return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value;
}
}
return null;
},
/**
Sets the Content-Type header for the response to mime.
Throws an "InvalidStateError" exception if the state is LOADING or DONE.
Throws a "SyntaxError" exception if mime is not a valid media type.
@method overrideMimeType
@param String mime Mime type to set
*/
overrideMimeType: function(mime) {
var matches, charset;
// 1
if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2
mime = Basic.trim(mime.toLowerCase());
if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) {
mime = matches[1];
if (matches[2]) {
charset = matches[2];
}
}
if (!Mime.mimes[mime]) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3-4
_finalMime = mime;
_finalCharset = charset;
},
/**
Initiates the request. The optional argument provides the request entity body.
The argument is ignored if request method is GET or HEAD.
Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
@method send
@param {Blob|Document|String|FormData} [data] Request entity body
@param {Object} [options] Set of requirements and pre-requisities for runtime initialization
*/
send: function(data, options) {
if (Basic.typeOf(options) === 'string') {
_options = { ruid: options };
} else if (!options) {
_options = {};
} else {
_options = options;
}
this.convertEventPropsToHandlers(dispatches);
this.upload.convertEventPropsToHandlers(dispatches);
// 1-2
if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
// sending Blob
if (data instanceof Blob) {
_options.ruid = data.ruid;
_mimeType = data.type || 'application/octet-stream';
}
// FormData
else if (data instanceof FormData) {
if (data.hasBlob()) {
var blob = data.getBlob();
_options.ruid = blob.ruid;
_mimeType = blob.type || 'application/octet-stream';
}
}
// DOMString
else if (typeof data === 'string') {
_encoding = 'UTF-8';
_mimeType = 'text/plain;charset=UTF-8';
// data should be converted to Unicode and encoded as UTF-8
data = Encode.utf8_encode(data);
}
// if withCredentials not set, but requested, set it automatically
if (!this.withCredentials) {
this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag;
}
// 4 - storage mutex
// 5
_upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP
// 6
_error_flag = false;
// 7
_upload_complete_flag = !data;
// 8 - Asynchronous steps
if (!_sync_flag) {
// 8.1
_send_flag = true;
// 8.2
// this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
// 8.3
//if (!_upload_complete_flag) {
// this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
//}
}
// 8.5 - Return the send() method call, but continue running the steps in this algorithm.
_doXHR.call(this, data);
},
/**
Cancels any network activity.
@method abort
*/
abort: function() {
_error_flag = true;
_sync_flag = false;
if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) {
_p('readyState', XMLHttpRequest.DONE);
_send_flag = false;
if (_xhr) {
_xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag);
} else {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
_upload_complete_flag = true;
} else {
_p('readyState', XMLHttpRequest.UNSENT);
}
},
destroy: function() {
if (_xhr) {
if (Basic.typeOf(_xhr.destroy) === 'function') {
_xhr.destroy();
}
_xhr = null;
}
this.unbindAll();
if (this.upload) {
this.upload.unbindAll();
this.upload = null;
}
}
});
/* this is nice, but maybe too lengthy
// if supported by JS version, set getters/setters for specific properties
o.defineProperty(this, 'readyState', {
configurable: false,
get: function() {
return _p('readyState');
}
});
o.defineProperty(this, 'timeout', {
configurable: false,
get: function() {
return _p('timeout');
},
set: function(value) {
if (_sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// timeout still should be measured relative to the start time of request
_timeoutset_time = (new Date).getTime();
_p('timeout', value);
}
});
// the withCredentials attribute has no effect when fetching same-origin resources
o.defineProperty(this, 'withCredentials', {
configurable: false,
get: function() {
return _p('withCredentials');
},
set: function(value) {
// 1-2
if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3-4
if (_anonymous_flag || _sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 5
_p('withCredentials', value);
}
});
o.defineProperty(this, 'status', {
configurable: false,
get: function() {
return _p('status');
}
});
o.defineProperty(this, 'statusText', {
configurable: false,
get: function() {
return _p('statusText');
}
});
o.defineProperty(this, 'responseType', {
configurable: false,
get: function() {
return _p('responseType');
},
set: function(value) {
// 1
if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2
if (_sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 3
_p('responseType', value.toLowerCase());
}
});
o.defineProperty(this, 'responseText', {
configurable: false,
get: function() {
// 1
if (!~o.inArray(_p('responseType'), ['', 'text'])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2-3
if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
return _p('responseText');
}
});
o.defineProperty(this, 'responseXML', {
configurable: false,
get: function() {
// 1
if (!~o.inArray(_p('responseType'), ['', 'document'])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2-3
if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
return _p('responseXML');
}
});
o.defineProperty(this, 'response', {
configurable: false,
get: function() {
if (!!~o.inArray(_p('responseType'), ['', 'text'])) {
if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
return '';
}
}
if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
return null;
}
return _p('response');
}
});
*/
function _p(prop, value) {
if (!props.hasOwnProperty(prop)) {
return;
}
if (arguments.length === 1) { // get
return Env.can('define_property') ? props[prop] : self[prop];
} else { // set
if (Env.can('define_property')) {
props[prop] = value;
} else {
self[prop] = value;
}
}
}
/*
function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) {
// TODO: http://tools.ietf.org/html/rfc3490#section-4.1
return str.toLowerCase();
}
*/
function _doXHR(data) {
var self = this;
_start_time = new Date().getTime();
_xhr = new RuntimeTarget();
function loadEnd() {
if (_xhr) { // it could have been destroyed by now
_xhr.destroy();
_xhr = null;
}
self.dispatchEvent('loadend');
self = null;
}
function exec(runtime) {
_xhr.bind('LoadStart', function(e) {
_p('readyState', XMLHttpRequest.LOADING);
self.dispatchEvent('readystatechange');
self.dispatchEvent(e);
if (_upload_events_flag) {
self.upload.dispatchEvent(e);
}
});
_xhr.bind('Progress', function(e) {
if (_p('readyState') !== XMLHttpRequest.LOADING) {
_p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example)
self.dispatchEvent('readystatechange');
}
self.dispatchEvent(e);
});
_xhr.bind('UploadProgress', function(e) {
if (_upload_events_flag) {
self.upload.dispatchEvent({
type: 'progress',
lengthComputable: false,
total: e.total,
loaded: e.loaded
});
}
});
_xhr.bind('Load', function(e) {
_p('readyState', XMLHttpRequest.DONE);
_p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0));
_p('statusText', httpCode[_p('status')] || "");
_p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType')));
if (!!~Basic.inArray(_p('responseType'), ['text', ''])) {
_p('responseText', _p('response'));
} else if (_p('responseType') === 'document') {
_p('responseXML', _p('response'));
}
_responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders');
self.dispatchEvent('readystatechange');
if (_p('status') > 0) { // status 0 usually means that server is unreachable
if (_upload_events_flag) {
self.upload.dispatchEvent(e);
}
self.dispatchEvent(e);
} else {
_error_flag = true;
self.dispatchEvent('error');
}
loadEnd();
});
_xhr.bind('Abort', function(e) {
self.dispatchEvent(e);
loadEnd();
});
_xhr.bind('Error', function(e) {
_error_flag = true;
_p('readyState', XMLHttpRequest.DONE);
self.dispatchEvent('readystatechange');
_upload_complete_flag = true;
self.dispatchEvent(e);
loadEnd();
});
runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', {
url: _url,
method: _method,
async: _async,
user: _user,
password: _password,
headers: _headers,
mimeType: _mimeType,
encoding: _encoding,
responseType: self.responseType,
withCredentials: self.withCredentials,
options: _options
}, data);
}
// clarify our requirements
if (typeof(_options.required_caps) === 'string') {
_options.required_caps = Runtime.parseCaps(_options.required_caps);
}
_options.required_caps = Basic.extend({}, _options.required_caps, {
return_response_type: self.responseType
});
if (data instanceof FormData) {
_options.required_caps.send_multipart = true;
}
if (!_same_origin_flag) {
_options.required_caps.do_cors = true;
}
if (_options.ruid) { // we do not need to wait if we can connect directly
exec(_xhr.connectRuntime(_options));
} else {
_xhr.bind('RuntimeInit', function(e, runtime) {
exec(runtime);
});
_xhr.bind('RuntimeError', function(e, err) {
self.dispatchEvent('RuntimeError', err);
});
_xhr.connectRuntime(_options);
}
}
function _reset() {
_p('responseText', "");
_p('responseXML', null);
_p('response', null);
_p('status', 0);
_p('statusText', "");
_start_time = _timeoutset_time = null;
}
}
XMLHttpRequest.UNSENT = 0;
XMLHttpRequest.OPENED = 1;
XMLHttpRequest.HEADERS_RECEIVED = 2;
XMLHttpRequest.LOADING = 3;
XMLHttpRequest.DONE = 4;
XMLHttpRequest.prototype = EventTarget.instance;
return XMLHttpRequest;
});
// Included from: src/javascript/runtime/flash/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global ActiveXObject:true */
/**
Defines constructor for Flash runtime.
@class moxie/runtime/flash/Runtime
@private
*/
define("moxie/runtime/flash/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/utils/Env",
"moxie/core/utils/Dom",
"moxie/core/Exceptions",
"moxie/runtime/Runtime"
], function(Basic, Env, Dom, x, Runtime) {
var type = 'flash', extensions = {};
/**
Get the version of the Flash Player
@method getShimVersion
@private
@return {Number} Flash Player version
*/
function getShimVersion() {
var version;
try {
version = navigator.plugins['Shockwave Flash'];
version = version.description;
} catch (e1) {
try {
version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
} catch (e2) {
version = '0.0';
}
}
version = version.match(/\d+/g);
return parseFloat(version[0] + '.' + version[1]);
}
/**
Constructor for the Flash Runtime
@class FlashRuntime
@extends Runtime
*/
function FlashRuntime(options) {
var I = this, initTimer;
options = Basic.extend({ swf_url: Env.swf_url }, options);
Runtime.call(this, options, type, {
access_binary: function(value) {
return value && I.mode === 'browser';
},
access_image_binary: function(value) {
return value && I.mode === 'browser';
},
display_media: Runtime.capTrue,
do_cors: Runtime.capTrue,
drag_and_drop: false,
report_upload_progress: function() {
return I.mode === 'client';
},
resize_image: Runtime.capTrue,
return_response_headers: false,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) {
return true;
}
return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser';
},
return_status_code: function(code) {
return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]);
},
select_file: Runtime.capTrue,
select_multiple: Runtime.capTrue,
send_binary_string: function(value) {
return value && I.mode === 'browser';
},
send_browser_cookies: function(value) {
return value && I.mode === 'browser';
},
send_custom_headers: function(value) {
return value && I.mode === 'browser';
},
send_multipart: Runtime.capTrue,
slice_blob: function(value) {
return value && I.mode === 'browser';
},
stream_upload: function(value) {
return value && I.mode === 'browser';
},
summon_file_dialog: false,
upload_filesize: function(size) {
return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client';
},
use_http_method: function(methods) {
return !Basic.arrayDiff(methods, ['GET', 'POST']);
}
}, {
// capabilities that require specific mode
access_binary: function(value) {
return value ? 'browser' : 'client';
},
access_image_binary: function(value) {
return value ? 'browser' : 'client';
},
report_upload_progress: function(value) {
return value ? 'browser' : 'client';
},
return_response_type: function(responseType) {
return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser'];
},
return_status_code: function(code) {
return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser'];
},
send_binary_string: function(value) {
return value ? 'browser' : 'client';
},
send_browser_cookies: function(value) {
return value ? 'browser' : 'client';
},
send_custom_headers: function(value) {
return value ? 'browser' : 'client';
},
stream_upload: function(value) {
return value ? 'client' : 'browser';
},
upload_filesize: function(size) {
return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser';
}
}, 'client');
// minimal requirement for Flash Player version
if (getShimVersion() < 10) {
this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before
}
Basic.extend(this, {
getShim: function() {
return Dom.get(this.uid);
},
shimExec: function(component, action) {
var args = [].slice.call(arguments, 2);
return I.getShim().exec(this.uid, component, action, args);
},
init: function() {
var html, el, container;
container = this.getShimContainer();
// if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
Basic.extend(container.style, {
position: 'absolute',
top: '-8px',
left: '-8px',
width: '9px',
height: '9px',
overflow: 'hidden'
});
// insert flash object
html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" ';
if (Env.browser === 'IE') {
html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
}
html += 'width="100%" height="100%" style="outline:0">' +
'<param name="movie" value="' + options.swf_url + '" />' +
'<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowscriptaccess" value="always" />' +
'</object>';
if (Env.browser === 'IE') {
el = document.createElement('div');
container.appendChild(el);
el.outerHTML = html;
el = container = null; // just in case
} else {
container.innerHTML = html;
}
// Init is dispatched by the shim
initTimer = setTimeout(function() {
if (I && !I.initialized) { // runtime might be already destroyed by this moment
I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
}
}, 5000);
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
clearTimeout(initTimer); // initialization check might be still onwait
options = initTimer = destroy = I = null;
};
}(this.destroy))
}, extensions);
}
Runtime.addConstructor(type, FlashRuntime);
return extensions;
});
// Included from: src/javascript/runtime/flash/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/Blob
@private
*/
define("moxie/runtime/flash/file/Blob", [
"moxie/runtime/flash/Runtime",
"moxie/file/Blob"
], function(extensions, Blob) {
var FlashBlob = {
slice: function(blob, start, end, type) {
var self = this.getRuntime();
if (start < 0) {
start = Math.max(blob.size + start, 0);
} else if (start > 0) {
start = Math.min(start, blob.size);
}
if (end < 0) {
end = Math.max(blob.size + end, 0);
} else if (end > 0) {
end = Math.min(end, blob.size);
}
blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || '');
if (blob) {
blob = new Blob(self.uid, blob);
}
return blob;
}
};
return (extensions.Blob = FlashBlob);
});
// Included from: src/javascript/runtime/flash/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/FileInput
@private
*/
define("moxie/runtime/flash/file/FileInput", [
"moxie/runtime/flash/Runtime"
], function(extensions) {
var FileInput = {
init: function(options) {
this.getRuntime().shimExec.call(this, 'FileInput', 'init', {
name: options.name,
accept: options.accept,
multiple: options.multiple
});
this.trigger('ready');
}
};
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/flash/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/FileReader
@private
*/
define("moxie/runtime/flash/file/FileReader", [
"moxie/runtime/flash/Runtime",
"moxie/core/utils/Encode"
], function(extensions, Encode) {
var _result = '';
function _formatData(data, op) {
switch (op) {
case 'readAsText':
return Encode.atob(data, 'utf8');
case 'readAsBinaryString':
return Encode.atob(data);
case 'readAsDataURL':
return data;
}
return null;
}
var FileReader = {
read: function(op, blob) {
var target = this, self = target.getRuntime();
// special prefix for DataURL read mode
if (op === 'readAsDataURL') {
_result = 'data:' + (blob.type || '') + ';base64,';
}
target.bind('Progress', function(e, data) {
if (data) {
_result += _formatData(data, op);
}
});
return self.shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid);
},
getResult: function() {
return _result;
},
destroy: function() {
_result = null;
}
};
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/flash/file/FileReaderSync.js
/**
* FileReaderSync.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/FileReaderSync
@private
*/
define("moxie/runtime/flash/file/FileReaderSync", [
"moxie/runtime/flash/Runtime",
"moxie/core/utils/Encode"
], function(extensions, Encode) {
function _formatData(data, op) {
switch (op) {
case 'readAsText':
return Encode.atob(data, 'utf8');
case 'readAsBinaryString':
return Encode.atob(data);
case 'readAsDataURL':
return data;
}
return null;
}
var FileReaderSync = {
read: function(op, blob) {
var result, self = this.getRuntime();
result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid);
if (!result) {
return null; // or throw ex
}
// special prefix for DataURL read mode
if (op === 'readAsDataURL') {
result = 'data:' + (blob.type || '') + ';base64,' + result;
}
return _formatData(result, op, blob.type);
}
};
return (extensions.FileReaderSync = FileReaderSync);
});
// Included from: src/javascript/runtime/Transporter.js
/**
* Transporter.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/runtime/Transporter", [
"moxie/core/utils/Basic",
"moxie/core/utils/Encode",
"moxie/runtime/RuntimeClient",
"moxie/core/EventTarget"
], function(Basic, Encode, RuntimeClient, EventTarget) {
function Transporter() {
var mod, _runtime, _data, _size, _pos, _chunk_size;
RuntimeClient.call(this);
Basic.extend(this, {
uid: Basic.guid('uid_'),
state: Transporter.IDLE,
result: null,
transport: function(data, type, options) {
var self = this;
options = Basic.extend({
chunk_size: 204798
}, options);
// should divide by three, base64 requires this
if ((mod = options.chunk_size % 3)) {
options.chunk_size += 3 - mod;
}
_chunk_size = options.chunk_size;
_reset.call(this);
_data = data;
_size = data.length;
if (Basic.typeOf(options) === 'string' || options.ruid) {
_run.call(self, type, this.connectRuntime(options));
} else {
// we require this to run only once
var cb = function(e, runtime) {
self.unbind("RuntimeInit", cb);
_run.call(self, type, runtime);
};
this.bind("RuntimeInit", cb);
this.connectRuntime(options);
}
},
abort: function() {
var self = this;
self.state = Transporter.IDLE;
if (_runtime) {
_runtime.exec.call(self, 'Transporter', 'clear');
self.trigger("TransportingAborted");
}
_reset.call(self);
},
destroy: function() {
this.unbindAll();
_runtime = null;
this.disconnectRuntime();
_reset.call(this);
}
});
function _reset() {
_size = _pos = 0;
_data = this.result = null;
}
function _run(type, runtime) {
var self = this;
_runtime = runtime;
//self.unbind("RuntimeInit");
self.bind("TransportingProgress", function(e) {
_pos = e.loaded;
if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) {
_transport.call(self);
}
}, 999);
self.bind("TransportingComplete", function() {
_pos = _size;
self.state = Transporter.DONE;
_data = null; // clean a bit
self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || '');
}, 999);
self.state = Transporter.BUSY;
self.trigger("TransportingStarted");
_transport.call(self);
}
function _transport() {
var self = this,
chunk,
bytesLeft = _size - _pos;
if (_chunk_size > bytesLeft) {
_chunk_size = bytesLeft;
}
chunk = Encode.btoa(_data.substr(_pos, _chunk_size));
_runtime.exec.call(self, 'Transporter', 'receive', chunk, _size);
}
}
Transporter.IDLE = 0;
Transporter.BUSY = 1;
Transporter.DONE = 2;
Transporter.prototype = EventTarget.instance;
return Transporter;
});
// Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/flash/xhr/XMLHttpRequest", [
"moxie/runtime/flash/Runtime",
"moxie/core/utils/Basic",
"moxie/file/Blob",
"moxie/file/File",
"moxie/file/FileReaderSync",
"moxie/xhr/FormData",
"moxie/runtime/Transporter"
], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter) {
var XMLHttpRequest = {
send: function(meta, data) {
var target = this, self = target.getRuntime();
function send() {
meta.transport = self.mode;
self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data);
}
function appendBlob(name, blob) {
self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid);
data = null;
send();
}
function attachBlob(blob, cb) {
var tr = new Transporter();
tr.bind("TransportingComplete", function() {
cb(this.result);
});
tr.transport(blob.getSource(), blob.type, {
ruid: self.uid
});
}
// copy over the headers if any
if (!Basic.isEmptyObj(meta.headers)) {
Basic.each(meta.headers, function(value, header) {
self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object
});
}
// transfer over multipart params and blob itself
if (data instanceof FormData) {
var blobField;
data.each(function(value, name) {
if (value instanceof Blob) {
blobField = name;
} else {
self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value);
}
});
if (!data.hasBlob()) {
data = null;
send();
} else {
var blob = data.getBlob();
if (blob.isDetached()) {
attachBlob(blob, function(attachedBlob) {
blob.destroy();
appendBlob(blobField, attachedBlob);
});
} else {
appendBlob(blobField, blob);
}
}
} else if (data instanceof Blob) {
if (data.isDetached()) {
attachBlob(data, function(attachedBlob) {
data.destroy();
data = attachedBlob.uid;
send();
});
} else {
data = data.uid;
send();
}
} else {
send();
}
},
getResponse: function(responseType) {
var frs, blob, self = this.getRuntime();
blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob');
if (blob) {
blob = new File(self.uid, blob);
if ('blob' === responseType) {
return blob;
}
try {
frs = new FileReaderSync();
if (!!~Basic.inArray(responseType, ["", "text"])) {
return frs.readAsText(blob);
} else if ('json' === responseType && !!window.JSON) {
return JSON.parse(frs.readAsText(blob));
}
} finally {
blob.destroy();
}
}
return null;
},
abort: function(upload_complete_flag) {
var self = this.getRuntime();
self.shimExec.call(this, 'XMLHttpRequest', 'abort');
this.dispatchEvent('readystatechange');
// this.dispatchEvent('progress');
this.dispatchEvent('abort');
//if (!upload_complete_flag) {
// this.dispatchEvent('uploadprogress');
//}
}
};
return (extensions.XMLHttpRequest = XMLHttpRequest);
});
// Included from: src/javascript/runtime/html4/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global File:true */
/**
Defines constructor for HTML4 runtime.
@class moxie/runtime/html4/Runtime
@private
*/
define("moxie/runtime/html4/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/Runtime",
"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
var type = 'html4', extensions = {};
function Html4Runtime(options) {
var I = this
, Test = Runtime.capTest
, True = Runtime.capTrue
;
Runtime.call(this, options, type, {
access_binary: Test(window.FileReader || window.File && File.getAsDataURL),
access_image_binary: false,
display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))),
do_cors: false,
drag_and_drop: false,
filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10);
}()),
resize_image: function() {
return extensions.Image && I.can('access_binary') && Env.can('create_canvas');
},
report_upload_progress: false,
return_response_headers: false,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) {
return true;
}
return !!~Basic.inArray(responseType, ['text', 'document', '']);
},
return_status_code: function(code) {
return !Basic.arrayDiff(code, [200, 404]);
},
select_file: function() {
return Env.can('use_fileinput');
},
select_multiple: false,
send_binary_string: false,
send_custom_headers: false,
send_multipart: true,
slice_blob: false,
stream_upload: function() {
return I.can('select_file');
},
summon_file_dialog: Test(function() { // yeah... some dirty sniffing here...
return (Env.browser === 'Firefox' && Env.version >= 4) ||
(Env.browser === 'Opera' && Env.version >= 12) ||
!!~Basic.inArray(Env.browser, ['Chrome', 'Safari']);
}()),
upload_filesize: True,
use_http_method: function(methods) {
return !Basic.arrayDiff(methods, ['GET', 'POST']);
}
});
Basic.extend(this, {
init : function() {
this.trigger("Init");
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
destroy = I = null;
};
}(this.destroy))
});
Basic.extend(this.getShim(), extensions);
}
Runtime.addConstructor(type, Html4Runtime);
return extensions;
});
// Included from: src/javascript/core/utils/Events.js
/**
* Events.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Events', [
'moxie/core/utils/Basic'
], function(Basic) {
var eventhash = {}, uid = 'moxie_' + Basic.guid();
// IE W3C like event funcs
function preventDefault() {
this.returnValue = false;
}
function stopPropagation() {
this.cancelBubble = true;
}
/**
Adds an event handler to the specified object and store reference to the handler
in objects internal Plupload registry (@see removeEvent).
@method addEvent
@for Utils
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Name to add event listener to.
@param {Function} callback Function to call when event occurs.
@param {String} [key] that might be used to add specifity to the event record.
*/
var addEvent = function(obj, name, callback, key) {
var func, events;
name = name.toLowerCase();
// Add event listener
if (obj.addEventListener) {
func = callback;
obj.addEventListener(name, func, false);
} else if (obj.attachEvent) {
func = function() {
var evt = window.event;
if (!evt.target) {
evt.target = evt.srcElement;
}
evt.preventDefault = preventDefault;
evt.stopPropagation = stopPropagation;
callback(evt);
};
obj.attachEvent('on' + name, func);
}
// Log event handler to objects internal mOxie registry
if (!obj[uid]) {
obj[uid] = Basic.guid();
}
if (!eventhash.hasOwnProperty(obj[uid])) {
eventhash[obj[uid]] = {};
}
events = eventhash[obj[uid]];
if (!events.hasOwnProperty(name)) {
events[name] = [];
}
events[name].push({
func: func,
orig: callback, // store original callback for IE
key: key
});
};
/**
Remove event handler from the specified object. If third argument (callback)
is not specified remove all events with the specified name.
@method removeEvent
@static
@param {Object} obj DOM element to remove event listener(s) from.
@param {String} name Name of event listener to remove.
@param {Function|String} [callback] might be a callback or unique key to match.
*/
var removeEvent = function(obj, name, callback) {
var type, undef;
name = name.toLowerCase();
if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) {
type = eventhash[obj[uid]][name];
} else {
return;
}
for (var i = type.length - 1; i >= 0; i--) {
// undefined or not, key should match
if (type[i].orig === callback || type[i].key === callback) {
if (obj.removeEventListener) {
obj.removeEventListener(name, type[i].func, false);
} else if (obj.detachEvent) {
obj.detachEvent('on'+name, type[i].func);
}
type[i].orig = null;
type[i].func = null;
type.splice(i, 1);
// If callback was passed we are done here, otherwise proceed
if (callback !== undef) {
break;
}
}
}
// If event array got empty, remove it
if (!type.length) {
delete eventhash[obj[uid]][name];
}
// If mOxie registry has become empty, remove it
if (Basic.isEmptyObj(eventhash[obj[uid]])) {
delete eventhash[obj[uid]];
// IE doesn't let you remove DOM object property with - delete
try {
delete obj[uid];
} catch(e) {
obj[uid] = undef;
}
}
};
/**
Remove all kind of events from the specified object
@method removeAllEvents
@static
@param {Object} obj DOM element to remove event listeners from.
@param {String} [key] unique key to match, when removing events.
*/
var removeAllEvents = function(obj, key) {
if (!obj || !obj[uid]) {
return;
}
Basic.each(eventhash[obj[uid]], function(events, name) {
removeEvent(obj, name, key);
});
};
return {
addEvent: addEvent,
removeEvent: removeEvent,
removeAllEvents: removeAllEvents
};
});
// Included from: src/javascript/runtime/html4/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/file/FileInput
@private
*/
define("moxie/runtime/html4/file/FileInput", [
"moxie/runtime/html4/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/utils/Events",
"moxie/core/utils/Mime",
"moxie/core/utils/Env"
], function(extensions, Basic, Dom, Events, Mime, Env) {
function FileInput() {
var _uid, _files = [], _mimes = [], _options;
function addInput() {
var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid;
uid = Basic.guid('uid_');
shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE
if (_uid) { // move previous form out of the view
currForm = Dom.get(_uid + '_form');
if (currForm) {
Basic.extend(currForm.style, { top: '100%' });
}
}
// build form in DOM, since innerHTML version not able to submit file for some reason
form = document.createElement('form');
form.setAttribute('id', uid + '_form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('encoding', 'multipart/form-data');
Basic.extend(form.style, {
overflow: 'hidden',
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
});
input = document.createElement('input');
input.setAttribute('id', uid);
input.setAttribute('type', 'file');
input.setAttribute('name', _options.name || 'Filedata');
input.setAttribute('accept', _mimes.join(','));
Basic.extend(input.style, {
fontSize: '999px',
opacity: 0
});
form.appendChild(input);
shimContainer.appendChild(form);
// prepare file input to be placed underneath the browse_button element
Basic.extend(input.style, {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
});
if (Env.browser === 'IE' && Env.version < 10) {
Basic.extend(input.style, {
filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"
});
}
input.onchange = function() { // there should be only one handler for this
var file;
if (!this.value) {
return;
}
if (this.files) {
file = this.files[0];
} else {
file = {
name: this.value
};
}
_files = [file];
this.onchange = function() {}; // clear event handler
addInput.call(comp);
// after file is initialized as o.File, we need to update form and input ids
comp.bind('change', function onChange() {
var input = Dom.get(uid), form = Dom.get(uid + '_form'), file;
comp.unbind('change', onChange);
if (comp.files.length && input && form) {
file = comp.files[0];
input.setAttribute('id', file.uid);
form.setAttribute('id', file.uid + '_form');
// set upload target
form.setAttribute('target', file.uid + '_iframe');
}
input = form = null;
}, 998);
input = form = null;
comp.trigger('change');
};
// route click event to the input
if (I.can('summon_file_dialog')) {
browseButton = Dom.get(_options.browse_button);
Events.removeEvent(browseButton, 'click', comp.uid);
Events.addEvent(browseButton, 'click', function(e) {
if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
input.click();
}
e.preventDefault();
}, comp.uid);
}
_uid = uid;
shimContainer = currForm = browseButton = null;
}
Basic.extend(this, {
init: function(options) {
var comp = this, I = comp.getRuntime(), shimContainer;
// figure out accept string
_options = options;
_mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension'));
shimContainer = I.getShimContainer();
(function() {
var browseButton, zIndex, top;
browseButton = Dom.get(options.browse_button);
// Route click event to the input[type=file] element for browsers that support such behavior
if (I.can('summon_file_dialog')) {
if (Dom.getStyle(browseButton, 'position') === 'static') {
browseButton.style.position = 'relative';
}
zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1;
browseButton.style.zIndex = zIndex;
shimContainer.style.zIndex = zIndex - 1;
}
/* Since we have to place input[type=file] on top of the browse_button for some browsers,
browse_button loses interactivity, so we restore it here */
top = I.can('summon_file_dialog') ? browseButton : shimContainer;
Events.addEvent(top, 'mouseover', function() {
comp.trigger('mouseenter');
}, comp.uid);
Events.addEvent(top, 'mouseout', function() {
comp.trigger('mouseleave');
}, comp.uid);
Events.addEvent(top, 'mousedown', function() {
comp.trigger('mousedown');
}, comp.uid);
Events.addEvent(Dom.get(options.container), 'mouseup', function() {
comp.trigger('mouseup');
}, comp.uid);
browseButton = null;
}());
addInput.call(this);
shimContainer = null;
// trigger ready event asynchronously
comp.trigger({
type: 'ready',
async: true
});
},
getFiles: function() {
return _files;
},
disable: function(state) {
var input;
if ((input = Dom.get(_uid))) {
input.disabled = !!state;
}
},
destroy: function() {
var I = this.getRuntime()
, shim = I.getShim()
, shimContainer = I.getShimContainer()
;
Events.removeAllEvents(shimContainer, this.uid);
Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid);
if (shimContainer) {
shimContainer.innerHTML = '';
}
shim.removeInstance(this.uid);
_uid = _files = _mimes = _options = shimContainer = shim = null;
}
});
}
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/html5/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global File:true */
/**
Defines constructor for HTML5 runtime.
@class moxie/runtime/html5/Runtime
@private
*/
define("moxie/runtime/html5/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/Runtime",
"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
var type = "html5", extensions = {};
function Html5Runtime(options) {
var I = this
, Test = Runtime.capTest
, True = Runtime.capTrue
;
var caps = Basic.extend({
access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL),
access_image_binary: function() {
return I.can('access_binary') && !!extensions.Image;
},
display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')),
do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()),
drag_and_drop: Test(function() {
// this comes directly from Modernizr: http://www.modernizr.com/
var div = document.createElement('div');
// IE has support for drag and drop since version 5, but doesn't support dropping files from desktop
return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9);
}()),
filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10);
}()),
return_response_headers: True,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported
return true;
}
return Env.can('return_response_type', responseType);
},
return_status_code: True,
report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload),
resize_image: function() {
return I.can('access_binary') && Env.can('create_canvas');
},
select_file: function() {
return Env.can('use_fileinput') && window.File;
},
select_folder: function() {
return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21;
},
select_multiple: function() {
// it is buggy on Safari Windows and iOS
return I.can('select_file') &&
!(Env.browser === 'Safari' && Env.os === 'Windows') &&
!(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.4", '<'));
},
send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))),
send_custom_headers: Test(window.XMLHttpRequest),
send_multipart: function() {
return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string');
},
slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)),
stream_upload: function(){
return I.can('slice_blob') && I.can('send_multipart');
},
summon_file_dialog: Test(function() { // yeah... some dirty sniffing here...
return (Env.browser === 'Firefox' && Env.version >= 4) ||
(Env.browser === 'Opera' && Env.version >= 12) ||
(Env.browser === 'IE' && Env.version >= 10) ||
!!~Basic.inArray(Env.browser, ['Chrome', 'Safari']);
}()),
upload_filesize: True
},
arguments[2]
);
Runtime.call(this, options, (arguments[1] || type), caps);
Basic.extend(this, {
init : function() {
this.trigger("Init");
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
destroy = I = null;
};
}(this.destroy))
});
Basic.extend(this.getShim(), extensions);
}
Runtime.addConstructor(type, Html5Runtime);
return extensions;
});
// Included from: src/javascript/runtime/html5/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/file/FileReader
@private
*/
define("moxie/runtime/html5/file/FileReader", [
"moxie/runtime/html5/Runtime",
"moxie/core/utils/Encode",
"moxie/core/utils/Basic"
], function(extensions, Encode, Basic) {
function FileReader() {
var _fr, _convertToBinary = false;
Basic.extend(this, {
read: function(op, blob) {
var target = this;
_fr = new window.FileReader();
_fr.addEventListener('progress', function(e) {
target.trigger(e);
});
_fr.addEventListener('load', function(e) {
target.trigger(e);
});
_fr.addEventListener('error', function(e) {
target.trigger(e, _fr.error);
});
_fr.addEventListener('loadend', function() {
_fr = null;
});
if (Basic.typeOf(_fr[op]) === 'function') {
_convertToBinary = false;
_fr[op](blob.getSource());
} else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
_convertToBinary = true;
_fr.readAsDataURL(blob.getSource());
}
},
getResult: function() {
return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null;
},
abort: function() {
if (_fr) {
_fr.abort();
}
},
destroy: function() {
_fr = null;
}
});
function _toBinary(str) {
return Encode.atob(str.substring(str.indexOf('base64,') + 7));
}
}
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/html4/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/file/FileReader
@private
*/
define("moxie/runtime/html4/file/FileReader", [
"moxie/runtime/html4/Runtime",
"moxie/runtime/html5/file/FileReader"
], function(extensions, FileReader) {
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/html4/xhr/XMLHttpRequest", [
"moxie/runtime/html4/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/utils/Url",
"moxie/core/Exceptions",
"moxie/core/utils/Events",
"moxie/file/Blob",
"moxie/xhr/FormData"
], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) {
function XMLHttpRequest() {
var _status, _response, _iframe;
function cleanup(cb) {
var target = this, uid, form, inputs, i, hasFile = false;
if (!_iframe) {
return;
}
uid = _iframe.id.replace(/_iframe$/, '');
form = Dom.get(uid + '_form');
if (form) {
inputs = form.getElementsByTagName('input');
i = inputs.length;
while (i--) {
switch (inputs[i].getAttribute('type')) {
case 'hidden':
inputs[i].parentNode.removeChild(inputs[i]);
break;
case 'file':
hasFile = true; // flag the case for later
break;
}
}
inputs = [];
if (!hasFile) { // we need to keep the form for sake of possible retries
form.parentNode.removeChild(form);
}
form = null;
}
// without timeout, request is marked as canceled (in console)
setTimeout(function() {
Events.removeEvent(_iframe, 'load', target.uid);
if (_iframe.parentNode) { // #382
_iframe.parentNode.removeChild(_iframe);
}
// check if shim container has any other children, if - not, remove it as well
var shimContainer = target.getRuntime().getShimContainer();
if (!shimContainer.children.length) {
shimContainer.parentNode.removeChild(shimContainer);
}
shimContainer = _iframe = null;
cb();
}, 1);
}
Basic.extend(this, {
send: function(meta, data) {
var target = this, I = target.getRuntime(), uid, form, input, blob;
_status = _response = null;
function createIframe() {
var container = I.getShimContainer() || document.body
, temp = document.createElement('div')
;
// IE 6 won't be able to set the name using setAttribute or iframe.name
temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:""" style="display:none"></iframe>';
_iframe = temp.firstChild;
container.appendChild(_iframe);
/* _iframe.onreadystatechange = function() {
console.info(_iframe.readyState);
};*/
Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8
var el;
try {
el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document;
// try to detect some standard error pages
if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error
_status = el.title.replace(/^(\d+).*$/, '$1');
} else {
_status = 200;
// get result
_response = Basic.trim(el.body.innerHTML);
// we need to fire these at least once
target.trigger({
type: 'progress',
loaded: _response.length,
total: _response.length
});
if (blob) { // if we were uploading a file
target.trigger({
type: 'uploadprogress',
loaded: blob.size || 1025,
total: blob.size || 1025
});
}
}
} catch (ex) {
if (Url.hasSameOrigin(meta.url)) {
// if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm
// which obviously results to cross domain error (wtf?)
_status = 404;
} else {
cleanup.call(target, function() {
target.trigger('error');
});
return;
}
}
cleanup.call(target, function() {
target.trigger('load');
});
}, target.uid);
} // end createIframe
// prepare data to be sent and convert if required
if (data instanceof FormData && data.hasBlob()) {
blob = data.getBlob();
uid = blob.uid;
input = Dom.get(uid);
form = Dom.get(uid + '_form');
if (!form) {
throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
}
} else {
uid = Basic.guid('uid_');
form = document.createElement('form');
form.setAttribute('id', uid + '_form');
form.setAttribute('method', meta.method);
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('encoding', 'multipart/form-data');
form.setAttribute('target', uid + '_iframe');
I.getShimContainer().appendChild(form);
}
if (data instanceof FormData) {
data.each(function(value, name) {
if (value instanceof Blob) {
if (input) {
input.setAttribute('name', name);
}
} else {
var hidden = document.createElement('input');
Basic.extend(hidden, {
type : 'hidden',
name : name,
value : value
});
// make sure that input[type="file"], if it's there, comes last
if (input) {
form.insertBefore(hidden, input);
} else {
form.appendChild(hidden);
}
}
});
}
// set destination url
form.setAttribute("action", meta.url);
createIframe();
form.submit();
target.trigger('loadstart');
},
getStatus: function() {
return _status;
},
getResponse: function(responseType) {
if ('json' === responseType) {
// strip off <pre>..</pre> tags that might be enclosing the response
if (Basic.typeOf(_response) === 'string' && !!window.JSON) {
try {
return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, ''));
} catch (ex) {
return null;
}
}
} else if ('document' === responseType) {
}
return _response;
},
abort: function() {
var target = this;
if (_iframe && _iframe.contentWindow) {
if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome
_iframe.contentWindow.stop();
} else if (_iframe.contentWindow.document.execCommand) { // IE
_iframe.contentWindow.document.execCommand('Stop');
} else {
_iframe.src = "about:blank";
}
}
cleanup.call(this, function() {
// target.dispatchEvent('readystatechange');
target.dispatchEvent('abort');
});
}
});
}
return (extensions.XMLHttpRequest = XMLHttpRequest);
});
// Included from: src/javascript/runtime/silverlight/Runtime.js
/**
* RunTime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global ActiveXObject:true */
/**
Defines constructor for Silverlight runtime.
@class moxie/runtime/silverlight/Runtime
@private
*/
define("moxie/runtime/silverlight/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/utils/Env",
"moxie/core/utils/Dom",
"moxie/core/Exceptions",
"moxie/runtime/Runtime"
], function(Basic, Env, Dom, x, Runtime) {
var type = "silverlight", extensions = {};
function isInstalled(version) {
var isVersionSupported = false, control = null, actualVer,
actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0;
try {
try {
control = new ActiveXObject('AgControl.AgControl');
if (control.IsVersionSupported(version)) {
isVersionSupported = true;
}
control = null;
} catch (e) {
var plugin = navigator.plugins["Silverlight Plug-In"];
if (plugin) {
actualVer = plugin.description;
if (actualVer === "1.0.30226.2") {
actualVer = "2.0.30226.2";
}
actualVerArray = actualVer.split(".");
while (actualVerArray.length > 3) {
actualVerArray.pop();
}
while ( actualVerArray.length < 4) {
actualVerArray.push(0);
}
reqVerArray = version.split(".");
while (reqVerArray.length > 4) {
reqVerArray.pop();
}
do {
requiredVersionPart = parseInt(reqVerArray[index], 10);
actualVersionPart = parseInt(actualVerArray[index], 10);
index++;
} while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) {
isVersionSupported = true;
}
}
}
} catch (e2) {
isVersionSupported = false;
}
return isVersionSupported;
}
/**
Constructor for the Silverlight Runtime
@class SilverlightRuntime
@extends Runtime
*/
function SilverlightRuntime(options) {
var I = this, initTimer;
options = Basic.extend({ xap_url: Env.xap_url }, options);
Runtime.call(this, options, type, {
access_binary: Runtime.capTrue,
access_image_binary: Runtime.capTrue,
display_media: Runtime.capTrue,
do_cors: Runtime.capTrue,
drag_and_drop: false,
report_upload_progress: Runtime.capTrue,
resize_image: Runtime.capTrue,
return_response_headers: function(value) {
return value && I.mode === 'client';
},
return_response_type: function(responseType) {
if (responseType !== 'json') {
return true;
} else {
return !!window.JSON;
}
},
return_status_code: function(code) {
return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]);
},
select_file: Runtime.capTrue,
select_multiple: Runtime.capTrue,
send_binary_string: Runtime.capTrue,
send_browser_cookies: function(value) {
return value && I.mode === 'browser';
},
send_custom_headers: function(value) {
return value && I.mode === 'client';
},
send_multipart: Runtime.capTrue,
slice_blob: Runtime.capTrue,
stream_upload: true,
summon_file_dialog: false,
upload_filesize: Runtime.capTrue,
use_http_method: function(methods) {
return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']);
}
}, {
// capabilities that require specific mode
return_response_headers: function(value) {
return value ? 'client' : 'browser';
},
return_status_code: function(code) {
return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser'];
},
send_browser_cookies: function(value) {
return value ? 'browser' : 'client';
},
send_custom_headers: function(value) {
return value ? 'client' : 'browser';
},
use_http_method: function(methods) {
return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser'];
}
});
// minimal requirement
if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') {
this.mode = false;
}
Basic.extend(this, {
getShim: function() {
return Dom.get(this.uid).content.Moxie;
},
shimExec: function(component, action) {
var args = [].slice.call(arguments, 2);
return I.getShim().exec(this.uid, component, action, args);
},
init : function() {
var container;
container = this.getShimContainer();
container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' +
'<param name="source" value="' + options.xap_url + '"/>' +
'<param name="background" value="Transparent"/>' +
'<param name="windowless" value="true"/>' +
'<param name="enablehtmlaccess" value="true"/>' +
'<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' +
'</object>';
// Init is dispatched by the shim
initTimer = setTimeout(function() {
if (I && !I.initialized) { // runtime might be already destroyed by this moment
I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
}
}, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac)
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
clearTimeout(initTimer); // initialization check might be still onwait
options = initTimer = destroy = I = null;
};
}(this.destroy))
}, extensions);
}
Runtime.addConstructor(type, SilverlightRuntime);
return extensions;
});
// Included from: src/javascript/runtime/silverlight/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/Blob
@private
*/
define("moxie/runtime/silverlight/file/Blob", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/file/Blob"
], function(extensions, Basic, Blob) {
return (extensions.Blob = Basic.extend({}, Blob));
});
// Included from: src/javascript/runtime/silverlight/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/FileInput
@private
*/
define("moxie/runtime/silverlight/file/FileInput", [
"moxie/runtime/silverlight/Runtime"
], function(extensions) {
var FileInput = {
init: function(options) {
function toFilters(accept) {
var filter = '';
for (var i = 0; i < accept.length; i++) {
filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.');
}
return filter;
}
this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple);
this.trigger('ready');
}
};
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/silverlight/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/FileReader
@private
*/
define("moxie/runtime/silverlight/file/FileReader", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/file/FileReader"
], function(extensions, Basic, FileReader) {
return (extensions.FileReader = Basic.extend({}, FileReader));
});
// Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js
/**
* FileReaderSync.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/FileReaderSync
@private
*/
define("moxie/runtime/silverlight/file/FileReaderSync", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/file/FileReaderSync"
], function(extensions, Basic, FileReaderSync) {
return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync));
});
// Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/xhr/XMLHttpRequest"
], function(extensions, Basic, XMLHttpRequest) {
return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest));
});
expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/core/utils/Events"]);
})(this);/**
* o.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global moxie:true */
/**
Globally exposed namespace with the most frequently used public classes and handy methods.
@class o
@static
@private
*/
(function(exports) {
"use strict";
var o = {}, inArray = exports.moxie.core.utils.Basic.inArray;
// directly add some public classes
// (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included)
(function addAlias(ns) {
var name, itemType;
for (name in ns) {
itemType = typeof(ns[name]);
if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) {
addAlias(ns[name]);
} else if (itemType === 'function') {
o[name] = ns[name];
}
}
})(exports.moxie);
// add some manually
o.Env = exports.moxie.core.utils.Env;
o.Mime = exports.moxie.core.utils.Mime;
o.Exceptions = exports.moxie.core.Exceptions;
// expose globally
exports.mOxie = o;
if (!exports.o) {
exports.o = o;
}
return o;
})(this);
;webshim.register('filereader', function($, webshim, window, document, undefined, featureOptions){
"use strict";
var mOxie, moxie, hasXDomain;
var FormData = $.noop;
var sel = 'input[type="file"].ws-filereader';
var loadMoxie = function (){
webshim.loader.loadList(['moxie']);
};
var _createFilePicker = function(){
var $input, picker, $parent, onReset;
var input = this;
if(webshim.implement(input, 'filepicker')){
input = this;
$input = $(this);
$parent = $input.parent();
onReset = function(){
if(!input.value){
$input.prop('value', '');
}
};
$input.attr('tabindex', '-1').on('mousedown.filereaderwaiting click.filereaderwaiting', false);
$parent.addClass('ws-loading');
picker = new mOxie.FileInput({
browse_button: this,
accept: $.prop(this, 'accept'),
multiple: $.prop(this, 'multiple')
});
$input.jProp('form').on('reset', function(){
setTimeout(onReset);
});
picker.onready = function(){
$input.off('.fileraderwaiting');
$parent.removeClass('ws-waiting');
};
picker.onchange = function(e){
webshim.data(input, 'fileList', e.target.files);
$input.trigger('change');
};
picker.onmouseenter = function(){
$input.trigger('mouseover');
$parent.addClass('ws-mouseenter');
};
picker.onmouseleave = function(){
$input.trigger('mouseout');
$parent.removeClass('ws-mouseenter');
};
picker.onmousedown = function(){
$input.trigger('mousedown');
$parent.addClass('ws-active');
};
picker.onmouseup = function(){
$input.trigger('mouseup');
$parent.removeClass('ws-active');
};
webshim.data(input, 'filePicker', picker);
webshim.ready('WINDOWLOAD', function(){
var lastWidth;
$input.onWSOff('updateshadowdom', function(){
var curWitdth = input.offsetWidth;
if(curWitdth && lastWidth != curWitdth){
lastWidth = curWitdth;
picker.refresh();
}
});
});
webshim.addShadowDom();
picker.init();
if(input.disabled){
picker.disable(true);
}
}
};
var getFileNames = function(file){
return file.name;
};
var createFilePicker = function(){
var elem = this;
loadMoxie();
$(elem)
.on('mousedown.filereaderwaiting click.filereaderwaiting', false)
.parent()
.addClass('ws-loading')
;
webshim.ready('moxie', function(){
createFilePicker.call(elem);
});
};
var noxhr = /^(?:script|jsonp)$/i;
var notReadyYet = function(){
loadMoxie();
webshim.error('filereader/formdata not ready yet. please wait for moxie to load `webshim.ready("moxie", callbackFn);`` or wait for the first change event on input[type="file"].ws-filereader.')
};
var inputValueDesc = webshim.defineNodeNameProperty('input', 'value', {
prop: {
get: function(){
var fileList = webshim.data(this, 'fileList');
if(fileList && fileList.map){
return fileList.map(getFileNames).join(', ');
}
return inputValueDesc.prop._supget.call(this);
}
}
}
);
var shimMoxiePath = webshim.cfg.basePath+'moxie/';
var crossXMLMessage = 'You nedd a crossdomain.xml to get all "filereader" / "XHR2" / "CORS" features to work. Or host moxie.swf/moxie.xap on your server an configure filereader options: "swfpath"/"xappath"';
var testMoxie = function(options){
return (options.wsType == 'moxie' || (options.data && options.data instanceof mOxie.FormData) || (options.crossDomain && $.support.cors !== false && hasXDomain != 'no' && !noxhr.test(options.dataType || '')));
};
var createMoxieTransport = function (options){
if(testMoxie(options)){
var ajax;
webshim.info('moxie transfer used for $.ajax');
if(hasXDomain == 'no'){
webshim.error(crossXMLMessage);
}
return {
send: function( headers, completeCallback ) {
var proressEvent = function(obj, name){
if(options[name]){
var called = false;
ajax.addEventListener('load', function(e){
if(!called){
options[name]({type: 'progress', lengthComputable: true, total: 1, loaded: 1});
} else if(called.lengthComputable && called.total > called.loaded){
options[name]({type: 'progress', lengthComputable: true, total: called.total, loaded: called.total});
}
});
obj.addEventListener('progress', function(e){
called = e;
options[name](e);
});
}
};
ajax = new moxie.xhr.XMLHttpRequest();
ajax.open(options.type, options.url, options.async, options.username, options.password);
proressEvent(ajax.upload, featureOptions.uploadprogress);
proressEvent(ajax.upload, featureOptions.progress);
ajax.addEventListener('load', function(e){
var responses = {
text: ajax.responseText,
xml: ajax.responseXML
};
completeCallback(ajax.status, ajax.statusText, responses, ajax.getAllResponseHeaders());
});
if(options.xhrFields && options.xhrFields.withCredentials){
ajax.withCredentials = true;
}
if(options.timeout){
ajax.timeout = options.timeout;
}
$.each(headers, function(name, value){
ajax.setRequestHeader(name, value);
});
ajax.send(options.data);
},
abort: function() {
if(ajax){
ajax.abort();
}
}
};
}
};
var transports = {
//based on script: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
xdomain: (function(){
var httpRegEx = /^https?:\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^'+location.protocol, 'i');
return function(options, userOptions, jqXHR) {
// Only continue if the request is: asynchronous, uses GET or POST method, has HTTP or HTTPS protocol, and has the same scheme as the calling page
if (!options.crossDomain || options.username || (options.xhrFields && options.xhrFields.withCredentials) || !options.async || !getOrPostRegEx.test(options.type) || !httpRegEx.test(options.url) || !sameSchemeRegEx.test(options.url) || (options.data && options.data instanceof mOxie.FormData) || noxhr.test(options.dataType || '')) {
return;
}
var xdr = null;
webshim.info('xdomain transport used.');
return {
send: function(headers, complete) {
var postData = '';
var userType = (userOptions.dataType || '').toLowerCase();
xdr = new XDomainRequest();
if (/^\d+$/.test(userOptions.timeout)) {
xdr.timeout = userOptions.timeout;
}
xdr.ontimeout = function() {
complete(500, 'timeout');
};
xdr.onload = function() {
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: xdr.status || 200,
message: xdr.statusText || 'OK'
};
var responses = {
text: xdr.responseText,
xml: xdr.responseXML
};
try {
if (userType === 'html' || /text\/html/i.test(xdr.contentType)) {
responses.html = xdr.responseText;
} else if (userType === 'json' || (userType !== 'text' && /\/json/i.test(xdr.contentType))) {
try {
responses.json = $.parseJSON(xdr.responseText);
} catch(e) {
}
} else if (userType === 'xml' && !xdr.responseXML) {
var doc;
try {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
doc.loadXML(xdr.responseText);
} catch(e) {
}
responses.xml = doc;
}
} catch(parseMessage) {}
complete(status.code, status.message, responses, allResponseHeaders);
};
// set an empty handler for 'onprogress' so requests don't get aborted
xdr.onprogress = function(){};
xdr.onerror = function() {
complete(500, 'error', {
text: xdr.responseText
});
};
if (userOptions.data) {
postData = ($.type(userOptions.data) === 'string') ? userOptions.data : $.param(userOptions.data);
}
xdr.open(options.type, options.url);
xdr.send(postData);
},
abort: function() {
if (xdr) {
xdr.abort();
}
}
};
};
})(),
moxie: function (options, originalOptions, jqXHR){
if(testMoxie(options)){
loadMoxie(options);
var ajax;
var tmpTransport = {
send: function( headers, completeCallback ) {
ajax = true;
webshim.ready('moxie', function(){
if(ajax){
ajax = createMoxieTransport(options, originalOptions, jqXHR);
tmpTransport.send = ajax.send;
tmpTransport.abort = ajax.abort;
ajax.send(headers, completeCallback);
}
});
},
abort: function() {
ajax = false;
}
};
return tmpTransport;
}
}
};
if(!featureOptions.progress){
featureOptions.progress = 'onprogress';
}
if(!featureOptions.uploadprogress){
featureOptions.uploadprogress = 'onuploadprogress';
}
if(!featureOptions.swfpath){
featureOptions.swfpath = shimMoxiePath+'flash/Moxie.min.swf';
}
if(!featureOptions.xappath){
featureOptions.xappath = shimMoxiePath+'silverlight/Moxie.min.xap';
}
if($.support.cors !== false || !window.XDomainRequest){
delete transports.xdomain;
}
$.ajaxTransport("+*", function( options, originalOptions, jqXHR ) {
var ajax, type;
if(options.wsType || transports[transports]){
ajax = transports[transports](options, originalOptions, jqXHR);
}
if(!ajax){
for(type in transports){
ajax = transports[type](options, originalOptions, jqXHR);
if(ajax){break;}
}
}
return ajax;
});
webshim.defineNodeNameProperty('input', 'files', {
prop: {
writeable: false,
get: function(){
if(this.type != 'file'){return null;}
if(!$(this).hasClass('ws-filereader')){
webshim.info("please add the 'ws-filereader' class to your input[type='file'] to implement files-property");
}
return webshim.data(this, 'fileList') || [];
}
}
}
);
webshim.reflectProperties(['input'], ['accept']);
if($('<input />').prop('multiple') == null){
webshim.defineNodeNamesBooleanProperty(['input'], ['multiple']);
}
webshim.onNodeNamesPropertyModify('input', 'disabled', function(value, boolVal, type){
var picker = webshim.data(this, 'filePicker');
if(picker){
picker.disable(boolVal);
}
});
webshim.onNodeNamesPropertyModify('input', 'value', function(value, boolVal, type){
if(value === '' && this.type == 'file' && $(this).hasClass('ws-filereader')){
webshim.data(this, 'fileList', []);
}
});
window.FileReader = notReadyYet;
window.FormData = notReadyYet;
webshim.ready('moxie', function(){
var wsMimes = 'application/xml,xml';
moxie = window.moxie;
mOxie = window.mOxie;
mOxie.Env.swf_url = featureOptions.swfpath;
mOxie.Env.xap_url = featureOptions.xappath;
window.FileReader = mOxie.FileReader;
window.FormData = function(form){
var appendData, i, len, files, fileI, fileLen, inputName;
var moxieData = new mOxie.FormData();
if(form && $.nodeName(form, 'form')){
appendData = $(form).serializeArray();
for(i = 0; i < appendData.length; i++){
if(Array.isArray(appendData[i].value)){
appendData[i].value.forEach(function(val){
moxieData.append(appendData[i].name, val);
});
} else {
moxieData.append(appendData[i].name, appendData[i].value);
}
}
appendData = form.querySelectorAll('input[type="file"][name]');
for(i = 0, len = appendData.length; i < appendData.length; i++){
inputName = appendData[i].name;
if(inputName && !$(appendData[i]).is(':disabled')){
files = $.prop(appendData[i], 'files') || [];
if(files.length){
if(files.length > 1 || (moxieData.hasBlob && moxieData.hasBlob())){
webshim.error('FormData shim can only handle one file per ajax. Use multiple ajax request. One per file.');
}
for(fileI = 0, fileLen = files.length; fileI < fileLen; fileI++){
moxieData.append(inputName, files[fileI]);
}
}
}
}
}
return moxieData;
};
FormData = window.FormData;
createFilePicker = _createFilePicker;
transports.moxie = createMoxieTransport;
featureOptions.mimeTypes = (featureOptions.mimeTypes) ? wsMimes+','+featureOptions.mimeTypes : wsMimes;
try {
mOxie.Mime.addMimeType(featureOptions.mimeTypes);
} catch(e){
webshim.warn('mimetype to moxie error: '+e);
}
});
webshim.addReady(function(context, contextElem){
$(context.querySelectorAll(sel)).add(contextElem.filter(sel)).each(createFilePicker);
});
webshim.ready('WINDOWLOAD', loadMoxie);
if(webshim.cfg.debug !== false && featureOptions.swfpath.indexOf((location.protocol+'//'+location.hostname)) && featureOptions.swfpath.indexOf(('https://'+location.hostname))){
webshim.ready('WINDOWLOAD', function(){
var printMessage = function(){
if(hasXDomain == 'no'){
webshim.error(crossXMLMessage);
}
};
try {
hasXDomain = sessionStorage.getItem('wsXdomain.xml');
} catch(e){}
printMessage();
if(hasXDomain == null){
$.ajax({
url: 'crossdomain.xml',
type: 'HEAD',
dataType: 'xml',
success: function(){
hasXDomain = 'yes';
},
error: function(){
hasXDomain = 'no';
},
complete: function(){
try {
sessionStorage.setItem('wsXdomain.xml', hasXDomain);
} catch(e){}
printMessage();
}
});
}
});
}
});
| kartikrao31/cdnjs | ajax/libs/webshim/1.14.5/dev/shims/combos/26.js | JavaScript | mit | 200,646 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"bazar",
"bazar ert\u0259si",
"\u00e7\u0259r\u015f\u0259nb\u0259 ax\u015fam\u0131",
"\u00e7\u0259r\u015f\u0259nb\u0259",
"c\u00fcm\u0259 ax\u015fam\u0131",
"c\u00fcm\u0259",
"\u015f\u0259nb\u0259"
],
"MONTH": [
"yanvar",
"fevral",
"mart",
"aprel",
"may",
"iyun",
"iyul",
"avqust",
"sentyabr",
"oktyabr",
"noyabr",
"dekabr"
],
"SHORTDAY": [
"B.",
"B.E.",
"\u00c7.A.",
"\u00c7.",
"C.A.",
"C",
"\u015e."
],
"SHORTMONTH": [
"yan",
"fev",
"mar",
"apr",
"may",
"iyn",
"iyl",
"avq",
"sen",
"okt",
"noy",
"dek"
],
"fullDate": "d MMMM y, EEEE",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "man.",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "az",
"pluralCat": function (n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | tjbp/cdnjs | ajax/libs/angular-i18n/1.3.0-rc.0/angular-locale_az.js | JavaScript | mit | 2,062 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
function getWT(v, f) {
if (f === 0) {
return {w: 0, t: 0};
}
while ((f % 10) === 0) {
f /= 10;
v--;
}
return {w: v, t: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"domingo",
"segunda-feira",
"ter\u00e7a-feira",
"quarta-feira",
"quinta-feira",
"sexta-feira",
"s\u00e1bado"
],
"MONTH": [
"janeiro",
"fevereiro",
"mar\u00e7o",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro"
],
"SHORTDAY": [
"dom",
"seg",
"ter",
"qua",
"qui",
"sex",
"s\u00e1b"
],
"SHORTMONTH": [
"jan",
"fev",
"mar",
"abr",
"mai",
"jun",
"jul",
"ago",
"set",
"out",
"nov",
"dez"
],
"fullDate": "EEEE, d 'de' MMMM 'de' y",
"longDate": "d 'de' MMMM 'de' y",
"medium": "dd/MM/y HH:mm:ss",
"mediumDate": "dd/MM/y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "R$",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "pt-tl",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); var wt = getWT(vf.v, vf.f); if (i == 1 && vf.v == 0 || i == 0 && wt.t == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | drewfreyling/cdnjs | ajax/libs/angular.js/1.3.0-beta.13/i18n/angular-locale_pt-tl.js | JavaScript | mit | 2,589 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u092a\u0942\u0930\u094d\u0935 \u092e\u0927\u094d\u092f\u093e\u0928\u094d\u0939",
"\u0909\u0924\u094d\u0924\u0930 \u092e\u0927\u094d\u092f\u093e\u0928\u094d\u0939"
],
"DAY": [
"\u0906\u0907\u0924\u092c\u093e\u0930",
"\u0938\u094b\u092e\u092c\u093e\u0930",
"\u092e\u0919\u094d\u0917\u0932\u092c\u093e\u0930",
"\u092c\u0941\u0927\u092c\u093e\u0930",
"\u092c\u093f\u0939\u0940\u092c\u093e\u0930",
"\u0936\u0941\u0915\u094d\u0930\u092c\u093e\u0930",
"\u0936\u0928\u093f\u092c\u093e\u0930"
],
"MONTH": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0947\u092c\u094d\u0930\u0941\u0905\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u093f\u0932",
"\u092e\u0947",
"\u091c\u0941\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u091f",
"\u0938\u0947\u092a\u094d\u091f\u0947\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u091f\u094b\u092c\u0930",
"\u0928\u094b\u092d\u0947\u092e\u094d\u092c\u0930",
"\u0921\u093f\u0938\u0947\u092e\u094d\u092c\u0930"
],
"SHORTDAY": [
"\u0906\u0907\u0924",
"\u0938\u094b\u092e",
"\u092e\u0919\u094d\u0917\u0932",
"\u092c\u0941\u0927",
"\u092c\u093f\u0939\u0940",
"\u0936\u0941\u0915\u094d\u0930",
"\u0936\u0928\u093f"
],
"SHORTMONTH": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0947\u092c\u094d\u0930\u0941\u0905\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u093f\u0932",
"\u092e\u0947",
"\u091c\u0941\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u091f",
"\u0938\u0947\u092a\u094d\u091f\u0947\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u091f\u094b\u092c\u0930",
"\u0928\u094b\u092d\u0947\u092e\u094d\u092c\u0930",
"\u0921\u093f\u0938\u0947\u092e\u094d\u092c\u0930"
],
"fullDate": "y MMMM d, EEEE",
"longDate": "y MMMM d",
"medium": "y MMM d HH:mm:ss",
"mediumDate": "y MMM d",
"mediumTime": "HH:mm:ss",
"short": "y-MM-dd HH:mm",
"shortDate": "y-MM-dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Rs",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "ne",
"pluralCat": function (n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | vfonic/cdnjs | ajax/libs/angular.js/1.3.0-beta.19/i18n/angular-locale_ne.js | JavaScript | mit | 3,209 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\uc624\uc804",
"\uc624\ud6c4"
],
"DAY": [
"\uc77c\uc694\uc77c",
"\uc6d4\uc694\uc77c",
"\ud654\uc694\uc77c",
"\uc218\uc694\uc77c",
"\ubaa9\uc694\uc77c",
"\uae08\uc694\uc77c",
"\ud1a0\uc694\uc77c"
],
"MONTH": [
"1\uc6d4",
"2\uc6d4",
"3\uc6d4",
"4\uc6d4",
"5\uc6d4",
"6\uc6d4",
"7\uc6d4",
"8\uc6d4",
"9\uc6d4",
"10\uc6d4",
"11\uc6d4",
"12\uc6d4"
],
"SHORTDAY": [
"\uc77c",
"\uc6d4",
"\ud654",
"\uc218",
"\ubaa9",
"\uae08",
"\ud1a0"
],
"SHORTMONTH": [
"1\uc6d4",
"2\uc6d4",
"3\uc6d4",
"4\uc6d4",
"5\uc6d4",
"6\uc6d4",
"7\uc6d4",
"8\uc6d4",
"9\uc6d4",
"10\uc6d4",
"11\uc6d4",
"12\uc6d4"
],
"fullDate": "y\ub144 M\uc6d4 d\uc77c EEEE",
"longDate": "y\ub144 M\uc6d4 d\uc77c",
"medium": "y. M. d. a h:mm:ss",
"mediumDate": "y. M. d.",
"mediumTime": "a h:mm:ss",
"short": "yy. M. d. a h:mm",
"shortDate": "yy. M. d.",
"shortTime": "a h:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20a9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "ko-kp",
"pluralCat": function (n, opt_precision) { return PLURAL_CATEGORY.OTHER;}
});
}]); | WebReflection/cdnjs | ajax/libs/angular-i18n/1.3.0-beta.18/angular-locale_ko-kp.js | JavaScript | mit | 2,100 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-nu",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | mikelambert/cdnjs | ajax/libs/angular.js/1.3.0-beta.16/i18n/angular-locale_en-nu.js | JavaScript | mit | 2,325 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-dz",
"pluralCat": function (n, opt_precision) { var i = n | 0; if (i == 0 || i == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | gaearon/cdnjs | ajax/libs/angular-i18n/1.3.0-beta.15/angular-locale_fr-dz.js | JavaScript | mit | 2,017 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0db4\u0dd9.\u0dc0.",
"\u0db4.\u0dc0."
],
"DAY": [
"\u0d89\u0dbb\u0dd2\u0daf\u0dcf",
"\u0dc3\u0db3\u0dd4\u0daf\u0dcf",
"\u0d85\u0d9f\u0dc4\u0dbb\u0dd4\u0dc0\u0dcf\u0daf\u0dcf",
"\u0db6\u0daf\u0dcf\u0daf\u0dcf",
"\u0db6\u0dca\u200d\u0dbb\u0dc4\u0dc3\u0dca\u0db4\u0dad\u0dd2\u0db1\u0dca\u0daf\u0dcf",
"\u0dc3\u0dd2\u0d9a\u0dd4\u0dbb\u0dcf\u0daf\u0dcf",
"\u0dc3\u0dd9\u0db1\u0dc3\u0dd4\u0dbb\u0dcf\u0daf\u0dcf"
],
"MONTH": [
"\u0da2\u0db1\u0dc0\u0dcf\u0dbb\u0dd2",
"\u0db4\u0dd9\u0db6\u0dbb\u0dc0\u0dcf\u0dbb\u0dd2",
"\u0db8\u0dcf\u0dbb\u0dca\u0dad\u0dd4",
"\u0d85\u0db4\u0dca\u200d\u0dbb\u0dda\u0dbd\u0dca",
"\u0db8\u0dd0\u0dba\u0dd2",
"\u0da2\u0dd6\u0db1\u0dd2",
"\u0da2\u0dd6\u0dbd\u0dd2",
"\u0d85\u0d9c\u0ddd\u0dc3\u0dca\u0dad\u0dd4",
"\u0dc3\u0dd0\u0db4\u0dca\u0dad\u0dd0\u0db8\u0dca\u0db6\u0dbb\u0dca",
"\u0d94\u0d9a\u0dca\u0dad\u0ddd\u0db6\u0dbb\u0dca",
"\u0db1\u0ddc\u0dc0\u0dd0\u0db8\u0dca\u0db6\u0dbb\u0dca",
"\u0daf\u0dd9\u0dc3\u0dd0\u0db8\u0dca\u0db6\u0dbb\u0dca"
],
"SHORTDAY": [
"\u0d89\u0dbb\u0dd2\u0daf\u0dcf",
"\u0dc3\u0db3\u0dd4\u0daf\u0dcf",
"\u0d85\u0d9f\u0dc4",
"\u0db6\u0daf\u0dcf\u0daf\u0dcf",
"\u0db6\u0dca\u200d\u0dbb\u0dc4\u0dc3\u0dca",
"\u0dc3\u0dd2\u0d9a\u0dd4",
"\u0dc3\u0dd9\u0db1"
],
"SHORTMONTH": [
"\u0da2\u0db1",
"\u0db4\u0dd9\u0db6",
"\u0db8\u0dcf\u0dbb\u0dca\u0dad\u0dd4",
"\u0d85\u0db4\u0dca\u200d\u0dbb\u0dda\u0dbd\u0dca",
"\u0db8\u0dd0\u0dba\u0dd2",
"\u0da2\u0dd6\u0db1\u0dd2",
"\u0da2\u0dd6\u0dbd\u0dd2",
"\u0d85\u0d9c\u0ddd",
"\u0dc3\u0dd0\u0db4\u0dca",
"\u0d94\u0d9a\u0dca",
"\u0db1\u0ddc\u0dc0\u0dd0",
"\u0daf\u0dd9\u0dc3\u0dd0"
],
"fullDate": "y MMMM d, EEEE",
"longDate": "y MMMM d",
"medium": "y MMM d a h.mm.ss",
"mediumDate": "y MMM d",
"mediumTime": "a h.mm.ss",
"short": "y-MM-dd a h.mm",
"shortDate": "y-MM-dd",
"shortTime": "a h.mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Rs",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "si",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if ((n == 0 || n == 1) || i == 0 && vf.f == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | AlexisArce/cdnjs | ajax/libs/angular.js/1.3.0-beta.16/i18n/angular-locale_si.js | JavaScript | mit | 3,512 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-gg",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | anshulverma/cdnjs | ajax/libs/angular.js/1.3.0-beta.19/i18n/angular-locale_en-gg.js | JavaScript | mit | 2,325 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u056f\u0565\u057d\u0585\u0580\u056b\u0581 \u0561\u057c\u0561\u057b",
"\u056f\u0565\u057d\u0585\u0580\u056b\u0581 \u0570\u0565\u057f\u0578"
],
"DAY": [
"\u056f\u056b\u0580\u0561\u056f\u056b",
"\u0565\u0580\u056f\u0578\u0582\u0577\u0561\u0562\u0569\u056b",
"\u0565\u0580\u0565\u0584\u0577\u0561\u0562\u0569\u056b",
"\u0579\u0578\u0580\u0565\u0584\u0577\u0561\u0562\u0569\u056b",
"\u0570\u056b\u0576\u0563\u0577\u0561\u0562\u0569\u056b",
"\u0578\u0582\u0580\u0562\u0561\u0569",
"\u0577\u0561\u0562\u0561\u0569"
],
"MONTH": [
"\u0570\u0578\u0582\u0576\u057e\u0561\u0580\u056b",
"\u0583\u0565\u057f\u0580\u057e\u0561\u0580\u056b",
"\u0574\u0561\u0580\u057f\u056b",
"\u0561\u057a\u0580\u056b\u056c\u056b",
"\u0574\u0561\u0575\u056b\u057d\u056b",
"\u0570\u0578\u0582\u0576\u056b\u057d\u056b",
"\u0570\u0578\u0582\u056c\u056b\u057d\u056b",
"\u0585\u0563\u0578\u057d\u057f\u0578\u057d\u056b",
"\u057d\u0565\u057a\u057f\u0565\u0574\u0562\u0565\u0580\u056b",
"\u0570\u0578\u056f\u057f\u0565\u0574\u0562\u0565\u0580\u056b",
"\u0576\u0578\u0575\u0565\u0574\u0562\u0565\u0580\u056b",
"\u0564\u0565\u056f\u057f\u0565\u0574\u0562\u0565\u0580\u056b"
],
"SHORTDAY": [
"\u056f\u056b\u0580",
"\u0565\u0580\u056f",
"\u0565\u0580\u0584",
"\u0579\u0580\u0584",
"\u0570\u0576\u0563",
"\u0578\u0582\u0580",
"\u0577\u0562\u0569"
],
"SHORTMONTH": [
"\u0570\u0576\u057e",
"\u0583\u057f\u057e",
"\u0574\u0580\u057f",
"\u0561\u057a\u0580",
"\u0574\u0575\u057d",
"\u0570\u0576\u057d",
"\u0570\u056c\u057d",
"\u0585\u0563\u057d",
"\u057d\u057a\u057f",
"\u0570\u056f\u057f",
"\u0576\u0575\u0574",
"\u0564\u056f\u057f"
],
"fullDate": "y\u0569. MMMM d, EEEE",
"longDate": "dd MMMM, y\u0569.",
"medium": "dd MMM, y \u0569. H:mm:ss",
"mediumDate": "dd MMM, y \u0569.",
"mediumTime": "H:mm:ss",
"short": "dd.MM.yy H:mm",
"shortDate": "dd.MM.yy",
"shortTime": "H:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Dram",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "hy-am",
"pluralCat": function (n, opt_precision) { var i = n | 0; if (i == 0 || i == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | Olical/cdnjs | ajax/libs/angular.js/1.3.0-beta.11/i18n/angular-locale_hy-am.js | JavaScript | mit | 3,184 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-sl",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | nouveller/cdnjs | ajax/libs/angular.js/1.3.0-beta.19/i18n/angular-locale_en-sl.js | JavaScript | mit | 2,325 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"\u0431\u0430\u0437\u0430\u0440",
"\u0431\u0430\u0437\u0430\u0440 \u0435\u0440\u0442\u04d9\u0441\u0438",
"\u0447\u04d9\u0440\u0448\u04d9\u043d\u0431\u04d9 \u0430\u0445\u0448\u0430\u043c\u044b",
"\u0447\u04d9\u0440\u0448\u04d9\u043d\u0431\u04d9",
"\u04b9\u04af\u043c\u04d9 \u0430\u0445\u0448\u0430\u043c\u044b",
"\u04b9\u04af\u043c\u04d9",
"\u0448\u04d9\u043d\u0431\u04d9"
],
"MONTH": [
"\u0458\u0430\u043d\u0432\u0430\u0440",
"\u0444\u0435\u0432\u0440\u0430\u043b",
"\u043c\u0430\u0440\u0442",
"\u0430\u043f\u0440\u0435\u043b",
"\u043c\u0430\u0439",
"\u0438\u0458\u0443\u043d",
"\u0438\u0458\u0443\u043b",
"\u0430\u0432\u0433\u0443\u0441\u0442",
"\u0441\u0435\u043d\u0442\u0458\u0430\u0431\u0440",
"\u043e\u043a\u0442\u0458\u0430\u0431\u0440",
"\u043d\u043e\u0458\u0430\u0431\u0440",
"\u0434\u0435\u043a\u0430\u0431\u0440"
],
"SHORTDAY": [
"B.",
"B.E.",
"\u00c7.A.",
"\u00c7.",
"C.A.",
"C",
"\u015e."
],
"SHORTMONTH": [
"yan",
"fev",
"mar",
"apr",
"may",
"iyn",
"iyl",
"avq",
"sen",
"okt",
"noy",
"dek"
],
"fullDate": "EEEE, d, MMMM, y",
"longDate": "d MMMM, y",
"medium": "d MMM, y HH:mm:ss",
"mediumDate": "d MMM, y",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "man.",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "az-cyrl-az",
"pluralCat": function (n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | dominic/cdnjs | ajax/libs/angular.js/1.3.0-beta.13/i18n/angular-locale_az-cyrl-az.js | JavaScript | mit | 2,575 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"\u044f\u043a\u0448\u0430\u043d\u0431\u0430",
"\u0434\u0443\u0448\u0430\u043d\u0431\u0430",
"\u0441\u0435\u0448\u0430\u043d\u0431\u0430",
"\u0447\u043e\u0440\u0448\u0430\u043d\u0431\u0430",
"\u043f\u0430\u0439\u0448\u0430\u043d\u0431\u0430",
"\u0436\u0443\u043c\u0430",
"\u0448\u0430\u043d\u0431\u0430"
],
"MONTH": [
"\u042f\u043d\u0432\u0430\u0440",
"\u0424\u0435\u0432\u0440\u0430\u043b",
"\u041c\u0430\u0440\u0442",
"\u0410\u043f\u0440\u0435\u043b",
"\u041c\u0430\u0439",
"\u0418\u044e\u043d",
"\u0418\u044e\u043b",
"\u0410\u0432\u0433\u0443\u0441\u0442",
"\u0421\u0435\u043d\u0442\u044f\u0431\u0440",
"\u041e\u043a\u0442\u044f\u0431\u0440",
"\u041d\u043e\u044f\u0431\u0440",
"\u0414\u0435\u043a\u0430\u0431\u0440"
],
"SHORTDAY": [
"\u042f\u043a\u0448",
"\u0414\u0443\u0448",
"\u0421\u0435\u0448",
"\u0427\u043e\u0440",
"\u041f\u0430\u0439",
"\u0416\u0443\u043c",
"\u0428\u0430\u043d"
],
"SHORTMONTH": [
"\u042f\u043d\u0432",
"\u0424\u0435\u0432",
"\u041c\u0430\u0440",
"\u0410\u043f\u0440",
"\u041c\u0430\u0439",
"\u0418\u044e\u043d",
"\u0418\u044e\u043b",
"\u0410\u0432\u0433",
"\u0421\u0435\u043d",
"\u041e\u043a\u0442",
"\u041d\u043e\u044f",
"\u0414\u0435\u043a"
],
"fullDate": "EEEE, y MMMM dd",
"longDate": "y MMMM d",
"medium": "y MMM d HH:mm:ss",
"mediumDate": "y MMM d",
"mediumTime": "HH:mm:ss",
"short": "yy/MM/dd HH:mm",
"shortDate": "yy/MM/dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "so\u02bcm",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "uz-cyrl-uz",
"pluralCat": function (n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | khasinski/cdnjs | ajax/libs/angular-i18n/1.3.0-rc.1/angular-locale_uz-cyrl-uz.js | JavaScript | mit | 2,748 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0635",
"\u0645"
],
"DAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"MONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"SHORTDAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"SHORTMONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"fullDate": "EEEE\u060c d MMMM\u060c y",
"longDate": "d MMMM\u060c y",
"medium": "dd\u200f/MM\u200f/y h:mm:ss a",
"mediumDate": "dd\u200f/MM\u200f/y",
"mediumTime": "h:mm:ss a",
"short": "d\u200f/M\u200f/y h:mm a",
"shortDate": "d\u200f/M\u200f/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u00a3",
"DECIMAL_SEP": "\u066b",
"GROUP_SEP": "\u066c",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "ar-so",
"pluralCat": function (n, opt_precision) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;}
});
}]); | boneskull/cdnjs | ajax/libs/angular.js/1.3.0-beta.14/i18n/angular-locale_ar-so.js | JavaScript | mit | 3,384 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"\u0a10\u0a24\u0a35\u0a3e\u0a30",
"\u0a38\u0a4b\u0a2e\u0a35\u0a3e\u0a30",
"\u0a2e\u0a70\u0a17\u0a32\u0a35\u0a3e\u0a30",
"\u0a2c\u0a41\u0a27\u0a35\u0a3e\u0a30",
"\u0a35\u0a40\u0a30\u0a35\u0a3e\u0a30",
"\u0a38\u0a3c\u0a41\u0a71\u0a15\u0a30\u0a35\u0a3e\u0a30",
"\u0a38\u0a3c\u0a28\u0a40\u0a35\u0a3e\u0a30"
],
"MONTH": [
"\u0a1c\u0a28\u0a35\u0a30\u0a40",
"\u0a2b\u0a3c\u0a30\u0a35\u0a30\u0a40",
"\u0a2e\u0a3e\u0a30\u0a1a",
"\u0a05\u0a2a\u0a4d\u0a30\u0a48\u0a32",
"\u0a2e\u0a08",
"\u0a1c\u0a42\u0a28",
"\u0a1c\u0a41\u0a32\u0a3e\u0a08",
"\u0a05\u0a17\u0a38\u0a24",
"\u0a38\u0a24\u0a70\u0a2c\u0a30",
"\u0a05\u0a15\u0a24\u0a42\u0a2c\u0a30",
"\u0a28\u0a35\u0a70\u0a2c\u0a30",
"\u0a26\u0a38\u0a70\u0a2c\u0a30"
],
"SHORTDAY": [
"\u0a10\u0a24.",
"\u0a38\u0a4b\u0a2e.",
"\u0a2e\u0a70\u0a17\u0a32.",
"\u0a2c\u0a41\u0a27.",
"\u0a35\u0a40\u0a30.",
"\u0a38\u0a3c\u0a41\u0a71\u0a15\u0a30.",
"\u0a38\u0a3c\u0a28\u0a40."
],
"SHORTMONTH": [
"\u0a1c\u0a28\u0a35\u0a30\u0a40",
"\u0a2b\u0a3c\u0a30\u0a35\u0a30\u0a40",
"\u0a2e\u0a3e\u0a30\u0a1a",
"\u0a05\u0a2a\u0a4d\u0a30\u0a48\u0a32",
"\u0a2e\u0a08",
"\u0a1c\u0a42\u0a28",
"\u0a1c\u0a41\u0a32\u0a3e\u0a08",
"\u0a05\u0a17\u0a38\u0a24",
"\u0a38\u0a24\u0a70\u0a2c\u0a30",
"\u0a05\u0a15\u0a24\u0a42\u0a2c\u0a30",
"\u0a28\u0a35\u0a70\u0a2c\u0a30",
"\u0a26\u0a38\u0a70\u0a2c\u0a30"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "pa",
"pluralCat": function (n, opt_precision) { if (n >= 0 && n <= 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | jmusicc/cdnjs | ajax/libs/angular.js/1.3.0-beta.11/i18n/angular-locale_pa.js | JavaScript | mit | 2,862 |
/*!
* Font Awesome 4.4.0 by @davegandy - http://fontawesome.io - @fontawesome
* License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
*/
/* FONT PATH
* -------------------------- */
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot?v=4.4.0');
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.4.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.4.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.4.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.4.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.4.0#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
.fa {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* makes the font 33% larger relative to the icon container */
.fa-lg {
font-size: 1.33333333em;
line-height: 0.75em;
vertical-align: -15%;
}
.fa-2x {
font-size: 2em;
}
.fa-3x {
font-size: 3em;
}
.fa-4x {
font-size: 4em;
}
.fa-5x {
font-size: 5em;
}
.fa-fw {
width: 1.28571429em;
text-align: center;
}
.fa-ul {
padding-left: 0;
margin-left: 2.14285714em;
list-style-type: none;
}
.fa-ul > li {
position: relative;
}
.fa-li {
position: absolute;
left: -2.14285714em;
width: 2.14285714em;
top: 0.14285714em;
text-align: center;
}
.fa-li.fa-lg {
left: -1.85714286em;
}
.fa-border {
padding: .2em .25em .15em;
border: solid 0.08em #eeeeee;
border-radius: .1em;
}
.fa-pull-left {
float: left;
}
.fa-pull-right {
float: right;
}
.fa.fa-pull-left {
margin-right: .3em;
}
.fa.fa-pull-right {
margin-left: .3em;
}
/* Deprecated as of 4.4.0 */
.pull-right {
float: right;
}
.pull-left {
float: left;
}
.fa.pull-left {
margin-right: .3em;
}
.fa.pull-right {
margin-left: .3em;
}
.fa-spin {
-webkit-animation: fa-spin 2s infinite linear;
animation: fa-spin 2s infinite linear;
}
.fa-pulse {
-webkit-animation: fa-spin 1s infinite steps(8);
animation: fa-spin 1s infinite steps(8);
}
@-webkit-keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.fa-rotate-90 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.fa-rotate-180 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
}
.fa-rotate-270 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
}
.fa-flip-horizontal {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);
-webkit-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
transform: scale(-1, 1);
}
.fa-flip-vertical {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);
-webkit-transform: scale(1, -1);
-ms-transform: scale(1, -1);
transform: scale(1, -1);
}
:root .fa-rotate-90,
:root .fa-rotate-180,
:root .fa-rotate-270,
:root .fa-flip-horizontal,
:root .fa-flip-vertical {
filter: none;
}
.fa-stack {
position: relative;
display: inline-block;
width: 2em;
height: 2em;
line-height: 2em;
vertical-align: middle;
}
.fa-stack-1x,
.fa-stack-2x {
position: absolute;
left: 0;
width: 100%;
text-align: center;
}
.fa-stack-1x {
line-height: inherit;
}
.fa-stack-2x {
font-size: 2em;
}
.fa-inverse {
color: #ffffff;
}
/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
readers do not read off random characters that represent icons */
.fa-glass:before {
content: "\f000";
}
.fa-music:before {
content: "\f001";
}
.fa-search:before {
content: "\f002";
}
.fa-envelope-o:before {
content: "\f003";
}
.fa-heart:before {
content: "\f004";
}
.fa-star:before {
content: "\f005";
}
.fa-star-o:before {
content: "\f006";
}
.fa-user:before {
content: "\f007";
}
.fa-film:before {
content: "\f008";
}
.fa-th-large:before {
content: "\f009";
}
.fa-th:before {
content: "\f00a";
}
.fa-th-list:before {
content: "\f00b";
}
.fa-check:before {
content: "\f00c";
}
.fa-remove:before,
.fa-close:before,
.fa-times:before {
content: "\f00d";
}
.fa-search-plus:before {
content: "\f00e";
}
.fa-search-minus:before {
content: "\f010";
}
.fa-power-off:before {
content: "\f011";
}
.fa-signal:before {
content: "\f012";
}
.fa-gear:before,
.fa-cog:before {
content: "\f013";
}
.fa-trash-o:before {
content: "\f014";
}
.fa-home:before {
content: "\f015";
}
.fa-file-o:before {
content: "\f016";
}
.fa-clock-o:before {
content: "\f017";
}
.fa-road:before {
content: "\f018";
}
.fa-download:before {
content: "\f019";
}
.fa-arrow-circle-o-down:before {
content: "\f01a";
}
.fa-arrow-circle-o-up:before {
content: "\f01b";
}
.fa-inbox:before {
content: "\f01c";
}
.fa-play-circle-o:before {
content: "\f01d";
}
.fa-rotate-right:before,
.fa-repeat:before {
content: "\f01e";
}
.fa-refresh:before {
content: "\f021";
}
.fa-list-alt:before {
content: "\f022";
}
.fa-lock:before {
content: "\f023";
}
.fa-flag:before {
content: "\f024";
}
.fa-headphones:before {
content: "\f025";
}
.fa-volume-off:before {
content: "\f026";
}
.fa-volume-down:before {
content: "\f027";
}
.fa-volume-up:before {
content: "\f028";
}
.fa-qrcode:before {
content: "\f029";
}
.fa-barcode:before {
content: "\f02a";
}
.fa-tag:before {
content: "\f02b";
}
.fa-tags:before {
content: "\f02c";
}
.fa-book:before {
content: "\f02d";
}
.fa-bookmark:before {
content: "\f02e";
}
.fa-print:before {
content: "\f02f";
}
.fa-camera:before {
content: "\f030";
}
.fa-font:before {
content: "\f031";
}
.fa-bold:before {
content: "\f032";
}
.fa-italic:before {
content: "\f033";
}
.fa-text-height:before {
content: "\f034";
}
.fa-text-width:before {
content: "\f035";
}
.fa-align-left:before {
content: "\f036";
}
.fa-align-center:before {
content: "\f037";
}
.fa-align-right:before {
content: "\f038";
}
.fa-align-justify:before {
content: "\f039";
}
.fa-list:before {
content: "\f03a";
}
.fa-dedent:before,
.fa-outdent:before {
content: "\f03b";
}
.fa-indent:before {
content: "\f03c";
}
.fa-video-camera:before {
content: "\f03d";
}
.fa-photo:before,
.fa-image:before,
.fa-picture-o:before {
content: "\f03e";
}
.fa-pencil:before {
content: "\f040";
}
.fa-map-marker:before {
content: "\f041";
}
.fa-adjust:before {
content: "\f042";
}
.fa-tint:before {
content: "\f043";
}
.fa-edit:before,
.fa-pencil-square-o:before {
content: "\f044";
}
.fa-share-square-o:before {
content: "\f045";
}
.fa-check-square-o:before {
content: "\f046";
}
.fa-arrows:before {
content: "\f047";
}
.fa-step-backward:before {
content: "\f048";
}
.fa-fast-backward:before {
content: "\f049";
}
.fa-backward:before {
content: "\f04a";
}
.fa-play:before {
content: "\f04b";
}
.fa-pause:before {
content: "\f04c";
}
.fa-stop:before {
content: "\f04d";
}
.fa-forward:before {
content: "\f04e";
}
.fa-fast-forward:before {
content: "\f050";
}
.fa-step-forward:before {
content: "\f051";
}
.fa-eject:before {
content: "\f052";
}
.fa-chevron-left:before {
content: "\f053";
}
.fa-chevron-right:before {
content: "\f054";
}
.fa-plus-circle:before {
content: "\f055";
}
.fa-minus-circle:before {
content: "\f056";
}
.fa-times-circle:before {
content: "\f057";
}
.fa-check-circle:before {
content: "\f058";
}
.fa-question-circle:before {
content: "\f059";
}
.fa-info-circle:before {
content: "\f05a";
}
.fa-crosshairs:before {
content: "\f05b";
}
.fa-times-circle-o:before {
content: "\f05c";
}
.fa-check-circle-o:before {
content: "\f05d";
}
.fa-ban:before {
content: "\f05e";
}
.fa-arrow-left:before {
content: "\f060";
}
.fa-arrow-right:before {
content: "\f061";
}
.fa-arrow-up:before {
content: "\f062";
}
.fa-arrow-down:before {
content: "\f063";
}
.fa-mail-forward:before,
.fa-share:before {
content: "\f064";
}
.fa-expand:before {
content: "\f065";
}
.fa-compress:before {
content: "\f066";
}
.fa-plus:before {
content: "\f067";
}
.fa-minus:before {
content: "\f068";
}
.fa-asterisk:before {
content: "\f069";
}
.fa-exclamation-circle:before {
content: "\f06a";
}
.fa-gift:before {
content: "\f06b";
}
.fa-leaf:before {
content: "\f06c";
}
.fa-fire:before {
content: "\f06d";
}
.fa-eye:before {
content: "\f06e";
}
.fa-eye-slash:before {
content: "\f070";
}
.fa-warning:before,
.fa-exclamation-triangle:before {
content: "\f071";
}
.fa-plane:before {
content: "\f072";
}
.fa-calendar:before {
content: "\f073";
}
.fa-random:before {
content: "\f074";
}
.fa-comment:before {
content: "\f075";
}
.fa-magnet:before {
content: "\f076";
}
.fa-chevron-up:before {
content: "\f077";
}
.fa-chevron-down:before {
content: "\f078";
}
.fa-retweet:before {
content: "\f079";
}
.fa-shopping-cart:before {
content: "\f07a";
}
.fa-folder:before {
content: "\f07b";
}
.fa-folder-open:before {
content: "\f07c";
}
.fa-arrows-v:before {
content: "\f07d";
}
.fa-arrows-h:before {
content: "\f07e";
}
.fa-bar-chart-o:before,
.fa-bar-chart:before {
content: "\f080";
}
.fa-twitter-square:before {
content: "\f081";
}
.fa-facebook-square:before {
content: "\f082";
}
.fa-camera-retro:before {
content: "\f083";
}
.fa-key:before {
content: "\f084";
}
.fa-gears:before,
.fa-cogs:before {
content: "\f085";
}
.fa-comments:before {
content: "\f086";
}
.fa-thumbs-o-up:before {
content: "\f087";
}
.fa-thumbs-o-down:before {
content: "\f088";
}
.fa-star-half:before {
content: "\f089";
}
.fa-heart-o:before {
content: "\f08a";
}
.fa-sign-out:before {
content: "\f08b";
}
.fa-linkedin-square:before {
content: "\f08c";
}
.fa-thumb-tack:before {
content: "\f08d";
}
.fa-external-link:before {
content: "\f08e";
}
.fa-sign-in:before {
content: "\f090";
}
.fa-trophy:before {
content: "\f091";
}
.fa-github-square:before {
content: "\f092";
}
.fa-upload:before {
content: "\f093";
}
.fa-lemon-o:before {
content: "\f094";
}
.fa-phone:before {
content: "\f095";
}
.fa-square-o:before {
content: "\f096";
}
.fa-bookmark-o:before {
content: "\f097";
}
.fa-phone-square:before {
content: "\f098";
}
.fa-twitter:before {
content: "\f099";
}
.fa-facebook-f:before,
.fa-facebook:before {
content: "\f09a";
}
.fa-github:before {
content: "\f09b";
}
.fa-unlock:before {
content: "\f09c";
}
.fa-credit-card:before {
content: "\f09d";
}
.fa-feed:before,
.fa-rss:before {
content: "\f09e";
}
.fa-hdd-o:before {
content: "\f0a0";
}
.fa-bullhorn:before {
content: "\f0a1";
}
.fa-bell:before {
content: "\f0f3";
}
.fa-certificate:before {
content: "\f0a3";
}
.fa-hand-o-right:before {
content: "\f0a4";
}
.fa-hand-o-left:before {
content: "\f0a5";
}
.fa-hand-o-up:before {
content: "\f0a6";
}
.fa-hand-o-down:before {
content: "\f0a7";
}
.fa-arrow-circle-left:before {
content: "\f0a8";
}
.fa-arrow-circle-right:before {
content: "\f0a9";
}
.fa-arrow-circle-up:before {
content: "\f0aa";
}
.fa-arrow-circle-down:before {
content: "\f0ab";
}
.fa-globe:before {
content: "\f0ac";
}
.fa-wrench:before {
content: "\f0ad";
}
.fa-tasks:before {
content: "\f0ae";
}
.fa-filter:before {
content: "\f0b0";
}
.fa-briefcase:before {
content: "\f0b1";
}
.fa-arrows-alt:before {
content: "\f0b2";
}
.fa-group:before,
.fa-users:before {
content: "\f0c0";
}
.fa-chain:before,
.fa-link:before {
content: "\f0c1";
}
.fa-cloud:before {
content: "\f0c2";
}
.fa-flask:before {
content: "\f0c3";
}
.fa-cut:before,
.fa-scissors:before {
content: "\f0c4";
}
.fa-copy:before,
.fa-files-o:before {
content: "\f0c5";
}
.fa-paperclip:before {
content: "\f0c6";
}
.fa-save:before,
.fa-floppy-o:before {
content: "\f0c7";
}
.fa-square:before {
content: "\f0c8";
}
.fa-navicon:before,
.fa-reorder:before,
.fa-bars:before {
content: "\f0c9";
}
.fa-list-ul:before {
content: "\f0ca";
}
.fa-list-ol:before {
content: "\f0cb";
}
.fa-strikethrough:before {
content: "\f0cc";
}
.fa-underline:before {
content: "\f0cd";
}
.fa-table:before {
content: "\f0ce";
}
.fa-magic:before {
content: "\f0d0";
}
.fa-truck:before {
content: "\f0d1";
}
.fa-pinterest:before {
content: "\f0d2";
}
.fa-pinterest-square:before {
content: "\f0d3";
}
.fa-google-plus-square:before {
content: "\f0d4";
}
.fa-google-plus:before {
content: "\f0d5";
}
.fa-money:before {
content: "\f0d6";
}
.fa-caret-down:before {
content: "\f0d7";
}
.fa-caret-up:before {
content: "\f0d8";
}
.fa-caret-left:before {
content: "\f0d9";
}
.fa-caret-right:before {
content: "\f0da";
}
.fa-columns:before {
content: "\f0db";
}
.fa-unsorted:before,
.fa-sort:before {
content: "\f0dc";
}
.fa-sort-down:before,
.fa-sort-desc:before {
content: "\f0dd";
}
.fa-sort-up:before,
.fa-sort-asc:before {
content: "\f0de";
}
.fa-envelope:before {
content: "\f0e0";
}
.fa-linkedin:before {
content: "\f0e1";
}
.fa-rotate-left:before,
.fa-undo:before {
content: "\f0e2";
}
.fa-legal:before,
.fa-gavel:before {
content: "\f0e3";
}
.fa-dashboard:before,
.fa-tachometer:before {
content: "\f0e4";
}
.fa-comment-o:before {
content: "\f0e5";
}
.fa-comments-o:before {
content: "\f0e6";
}
.fa-flash:before,
.fa-bolt:before {
content: "\f0e7";
}
.fa-sitemap:before {
content: "\f0e8";
}
.fa-umbrella:before {
content: "\f0e9";
}
.fa-paste:before,
.fa-clipboard:before {
content: "\f0ea";
}
.fa-lightbulb-o:before {
content: "\f0eb";
}
.fa-exchange:before {
content: "\f0ec";
}
.fa-cloud-download:before {
content: "\f0ed";
}
.fa-cloud-upload:before {
content: "\f0ee";
}
.fa-user-md:before {
content: "\f0f0";
}
.fa-stethoscope:before {
content: "\f0f1";
}
.fa-suitcase:before {
content: "\f0f2";
}
.fa-bell-o:before {
content: "\f0a2";
}
.fa-coffee:before {
content: "\f0f4";
}
.fa-cutlery:before {
content: "\f0f5";
}
.fa-file-text-o:before {
content: "\f0f6";
}
.fa-building-o:before {
content: "\f0f7";
}
.fa-hospital-o:before {
content: "\f0f8";
}
.fa-ambulance:before {
content: "\f0f9";
}
.fa-medkit:before {
content: "\f0fa";
}
.fa-fighter-jet:before {
content: "\f0fb";
}
.fa-beer:before {
content: "\f0fc";
}
.fa-h-square:before {
content: "\f0fd";
}
.fa-plus-square:before {
content: "\f0fe";
}
.fa-angle-double-left:before {
content: "\f100";
}
.fa-angle-double-right:before {
content: "\f101";
}
.fa-angle-double-up:before {
content: "\f102";
}
.fa-angle-double-down:before {
content: "\f103";
}
.fa-angle-left:before {
content: "\f104";
}
.fa-angle-right:before {
content: "\f105";
}
.fa-angle-up:before {
content: "\f106";
}
.fa-angle-down:before {
content: "\f107";
}
.fa-desktop:before {
content: "\f108";
}
.fa-laptop:before {
content: "\f109";
}
.fa-tablet:before {
content: "\f10a";
}
.fa-mobile-phone:before,
.fa-mobile:before {
content: "\f10b";
}
.fa-circle-o:before {
content: "\f10c";
}
.fa-quote-left:before {
content: "\f10d";
}
.fa-quote-right:before {
content: "\f10e";
}
.fa-spinner:before {
content: "\f110";
}
.fa-circle:before {
content: "\f111";
}
.fa-mail-reply:before,
.fa-reply:before {
content: "\f112";
}
.fa-github-alt:before {
content: "\f113";
}
.fa-folder-o:before {
content: "\f114";
}
.fa-folder-open-o:before {
content: "\f115";
}
.fa-smile-o:before {
content: "\f118";
}
.fa-frown-o:before {
content: "\f119";
}
.fa-meh-o:before {
content: "\f11a";
}
.fa-gamepad:before {
content: "\f11b";
}
.fa-keyboard-o:before {
content: "\f11c";
}
.fa-flag-o:before {
content: "\f11d";
}
.fa-flag-checkered:before {
content: "\f11e";
}
.fa-terminal:before {
content: "\f120";
}
.fa-code:before {
content: "\f121";
}
.fa-mail-reply-all:before,
.fa-reply-all:before {
content: "\f122";
}
.fa-star-half-empty:before,
.fa-star-half-full:before,
.fa-star-half-o:before {
content: "\f123";
}
.fa-location-arrow:before {
content: "\f124";
}
.fa-crop:before {
content: "\f125";
}
.fa-code-fork:before {
content: "\f126";
}
.fa-unlink:before,
.fa-chain-broken:before {
content: "\f127";
}
.fa-question:before {
content: "\f128";
}
.fa-info:before {
content: "\f129";
}
.fa-exclamation:before {
content: "\f12a";
}
.fa-superscript:before {
content: "\f12b";
}
.fa-subscript:before {
content: "\f12c";
}
.fa-eraser:before {
content: "\f12d";
}
.fa-puzzle-piece:before {
content: "\f12e";
}
.fa-microphone:before {
content: "\f130";
}
.fa-microphone-slash:before {
content: "\f131";
}
.fa-shield:before {
content: "\f132";
}
.fa-calendar-o:before {
content: "\f133";
}
.fa-fire-extinguisher:before {
content: "\f134";
}
.fa-rocket:before {
content: "\f135";
}
.fa-maxcdn:before {
content: "\f136";
}
.fa-chevron-circle-left:before {
content: "\f137";
}
.fa-chevron-circle-right:before {
content: "\f138";
}
.fa-chevron-circle-up:before {
content: "\f139";
}
.fa-chevron-circle-down:before {
content: "\f13a";
}
.fa-html5:before {
content: "\f13b";
}
.fa-css3:before {
content: "\f13c";
}
.fa-anchor:before {
content: "\f13d";
}
.fa-unlock-alt:before {
content: "\f13e";
}
.fa-bullseye:before {
content: "\f140";
}
.fa-ellipsis-h:before {
content: "\f141";
}
.fa-ellipsis-v:before {
content: "\f142";
}
.fa-rss-square:before {
content: "\f143";
}
.fa-play-circle:before {
content: "\f144";
}
.fa-ticket:before {
content: "\f145";
}
.fa-minus-square:before {
content: "\f146";
}
.fa-minus-square-o:before {
content: "\f147";
}
.fa-level-up:before {
content: "\f148";
}
.fa-level-down:before {
content: "\f149";
}
.fa-check-square:before {
content: "\f14a";
}
.fa-pencil-square:before {
content: "\f14b";
}
.fa-external-link-square:before {
content: "\f14c";
}
.fa-share-square:before {
content: "\f14d";
}
.fa-compass:before {
content: "\f14e";
}
.fa-toggle-down:before,
.fa-caret-square-o-down:before {
content: "\f150";
}
.fa-toggle-up:before,
.fa-caret-square-o-up:before {
content: "\f151";
}
.fa-toggle-right:before,
.fa-caret-square-o-right:before {
content: "\f152";
}
.fa-euro:before,
.fa-eur:before {
content: "\f153";
}
.fa-gbp:before {
content: "\f154";
}
.fa-dollar:before,
.fa-usd:before {
content: "\f155";
}
.fa-rupee:before,
.fa-inr:before {
content: "\f156";
}
.fa-cny:before,
.fa-rmb:before,
.fa-yen:before,
.fa-jpy:before {
content: "\f157";
}
.fa-ruble:before,
.fa-rouble:before,
.fa-rub:before {
content: "\f158";
}
.fa-won:before,
.fa-krw:before {
content: "\f159";
}
.fa-bitcoin:before,
.fa-btc:before {
content: "\f15a";
}
.fa-file:before {
content: "\f15b";
}
.fa-file-text:before {
content: "\f15c";
}
.fa-sort-alpha-asc:before {
content: "\f15d";
}
.fa-sort-alpha-desc:before {
content: "\f15e";
}
.fa-sort-amount-asc:before {
content: "\f160";
}
.fa-sort-amount-desc:before {
content: "\f161";
}
.fa-sort-numeric-asc:before {
content: "\f162";
}
.fa-sort-numeric-desc:before {
content: "\f163";
}
.fa-thumbs-up:before {
content: "\f164";
}
.fa-thumbs-down:before {
content: "\f165";
}
.fa-youtube-square:before {
content: "\f166";
}
.fa-youtube:before {
content: "\f167";
}
.fa-xing:before {
content: "\f168";
}
.fa-xing-square:before {
content: "\f169";
}
.fa-youtube-play:before {
content: "\f16a";
}
.fa-dropbox:before {
content: "\f16b";
}
.fa-stack-overflow:before {
content: "\f16c";
}
.fa-instagram:before {
content: "\f16d";
}
.fa-flickr:before {
content: "\f16e";
}
.fa-adn:before {
content: "\f170";
}
.fa-bitbucket:before {
content: "\f171";
}
.fa-bitbucket-square:before {
content: "\f172";
}
.fa-tumblr:before {
content: "\f173";
}
.fa-tumblr-square:before {
content: "\f174";
}
.fa-long-arrow-down:before {
content: "\f175";
}
.fa-long-arrow-up:before {
content: "\f176";
}
.fa-long-arrow-left:before {
content: "\f177";
}
.fa-long-arrow-right:before {
content: "\f178";
}
.fa-apple:before {
content: "\f179";
}
.fa-windows:before {
content: "\f17a";
}
.fa-android:before {
content: "\f17b";
}
.fa-linux:before {
content: "\f17c";
}
.fa-dribbble:before {
content: "\f17d";
}
.fa-skype:before {
content: "\f17e";
}
.fa-foursquare:before {
content: "\f180";
}
.fa-trello:before {
content: "\f181";
}
.fa-female:before {
content: "\f182";
}
.fa-male:before {
content: "\f183";
}
.fa-gittip:before,
.fa-gratipay:before {
content: "\f184";
}
.fa-sun-o:before {
content: "\f185";
}
.fa-moon-o:before {
content: "\f186";
}
.fa-archive:before {
content: "\f187";
}
.fa-bug:before {
content: "\f188";
}
.fa-vk:before {
content: "\f189";
}
.fa-weibo:before {
content: "\f18a";
}
.fa-renren:before {
content: "\f18b";
}
.fa-pagelines:before {
content: "\f18c";
}
.fa-stack-exchange:before {
content: "\f18d";
}
.fa-arrow-circle-o-right:before {
content: "\f18e";
}
.fa-arrow-circle-o-left:before {
content: "\f190";
}
.fa-toggle-left:before,
.fa-caret-square-o-left:before {
content: "\f191";
}
.fa-dot-circle-o:before {
content: "\f192";
}
.fa-wheelchair:before {
content: "\f193";
}
.fa-vimeo-square:before {
content: "\f194";
}
.fa-turkish-lira:before,
.fa-try:before {
content: "\f195";
}
.fa-plus-square-o:before {
content: "\f196";
}
.fa-space-shuttle:before {
content: "\f197";
}
.fa-slack:before {
content: "\f198";
}
.fa-envelope-square:before {
content: "\f199";
}
.fa-wordpress:before {
content: "\f19a";
}
.fa-openid:before {
content: "\f19b";
}
.fa-institution:before,
.fa-bank:before,
.fa-university:before {
content: "\f19c";
}
.fa-mortar-board:before,
.fa-graduation-cap:before {
content: "\f19d";
}
.fa-yahoo:before {
content: "\f19e";
}
.fa-google:before {
content: "\f1a0";
}
.fa-reddit:before {
content: "\f1a1";
}
.fa-reddit-square:before {
content: "\f1a2";
}
.fa-stumbleupon-circle:before {
content: "\f1a3";
}
.fa-stumbleupon:before {
content: "\f1a4";
}
.fa-delicious:before {
content: "\f1a5";
}
.fa-digg:before {
content: "\f1a6";
}
.fa-pied-piper:before {
content: "\f1a7";
}
.fa-pied-piper-alt:before {
content: "\f1a8";
}
.fa-drupal:before {
content: "\f1a9";
}
.fa-joomla:before {
content: "\f1aa";
}
.fa-language:before {
content: "\f1ab";
}
.fa-fax:before {
content: "\f1ac";
}
.fa-building:before {
content: "\f1ad";
}
.fa-child:before {
content: "\f1ae";
}
.fa-paw:before {
content: "\f1b0";
}
.fa-spoon:before {
content: "\f1b1";
}
.fa-cube:before {
content: "\f1b2";
}
.fa-cubes:before {
content: "\f1b3";
}
.fa-behance:before {
content: "\f1b4";
}
.fa-behance-square:before {
content: "\f1b5";
}
.fa-steam:before {
content: "\f1b6";
}
.fa-steam-square:before {
content: "\f1b7";
}
.fa-recycle:before {
content: "\f1b8";
}
.fa-automobile:before,
.fa-car:before {
content: "\f1b9";
}
.fa-cab:before,
.fa-taxi:before {
content: "\f1ba";
}
.fa-tree:before {
content: "\f1bb";
}
.fa-spotify:before {
content: "\f1bc";
}
.fa-deviantart:before {
content: "\f1bd";
}
.fa-soundcloud:before {
content: "\f1be";
}
.fa-database:before {
content: "\f1c0";
}
.fa-file-pdf-o:before {
content: "\f1c1";
}
.fa-file-word-o:before {
content: "\f1c2";
}
.fa-file-excel-o:before {
content: "\f1c3";
}
.fa-file-powerpoint-o:before {
content: "\f1c4";
}
.fa-file-photo-o:before,
.fa-file-picture-o:before,
.fa-file-image-o:before {
content: "\f1c5";
}
.fa-file-zip-o:before,
.fa-file-archive-o:before {
content: "\f1c6";
}
.fa-file-sound-o:before,
.fa-file-audio-o:before {
content: "\f1c7";
}
.fa-file-movie-o:before,
.fa-file-video-o:before {
content: "\f1c8";
}
.fa-file-code-o:before {
content: "\f1c9";
}
.fa-vine:before {
content: "\f1ca";
}
.fa-codepen:before {
content: "\f1cb";
}
.fa-jsfiddle:before {
content: "\f1cc";
}
.fa-life-bouy:before,
.fa-life-buoy:before,
.fa-life-saver:before,
.fa-support:before,
.fa-life-ring:before {
content: "\f1cd";
}
.fa-circle-o-notch:before {
content: "\f1ce";
}
.fa-ra:before,
.fa-rebel:before {
content: "\f1d0";
}
.fa-ge:before,
.fa-empire:before {
content: "\f1d1";
}
.fa-git-square:before {
content: "\f1d2";
}
.fa-git:before {
content: "\f1d3";
}
.fa-y-combinator-square:before,
.fa-yc-square:before,
.fa-hacker-news:before {
content: "\f1d4";
}
.fa-tencent-weibo:before {
content: "\f1d5";
}
.fa-qq:before {
content: "\f1d6";
}
.fa-wechat:before,
.fa-weixin:before {
content: "\f1d7";
}
.fa-send:before,
.fa-paper-plane:before {
content: "\f1d8";
}
.fa-send-o:before,
.fa-paper-plane-o:before {
content: "\f1d9";
}
.fa-history:before {
content: "\f1da";
}
.fa-circle-thin:before {
content: "\f1db";
}
.fa-header:before {
content: "\f1dc";
}
.fa-paragraph:before {
content: "\f1dd";
}
.fa-sliders:before {
content: "\f1de";
}
.fa-share-alt:before {
content: "\f1e0";
}
.fa-share-alt-square:before {
content: "\f1e1";
}
.fa-bomb:before {
content: "\f1e2";
}
.fa-soccer-ball-o:before,
.fa-futbol-o:before {
content: "\f1e3";
}
.fa-tty:before {
content: "\f1e4";
}
.fa-binoculars:before {
content: "\f1e5";
}
.fa-plug:before {
content: "\f1e6";
}
.fa-slideshare:before {
content: "\f1e7";
}
.fa-twitch:before {
content: "\f1e8";
}
.fa-yelp:before {
content: "\f1e9";
}
.fa-newspaper-o:before {
content: "\f1ea";
}
.fa-wifi:before {
content: "\f1eb";
}
.fa-calculator:before {
content: "\f1ec";
}
.fa-paypal:before {
content: "\f1ed";
}
.fa-google-wallet:before {
content: "\f1ee";
}
.fa-cc-visa:before {
content: "\f1f0";
}
.fa-cc-mastercard:before {
content: "\f1f1";
}
.fa-cc-discover:before {
content: "\f1f2";
}
.fa-cc-amex:before {
content: "\f1f3";
}
.fa-cc-paypal:before {
content: "\f1f4";
}
.fa-cc-stripe:before {
content: "\f1f5";
}
.fa-bell-slash:before {
content: "\f1f6";
}
.fa-bell-slash-o:before {
content: "\f1f7";
}
.fa-trash:before {
content: "\f1f8";
}
.fa-copyright:before {
content: "\f1f9";
}
.fa-at:before {
content: "\f1fa";
}
.fa-eyedropper:before {
content: "\f1fb";
}
.fa-paint-brush:before {
content: "\f1fc";
}
.fa-birthday-cake:before {
content: "\f1fd";
}
.fa-area-chart:before {
content: "\f1fe";
}
.fa-pie-chart:before {
content: "\f200";
}
.fa-line-chart:before {
content: "\f201";
}
.fa-lastfm:before {
content: "\f202";
}
.fa-lastfm-square:before {
content: "\f203";
}
.fa-toggle-off:before {
content: "\f204";
}
.fa-toggle-on:before {
content: "\f205";
}
.fa-bicycle:before {
content: "\f206";
}
.fa-bus:before {
content: "\f207";
}
.fa-ioxhost:before {
content: "\f208";
}
.fa-angellist:before {
content: "\f209";
}
.fa-cc:before {
content: "\f20a";
}
.fa-shekel:before,
.fa-sheqel:before,
.fa-ils:before {
content: "\f20b";
}
.fa-meanpath:before {
content: "\f20c";
}
.fa-buysellads:before {
content: "\f20d";
}
.fa-connectdevelop:before {
content: "\f20e";
}
.fa-dashcube:before {
content: "\f210";
}
.fa-forumbee:before {
content: "\f211";
}
.fa-leanpub:before {
content: "\f212";
}
.fa-sellsy:before {
content: "\f213";
}
.fa-shirtsinbulk:before {
content: "\f214";
}
.fa-simplybuilt:before {
content: "\f215";
}
.fa-skyatlas:before {
content: "\f216";
}
.fa-cart-plus:before {
content: "\f217";
}
.fa-cart-arrow-down:before {
content: "\f218";
}
.fa-diamond:before {
content: "\f219";
}
.fa-ship:before {
content: "\f21a";
}
.fa-user-secret:before {
content: "\f21b";
}
.fa-motorcycle:before {
content: "\f21c";
}
.fa-street-view:before {
content: "\f21d";
}
.fa-heartbeat:before {
content: "\f21e";
}
.fa-venus:before {
content: "\f221";
}
.fa-mars:before {
content: "\f222";
}
.fa-mercury:before {
content: "\f223";
}
.fa-intersex:before,
.fa-transgender:before {
content: "\f224";
}
.fa-transgender-alt:before {
content: "\f225";
}
.fa-venus-double:before {
content: "\f226";
}
.fa-mars-double:before {
content: "\f227";
}
.fa-venus-mars:before {
content: "\f228";
}
.fa-mars-stroke:before {
content: "\f229";
}
.fa-mars-stroke-v:before {
content: "\f22a";
}
.fa-mars-stroke-h:before {
content: "\f22b";
}
.fa-neuter:before {
content: "\f22c";
}
.fa-genderless:before {
content: "\f22d";
}
.fa-facebook-official:before {
content: "\f230";
}
.fa-pinterest-p:before {
content: "\f231";
}
.fa-whatsapp:before {
content: "\f232";
}
.fa-server:before {
content: "\f233";
}
.fa-user-plus:before {
content: "\f234";
}
.fa-user-times:before {
content: "\f235";
}
.fa-hotel:before,
.fa-bed:before {
content: "\f236";
}
.fa-viacoin:before {
content: "\f237";
}
.fa-train:before {
content: "\f238";
}
.fa-subway:before {
content: "\f239";
}
.fa-medium:before {
content: "\f23a";
}
.fa-yc:before,
.fa-y-combinator:before {
content: "\f23b";
}
.fa-optin-monster:before {
content: "\f23c";
}
.fa-opencart:before {
content: "\f23d";
}
.fa-expeditedssl:before {
content: "\f23e";
}
.fa-battery-4:before,
.fa-battery-full:before {
content: "\f240";
}
.fa-battery-3:before,
.fa-battery-three-quarters:before {
content: "\f241";
}
.fa-battery-2:before,
.fa-battery-half:before {
content: "\f242";
}
.fa-battery-1:before,
.fa-battery-quarter:before {
content: "\f243";
}
.fa-battery-0:before,
.fa-battery-empty:before {
content: "\f244";
}
.fa-mouse-pointer:before {
content: "\f245";
}
.fa-i-cursor:before {
content: "\f246";
}
.fa-object-group:before {
content: "\f247";
}
.fa-object-ungroup:before {
content: "\f248";
}
.fa-sticky-note:before {
content: "\f249";
}
.fa-sticky-note-o:before {
content: "\f24a";
}
.fa-cc-jcb:before {
content: "\f24b";
}
.fa-cc-diners-club:before {
content: "\f24c";
}
.fa-clone:before {
content: "\f24d";
}
.fa-balance-scale:before {
content: "\f24e";
}
.fa-hourglass-o:before {
content: "\f250";
}
.fa-hourglass-1:before,
.fa-hourglass-start:before {
content: "\f251";
}
.fa-hourglass-2:before,
.fa-hourglass-half:before {
content: "\f252";
}
.fa-hourglass-3:before,
.fa-hourglass-end:before {
content: "\f253";
}
.fa-hourglass:before {
content: "\f254";
}
.fa-hand-grab-o:before,
.fa-hand-rock-o:before {
content: "\f255";
}
.fa-hand-stop-o:before,
.fa-hand-paper-o:before {
content: "\f256";
}
.fa-hand-scissors-o:before {
content: "\f257";
}
.fa-hand-lizard-o:before {
content: "\f258";
}
.fa-hand-spock-o:before {
content: "\f259";
}
.fa-hand-pointer-o:before {
content: "\f25a";
}
.fa-hand-peace-o:before {
content: "\f25b";
}
.fa-trademark:before {
content: "\f25c";
}
.fa-registered:before {
content: "\f25d";
}
.fa-creative-commons:before {
content: "\f25e";
}
.fa-gg:before {
content: "\f260";
}
.fa-gg-circle:before {
content: "\f261";
}
.fa-tripadvisor:before {
content: "\f262";
}
.fa-odnoklassniki:before {
content: "\f263";
}
.fa-odnoklassniki-square:before {
content: "\f264";
}
.fa-get-pocket:before {
content: "\f265";
}
.fa-wikipedia-w:before {
content: "\f266";
}
.fa-safari:before {
content: "\f267";
}
.fa-chrome:before {
content: "\f268";
}
.fa-firefox:before {
content: "\f269";
}
.fa-opera:before {
content: "\f26a";
}
.fa-internet-explorer:before {
content: "\f26b";
}
.fa-tv:before,
.fa-television:before {
content: "\f26c";
}
.fa-contao:before {
content: "\f26d";
}
.fa-500px:before {
content: "\f26e";
}
.fa-amazon:before {
content: "\f270";
}
.fa-calendar-plus-o:before {
content: "\f271";
}
.fa-calendar-minus-o:before {
content: "\f272";
}
.fa-calendar-times-o:before {
content: "\f273";
}
.fa-calendar-check-o:before {
content: "\f274";
}
.fa-industry:before {
content: "\f275";
}
.fa-map-pin:before {
content: "\f276";
}
.fa-map-signs:before {
content: "\f277";
}
.fa-map-o:before {
content: "\f278";
}
.fa-map:before {
content: "\f279";
}
.fa-commenting:before {
content: "\f27a";
}
.fa-commenting-o:before {
content: "\f27b";
}
.fa-houzz:before {
content: "\f27c";
}
.fa-vimeo:before {
content: "\f27d";
}
.fa-black-tie:before {
content: "\f27e";
}
.fa-fonticons:before {
content: "\f280";
}
| holtkamp/cdnjs | ajax/libs/onsen/2.0.0-beta.10/css/font_awesome/css/font-awesome.css | CSS | mit | 32,318 |
var Stream = require('stream')
var tap = require('tap')
var MS = require('../mute.js')
// some marker objects
var END = {}
var PAUSE = {}
var RESUME = {}
function PassThrough () {
Stream.call(this)
this.readable = this.writable = true
}
PassThrough.prototype = Object.create(Stream.prototype, {
constructor: {
value: PassThrough
},
write: {
value: function (c) {
this.emit('data', c)
return true
}
},
end: {
value: function (c) {
if (c) this.write(c)
this.emit('end')
}
},
pause: {
value: function () {
this.emit('pause')
}
},
resume: {
value: function () {
this.emit('resume')
}
}
})
tap.test('incoming', function (t) {
var ms = new MS
var str = new PassThrough
str.pipe(ms)
var expect = ['foo', 'boo', END]
ms.on('data', function (c) {
t.equal(c, expect.shift())
})
ms.on('end', function () {
t.equal(END, expect.shift())
t.end()
})
str.write('foo')
ms.mute()
str.write('bar')
ms.unmute()
str.write('boo')
ms.mute()
str.write('blaz')
str.end('grelb')
})
tap.test('outgoing', function (t) {
var ms = new MS
var str = new PassThrough
ms.pipe(str)
var expect = ['foo', 'boo', END]
str.on('data', function (c) {
t.equal(c, expect.shift())
})
str.on('end', function () {
t.equal(END, expect.shift())
t.end()
})
ms.write('foo')
ms.mute()
ms.write('bar')
ms.unmute()
ms.write('boo')
ms.mute()
ms.write('blaz')
ms.end('grelb')
})
tap.test('isTTY', function (t) {
var str = new PassThrough
str.isTTY = true
str.columns=80
str.rows=24
var ms = new MS
t.equal(ms.isTTY, false)
t.equal(ms.columns, undefined)
t.equal(ms.rows, undefined)
ms.pipe(str)
t.equal(ms.isTTY, true)
t.equal(ms.columns, 80)
t.equal(ms.rows, 24)
str.isTTY = false
t.equal(ms.isTTY, false)
t.equal(ms.columns, 80)
t.equal(ms.rows, 24)
str.isTTY = true
t.equal(ms.isTTY, true)
t.equal(ms.columns, 80)
t.equal(ms.rows, 24)
ms.isTTY = false
t.equal(ms.isTTY, false)
t.equal(ms.columns, 80)
t.equal(ms.rows, 24)
ms = new MS
t.equal(ms.isTTY, false)
str.pipe(ms)
t.equal(ms.isTTY, true)
str.isTTY = false
t.equal(ms.isTTY, false)
str.isTTY = true
t.equal(ms.isTTY, true)
ms.isTTY = false
t.equal(ms.isTTY, false)
t.end()
})
tap.test('pause/resume incoming', function (t) {
var str = new PassThrough
var ms = new MS
str.on('pause', function () {
t.equal(PAUSE, expect.shift())
})
str.on('resume', function () {
t.equal(RESUME, expect.shift())
})
var expect = [PAUSE, RESUME, PAUSE, RESUME]
str.pipe(ms)
ms.pause()
ms.resume()
ms.pause()
ms.resume()
t.equal(expect.length, 0, 'saw all events')
t.end()
})
tap.test('replace with *', function (t) {
var str = new PassThrough
var ms = new MS({replace: '*'})
str.pipe(ms)
var expect = ['foo', '*****', 'bar', '***', 'baz', 'boo', '**', '****']
ms.on('data', function (c) {
t.equal(c, expect.shift())
})
str.write('foo')
ms.mute()
str.write('12345')
ms.unmute()
str.write('bar')
ms.mute()
str.write('baz')
ms.unmute()
str.write('baz')
str.write('boo')
ms.mute()
str.write('xy')
str.write('xyzΩ')
t.equal(expect.length, 0)
t.end()
})
tap.test('replace with ~YARG~', function (t) {
var str = new PassThrough
var ms = new MS({replace: '~YARG~'})
str.pipe(ms)
var expect = ['foo', '~YARG~~YARG~~YARG~~YARG~~YARG~', 'bar',
'~YARG~~YARG~~YARG~', 'baz', 'boo', '~YARG~~YARG~',
'~YARG~~YARG~~YARG~~YARG~']
ms.on('data', function (c) {
t.equal(c, expect.shift())
})
// also throw some unicode in there, just for good measure.
str.write('foo')
ms.mute()
str.write('ΩΩ')
ms.unmute()
str.write('bar')
ms.mute()
str.write('Ω')
ms.unmute()
str.write('baz')
str.write('boo')
ms.mute()
str.write('Ω')
str.write('ΩΩ')
t.equal(expect.length, 0)
t.end()
})
| salehrastani/BikeMe-mobile | node_modules/bower/node_modules/promptly/node_modules/read/node_modules/mute-stream/test/basic.js | JavaScript | mit | 4,006 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-re",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | arasmussen/cdnjs | ajax/libs/angular.js/1.2.5/i18n/angular-locale_fr-re.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMM y",
"medium": "dd MMM y HH:mm:ss",
"mediumDate": "dd MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-be",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | maxklenk/cdnjs | ajax/libs/angular.js/1.2.2/i18n/angular-locale_en-be.js | JavaScript | mit | 1,911 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE dd MMMM y",
"longDate": "dd MMMM y",
"medium": "dd MMM,y h:mm:ss a",
"mediumDate": "dd MMM,y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yyyy h:mm a",
"shortDate": "d/M/yyyy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-zw",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | Decker108/angularjs-zurbfoundation-example | angular-seed/app/lib/angular/i18n/angular-locale_en-zw.js | JavaScript | mit | 1,918 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-re",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | sairamsankaran/angularjs | app/lib/angular/i18n/angular-locale_fr-re.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0635",
"\u0645"
],
"DAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"MONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"SHORTDAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"SHORTMONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"fullDate": "EEEE\u060c d MMMM\u060c y",
"longDate": "d MMMM\u060c y",
"medium": "yyyy/MM/dd h:mm:ss a",
"mediumDate": "yyyy/MM/dd",
"mediumTime": "h:mm:ss a",
"short": "yyyy/M/d h:mm a",
"shortDate": "yyyy/M/d",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u00a3",
"DECIMAL_SEP": "\u066b",
"GROUP_SEP": "\u066c",
"PATTERNS": [
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "",
"negSuf": "-",
"posPre": "",
"posSuf": ""
},
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0",
"negSuf": "-",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "ar-tn",
"pluralCat": function (n) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n == (n | 0) && n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n == (n | 0) && n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;}
});
}]); | vetruvet/cdnjs | ajax/libs/angular.js/1.3.0-beta.7/i18n/angular-locale_ar-tn.js | JavaScript | mit | 3,360 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-as",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | ematsusaka/cdnjs | ajax/libs/angular-i18n/1.3.0-beta.4/angular-locale_en-as.js | JavaScript | mit | 1,915 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "dd MMMM y",
"longDate": "dd MMMM y",
"medium": "dd-MMM-y HH:mm:ss",
"mediumDate": "dd-MMM-y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-bz",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | ematsusaka/cdnjs | ajax/libs/angular-i18n/1.3.0-beta.3/angular-locale_en-bz.js | JavaScript | mit | 1,909 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMM y",
"medium": "dd MMM y HH:mm:ss",
"mediumDate": "dd MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-be",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | yinghunglai/cdnjs | ajax/libs/angular-i18n/1.2.22/angular-locale_en-be.js | JavaScript | mit | 1,911 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0635",
"\u0645"
],
"DAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"MONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"SHORTDAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"SHORTMONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"fullDate": "EEEE\u060c d MMMM\u060c y",
"longDate": "d MMMM\u060c y",
"medium": "yyyy/MM/dd h:mm:ss a",
"mediumDate": "yyyy/MM/dd",
"mediumTime": "h:mm:ss a",
"short": "yyyy/M/d h:mm a",
"shortDate": "yyyy/M/d",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u00a3",
"DECIMAL_SEP": "\u066b",
"GROUP_SEP": "\u066c",
"PATTERNS": [
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "",
"negSuf": "-",
"posPre": "",
"posSuf": ""
},
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0",
"negSuf": "-",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "ar-tn",
"pluralCat": function (n) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n == (n | 0) && n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n == (n | 0) && n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;}
});
}]); | sajochiu/cdnjs | ajax/libs/angular.js/1.3.0-beta.2/i18n/angular-locale_ar-tn.js | JavaScript | mit | 3,360 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "dd-MMM-y h:mm:ss a",
"mediumDate": "dd-MMM-y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yy h:mm a",
"shortDate": "dd/MM/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-pk",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | wil93/cdnjs | ajax/libs/angular.js/1.2.12/i18n/angular-locale_en-pk.js | JavaScript | mit | 1,916 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-cm",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | GaryChamberlain/cdnjs | ajax/libs/angular-i18n/1.2.3/angular-locale_fr-cm.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE dd MMMM y",
"longDate": "dd MMMM y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yy h:mm a",
"shortDate": "dd/MM/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-bw",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | sevab/cdnjs | ajax/libs/angular-i18n/1.2.5/angular-locale_en-bw.js | JavaScript | mit | 1,918 |
'use strict';
var Base = require('./base'),
Draft75 = require('./draft75'),
crypto = require('crypto'),
util = require('util');
var numberFromKey = function(key) {
return parseInt(key.match(/[0-9]/g).join(''), 10);
};
var spacesInKey = function(key) {
return key.match(/ /g).length;
};
var Draft76 = function(request, url, options) {
Draft75.apply(this, arguments);
this._stage = -1;
this._body = [];
this.version = 'hixie-76';
this._headers.clear();
this._headers.set('Upgrade', 'WebSocket');
this._headers.set('Connection', 'Upgrade');
this._headers.set('Sec-WebSocket-Origin', this._request.headers.origin);
this._headers.set('Sec-WebSocket-Location', this.url);
};
util.inherits(Draft76, Draft75);
var instance = {
BODY_SIZE: 8,
start: function() {
if (!Draft75.prototype.start.call(this)) return false;
this._started = true;
this._sendHandshakeBody();
return true;
},
close: function() {
if (this.readyState === 3) return false;
this._write(new Buffer([0xFF, 0x00]));
this.readyState = 3;
this.emit('close', new Base.CloseEvent(null, null));
return true;
},
_handshakeResponse: function() {
var start = 'HTTP/1.1 101 WebSocket Protocol Handshake',
headers = [start, this._headers.toString(), ''];
return new Buffer(headers.join('\r\n'), 'binary');
},
_handshakeSignature: function() {
if (this._body.length < this.BODY_SIZE) return null;
var headers = this._request.headers,
key1 = headers['sec-websocket-key1'],
value1 = numberFromKey(key1) / spacesInKey(key1),
key2 = headers['sec-websocket-key2'],
value2 = numberFromKey(key2) / spacesInKey(key2),
md5 = crypto.createHash('md5'),
buffer = new Buffer(8 + this.BODY_SIZE);
buffer.writeUInt32BE(value1, 0);
buffer.writeUInt32BE(value2, 4);
new Buffer(this._body).copy(buffer, 8, 0, this.BODY_SIZE);
md5.update(buffer);
return new Buffer(md5.digest('binary'), 'binary');
},
_sendHandshakeBody: function() {
if (!this._started) return;
var signature = this._handshakeSignature();
if (!signature) return;
this._write(signature);
this._stage = 0;
this._open();
if (this._body.length > this.BODY_SIZE)
this.parse(this._body.slice(this.BODY_SIZE));
},
_parseLeadingByte: function(octet) {
if (octet !== 0xFF)
return Draft75.prototype._parseLeadingByte.call(this, octet);
this._closing = true;
this._length = 0;
this._stage = 1;
}
};
for (var key in instance)
Draft76.prototype[key] = instance[key];
module.exports = Draft76;
| EducationforKids/e4k | node_modules/gulp-livereload/node_modules/tiny-lr/node_modules/faye-websocket/node_modules/websocket-driver/lib/websocket/driver/draft76.js | JavaScript | mit | 2,672 |
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Declaration = require('../declaration');
var InlineLogical = function (_Declaration) {
_inherits(InlineLogical, _Declaration);
function InlineLogical() {
_classCallCheck(this, InlineLogical);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Use old syntax for -moz- and -webkit-
*/
InlineLogical.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + prop.replace('-inline', '');
};
/**
* Return property name by spec
*/
InlineLogical.prototype.normalize = function normalize(prop) {
return prop.replace(/(margin|padding|border)-(start|end)/, '$1-inline-$2');
};
return InlineLogical;
}(Declaration);
Object.defineProperty(InlineLogical, 'names', {
enumerable: true,
writable: true,
value: ['border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end', 'border-start', 'border-end', 'margin-start', 'margin-end', 'padding-start', 'padding-end']
});
module.exports = InlineLogical; | Montana-Studio/PI_Landing | node_modules/autoprefixer/lib/hacks/inline-logical.js | JavaScript | mit | 2,032 |
.opentip-container,
.opentip-container * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.opentip-container {
position: absolute;
max-width: 300px;
z-index: 100;
-webkit-transition: -webkit-transform 1s ease-in-out;
-moz-transition: -moz-transform 1s ease-in-out;
-o-transition: -o-transform 1s ease-in-out;
-ms-transition: -ms-transform 1s ease-in-out;
transition: transform 1s ease-in-out;
pointer-events: none;
-webkit-transform: translateX(0) translateY(0);
-moz-transform: translateX(0) translateY(0);
-o-transform: translateX(0) translateY(0);
-ms-transform: translateX(0) translateY(0);
transform: translateX(0) translateY(0);
}
.opentip-container.fixed.hidden.stem-top.stem-center,
.opentip-container.fixed.going-to-show.stem-top.stem-center,
.opentip-container.fixed.hiding.stem-top.stem-center {
-webkit-transform: translateY(-5px);
-moz-transform: translateY(-5px);
-o-transform: translateY(-5px);
-ms-transform: translateY(-5px);
transform: translateY(-5px);
}
.opentip-container.fixed.hidden.stem-top.stem-right,
.opentip-container.fixed.going-to-show.stem-top.stem-right,
.opentip-container.fixed.hiding.stem-top.stem-right {
-webkit-transform: translateY(-5px) translateX(5px);
-moz-transform: translateY(-5px) translateX(5px);
-o-transform: translateY(-5px) translateX(5px);
-ms-transform: translateY(-5px) translateX(5px);
transform: translateY(-5px) translateX(5px);
}
.opentip-container.fixed.hidden.stem-middle.stem-right,
.opentip-container.fixed.going-to-show.stem-middle.stem-right,
.opentip-container.fixed.hiding.stem-middle.stem-right {
-webkit-transform: translateX(5px);
-moz-transform: translateX(5px);
-o-transform: translateX(5px);
-ms-transform: translateX(5px);
transform: translateX(5px);
}
.opentip-container.fixed.hidden.stem-bottom.stem-right,
.opentip-container.fixed.going-to-show.stem-bottom.stem-right,
.opentip-container.fixed.hiding.stem-bottom.stem-right {
-webkit-transform: translateY(5px) translateX(5px);
-moz-transform: translateY(5px) translateX(5px);
-o-transform: translateY(5px) translateX(5px);
-ms-transform: translateY(5px) translateX(5px);
transform: translateY(5px) translateX(5px);
}
.opentip-container.fixed.hidden.stem-bottom.stem-center,
.opentip-container.fixed.going-to-show.stem-bottom.stem-center,
.opentip-container.fixed.hiding.stem-bottom.stem-center {
-webkit-transform: translateY(5px);
-moz-transform: translateY(5px);
-o-transform: translateY(5px);
-ms-transform: translateY(5px);
transform: translateY(5px);
}
.opentip-container.fixed.hidden.stem-bottom.stem-left,
.opentip-container.fixed.going-to-show.stem-bottom.stem-left,
.opentip-container.fixed.hiding.stem-bottom.stem-left {
-webkit-transform: translateY(5px) translateX(-5px);
-moz-transform: translateY(5px) translateX(-5px);
-o-transform: translateY(5px) translateX(-5px);
-ms-transform: translateY(5px) translateX(-5px);
transform: translateY(5px) translateX(-5px);
}
.opentip-container.fixed.hidden.stem-middle.stem-left,
.opentip-container.fixed.going-to-show.stem-middle.stem-left,
.opentip-container.fixed.hiding.stem-middle.stem-left {
-webkit-transform: translateX(-5px);
-moz-transform: translateX(-5px);
-o-transform: translateX(-5px);
-ms-transform: translateX(-5px);
transform: translateX(-5px);
}
.opentip-container.fixed.hidden.stem-top.stem-left,
.opentip-container.fixed.going-to-show.stem-top.stem-left,
.opentip-container.fixed.hiding.stem-top.stem-left {
-webkit-transform: translateY(-5px) translateX(-5px);
-moz-transform: translateY(-5px) translateX(-5px);
-o-transform: translateY(-5px) translateX(-5px);
-ms-transform: translateY(-5px) translateX(-5px);
transform: translateY(-5px) translateX(-5px);
}
.opentip-container.fixed {
pointer-events: auto;
}
.opentip-container.hidden {
display: none;
}
.opentip-container .opentip {
position: relative;
font-size: 13px;
line-height: 120%;
padding: 9px 14px;
color: #4f4b47;
text-shadow: -1px -1px 0px rgba(255,255,255,0.2);
}
.opentip-container .opentip .header {
margin: 0;
padding: 0;
}
.opentip-container .opentip .close {
pointer-events: auto;
display: block;
position: absolute;
top: -12px;
left: 60px;
color: rgba(0,0,0,0.5);
background: rgba(0,0,0,0);
text-decoration: none;
}
.opentip-container .opentip .close span {
display: none;
}
.opentip-container .opentip .loading-indicator {
display: none;
}
.opentip-container.loading .loading-indicator {
display: block;
}
.opentip-container.style-dark .opentip,
.opentip-container.style-alert .opentip {
color: #f8f8f8;
text-shadow: 1px 1px 0px rgba(0,0,0,0.2);
}
.opentip-container.style-glass .opentip {
padding: 15px 25px;
color: #317cc5;
text-shadow: 1px 1px 8px rgba(0,94,153,0.3);
}
.opentip-container.hide-effect-fade {
-webkit-transition: -webkit-transform 0.5s ease-in-out, opacity 1s ease-in-out;
-moz-transition: -moz-transform 0.5s ease-in-out, opacity 1s ease-in-out;
-o-transition: -o-transform 0.5s ease-in-out, opacity 1s ease-in-out;
-ms-transition: -ms-transform 0.5s ease-in-out, opacity 1s ease-in-out;
transition: transform 0.5s ease-in-out, opacity 1s ease-in-out;
opacity: 1;
-ms-filter: none;
filter: none;
}
.opentip-container.hide-effect-fade.hiding {
opacity: 0;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
filter: alpha(opacity=0);
}
.opentip-container.show-effect-appear.going-to-show,
.opentip-container.show-effect-appear.showing {
-webkit-transition: -webkit-transform 0.5s ease-in-out, opacity 1s ease-in-out;
-moz-transition: -moz-transform 0.5s ease-in-out, opacity 1s ease-in-out;
-o-transition: -o-transform 0.5s ease-in-out, opacity 1s ease-in-out;
-ms-transition: -ms-transform 0.5s ease-in-out, opacity 1s ease-in-out;
transition: transform 0.5s ease-in-out, opacity 1s ease-in-out;
}
.opentip-container.show-effect-appear.going-to-show {
opacity: 0;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
filter: alpha(opacity=0);
}
.opentip-container.show-effect-appear.showing {
opacity: 1;
-ms-filter: none;
filter: none;
}
.opentip-container.show-effect-appear.visible {
opacity: 1;
-ms-filter: none;
filter: none;
}
| pvnr0082t/cdnjs | ajax/libs/opentip/2.2.1/css/opentip.css | CSS | mit | 6,304 |
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var Order = function (_Declaration) {
_inherits(Order, _Declaration);
function Order() {
_classCallCheck(this, Order);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 and 2012 specs
*/
Order.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-ordinal-group';
} else if (spec === 2012) {
return prefix + 'flex-order';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
Order.prototype.normalize = function normalize() {
return 'order';
};
/**
* Fix value for 2009 spec
*/
Order.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009 && /\d/.test(decl.value)) {
decl.value = (parseInt(decl.value) + 1).toString();
return _Declaration.prototype.set.call(this, decl, prefix);
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
return Order;
}(Declaration);
Object.defineProperty(Order, 'names', {
enumerable: true,
writable: true,
value: ['order', 'flex-order', 'box-ordinal-group']
});
module.exports = Order; | scaulfield01/HallHorn | node_modules/autoprefixer/lib/hacks/order.js | JavaScript | mit | 2,546 |
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2014 Petka Antonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
* bluebird build version 2.9.22
* Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
*/
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,r;return function n(t,e,r){function i(s,a){if(!e[s]){if(!t[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r?r:e)},l,l.exports,n,t,e,r)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(t,e){"use strict";e.exports=function(t){function e(t){var e=new r(t),n=e.promise();return e.setHowMany(1),e.setUnwrap(),e.init(),n}var r=t._SomePromiseArray;t.any=function(t){return e(t)},t.prototype.any=function(){return e(this)}}},{}],2:[function(t,e){"use strict";function r(){this._isTickUsed=!1,this._lateQueue=new c(16),this._normalQueue=new c(16),this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=u.isStatic?u(this.drainQueues):u}function n(t,e,r){t=this._withDomain(t),this._lateQueue.push(t,e,r),this._queueTick()}function i(t,e,r){t=this._withDomain(t),this._normalQueue.push(t,e,r),this._queueTick()}function o(t){this._normalQueue._pushOne(t),this._queueTick()}var s;try{throw new Error}catch(a){s=a}var u=t("./schedule.js"),c=t("./queue.js"),l="undefined"!=typeof process?process:void 0,h=t("./util.js");r.prototype.disableTrampolineIfNecessary=function(){h.hasDevTools&&(this._trampolineEnabled=!1)},r.prototype.enableTrampoline=function(){this._trampolineEnabled||(this._trampolineEnabled=!0,this._schedule=function(t){setTimeout(t,0)})},r.prototype.haveItemsQueued=function(){return this._normalQueue.length()>0},r.prototype._withDomain=function(t){return void 0===l||null==l.domain||t.domain||(t=l.domain.bind(t)),t},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),t=this._withDomain(t),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(r){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},h.hasDevTools?(r.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?n.call(this,t,e,r):setTimeout(function(){t.call(e,r)},100)},r.prototype.invoke=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):setTimeout(function(){t.call(e,r)},0)},r.prototype.settlePromises=function(t){this._trampolineEnabled?o.call(this,t):setTimeout(function(){t._settlePromises()},0)}):(r.prototype.invokeLater=n,r.prototype.invoke=i,r.prototype.settlePromises=o),r.prototype.invokeFirst=function(t,e,r){t=this._withDomain(t),this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=new r,e.exports.firstLineError=s},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(t,e){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._setBoundTo(t),this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(a instanceof t){var l={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,l),a._then(o,s,u._progress,u,l)}else u._setBoundTo(n),u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return o instanceof t?o._then(function(t){s._setBoundTo(t),s._resolveCallback(i)},s._reject,s._progress,s,null):(s._setBoundTo(n),s._resolveCallback(i)),s}}},{}],4:[function(t,e){"use strict";function r(){try{Promise===i&&(Promise=n)}catch(t){}return i}var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise.js")();i.noConflict=r,e.exports=i},{"./promise.js":23}],5:[function(t,e){"use strict";var r=Object.create;if(r){var n=r(null),i=r(null);n[" size"]=i[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(t,e){"use strict";e.exports=function(){function e(t){this._parent=t;var r=this._length=1+(void 0===t?0:t._length);j(this,e),r>32&&this.uncycle()}function r(t,e){for(var r=0;r<e.length-1;++r)e[r].push("From previous event:"),e[r]=e[r].join("\n");return r<e.length&&(e[r]=e[r].join("\n")),t+"\n"+e.join("\n")}function n(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}function i(t){for(var e=t[0],r=1;r<t.length;++r){for(var n=t[r],i=e.length-1,o=e[i],s=-1,a=n.length-1;a>=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function o(t){for(var e=[],r=0;r<t.length;++r){var n=t[r],i=_.test(n)||" (No stack trace)"===n,o=i&&y(n);i&&!o&&(v&&" "!==n.charAt(0)&&(n=" "+n),e.push(n))}return e}function s(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),r=0;r<e.length;++r){var n=e[r];if(" (No stack trace)"===n||_.test(n))break}return r>0&&(e=e.slice(r)),e}function a(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+u(e)+">, no stack trace)"}function u(t){var e=41;return t.length<e?t:t.substr(0,e-3)+"..."}function c(t){var e=t.match(g);return e?{fileName:e[1],line:parseInt(e[2],10)}:void 0}var l,h=t("./async.js"),p=t("./util.js"),f=/[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/,_=null,d=null,v=!1;p.inherits(e,Error),e.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=n-2;l>=0;--l)e[l]._length=c,c++;return}}}},e.prototype.parent=function(){return this._parent},e.prototype.hasParent=function(){return void 0!==this._parent},e.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var s=e.parseStackAndMessage(t),a=s.message,u=[s.stack],c=this;void 0!==c;)u.push(o(c.stack.split("\n"))),c=c._parent;i(u),n(u),p.notEnumerableProp(t,"stack",r(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},e.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?s(t):[" (No stack trace)"],{message:r,stack:o(e)}},e.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+d(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},e.unhandledRejection=function(t){e.formatAndLogError(t,"^--- With additional stack trace: ")},e.isSupported=function(){return"function"==typeof j},e.fireRejectionEvent=function(t,r,n,i){var o=!1;try{"function"==typeof r&&(o=!0,"rejectionHandled"===t?r(i):r(n,i))}catch(s){h.throwLater(s)}var a=!1;try{a=b(t,n,i)}catch(s){a=!0,h.throwLater(s)}var u=!1;if(m)try{u=m(t.toLowerCase(),{reason:n,promise:i})}catch(s){u=!0,h.throwLater(s)}a||o||u||"unhandledRejection"!==t||e.formatAndLogError(n,"Unhandled rejection ")};var y=function(){return!1},g=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;e.setBounds=function(t,r){if(e.isSupported()){for(var n,i,o=t.stack.split("\n"),s=r.stack.split("\n"),a=-1,u=-1,l=0;l<o.length;++l){var h=c(o[l]);if(h){n=h.fileName,a=h.line;break}}for(var l=0;l<s.length;++l){var h=c(s[l]);if(h){i=h.fileName,u=h.line;break}}0>a||0>u||!n||!i||n!==i||a>=u||(y=function(t){if(f.test(t))return!0;var e=c(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var m,j=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():a(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,d=e;var r=Error.captureStackTrace;return y=function(t){return f.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,d=e,v=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in n||!i?(d=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?a(e):e.toString()},null):(_=t,d=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),b=function(){if(p.isNode)return function(t,e,r){return"rejectionHandled"===t?process.emit(t,r):process.emit(t,e,r)};var t=!1,e=!0;try{var r=new self.CustomEvent("test");t=r instanceof CustomEvent}catch(n){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(n){e=!1}e&&(m=function(e,r){var n;return t?n=new self.CustomEvent(e,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(e,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&process.stderr.isTTY?l=function(t){process.stderr.write("[31m"+t+"[39m\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),e}},{"./async.js":2,"./util.js":38}],8:[function(t,e){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundTo,u=0,c=this._instances.length;c>u;++u){var l=this._instances[u],h=l===Error||null!=l&&l.prototype instanceof Error;if(h&&t instanceof l){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}if("function"==typeof l&&!h){var f=n(l,t);if(f===a){t=a.e;break}if(f){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(t,e){"use strict";e.exports=function(e,r){var n,i,o=t("./async.js"),s=t("./errors.js").Warning,a=t("./util.js"),u=a.canAttachTrace,c=!1||a.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return c&&o.disableTrampolineIfNecessary(),e.prototype._ensurePossibleRejectionHandled=function(){this._setRejectionIsUnhandled(),o.invokeLater(this._notifyUnhandledRejection,this,void 0)},e.prototype._notifyUnhandledRejectionIsHandled=function(){r.fireRejectionEvent("rejectionHandled",n,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),r.fireRejectionEvent("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},e.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},e.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},e.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},e.prototype._captureStackTrace=function(){return c&&(this._trace=new r(this._peekContext())),this},e.prototype._attachExtraTrace=function(t,e){if(c&&u(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=r.parseStackAndMessage(t);a.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),a.notEnumerableProp(t,"__stackCleaned__",!0)}}},e.prototype._warn=function(t){var e=new s(t),n=this._peekContext();if(n)n.attachExtraTrace(e);else{var i=r.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}r.formatAndLogError(e,"")},e.onPossiblyUnhandledRejection=function(t){i="function"==typeof t?t:void 0},e.onUnhandledRejectionHandled=function(t){n="function"==typeof t?t:void 0},e.longStackTraces=function(){if(o.haveItemsQueued()&&c===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");c=r.isSupported(),c&&o.disableTrampolineIfNecessary()},e.hasLongStackTraces=function(){return c&&r.isSupported()},r.isSupported()||(e.longStackTraces=function(){},c=!1),function(){return c}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e){"use strict";var r=t("./util.js"),n=r.isPrimitive,i=r.wrapsPrimitiveReceiver;e.exports=function(t){var e=function(){return this},r=function(){throw this},o=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype["return"]=t.prototype.thenReturn=function(t){return i&&n(t)?this._then(o(t,2),void 0,void 0,void 0,void 0):this._then(e,void 0,void 0,t,void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return i&&n(t)?this._then(o(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e){"use strict";function r(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return c(r,Error),r}function n(t){return this instanceof n?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new n(t)}var i,o,s=t("./es5.js"),a=s.freeze,u=t("./util.js"),c=u.inherits,l=u.notEnumerableProp,h=r("Warning","warning"),p=r("CancellationError","cancellation error"),f=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=r("TypeError","type error"),o=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y<v.length;++y)"function"==typeof Array.prototype[v[y]]&&(_.prototype[v[y]]=Array.prototype[v[y]]);s.defineProperty(_.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),_.prototype.isOperational=!0;var g=0;_.prototype.toString=function(){var t=Array(4*g+1).join(" "),e="\n"+t+"AggregateError of:\n";g++,t=Array(4*g+1).join(" ");for(var r=0;r<this.length;++r){for(var n=this[r]===this?"[Circular AggregateError]":this[r]+"",i=n.split("\n"),o=0;o<i.length;++o)i[o]=t+i[o];n=i.join("\n"),e+=n+"\n"}return g--,e},c(n,Error);var m=Error.__BluebirdErrorTypes__;m||(m=a({CancellationError:p,TimeoutError:f,OperationalError:n,RejectionError:n,AggregateError:_}),l(Error,"__BluebirdErrorTypes__",m)),e.exports={Error:Error,TypeError:i,RangeError:o,CancellationError:m.CancellationError,OperationalError:m.OperationalError,TimeoutError:m.TimeoutError,AggregateError:m.AggregateError,Warning:h}},{"./es5.js":14,"./util.js":38}],14:[function(t,e){var r=function(){"use strict";return void 0===this}();if(r)e.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:r,propertyIsWritable:function(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return!(r&&!r.writable&&!r.set)}};else{var n={}.hasOwnProperty,i={}.toString,o={}.constructor.prototype,s=function(t){var e=[];for(var r in t)n.call(t,r)&&e.push(r);return e},a=function(t,e){return{value:t[e]}},u=function(t,e,r){return t[e]=r.value,t},c=function(t){return t},l=function(t){try{return Object(t).constructor.prototype}catch(e){return o}},h=function(t){try{return"[object Array]"===i.call(t)}catch(e){return!1}};e.exports={isArray:h,keys:s,names:s,defineProperty:u,getDescriptor:a,freeze:c,getPrototypeOf:l,isES5:r,propertyIsWritable:function(){return!0}}}},{}],15:[function(t,e){"use strict";e.exports=function(t,e){var r=t.map;t.prototype.filter=function(t,n){return r(this,t,n,e)},t.filter=function(t,n,i){return r(t,n,i,e)}}},{}],16:[function(t,e){"use strict";e.exports=function(e,r,n){function i(){return this}function o(){throw this}function s(t){return function(){return t}}function a(t){return function(){throw t}}function u(t,e,r){var n;return n=p&&f(e)?r?s(e):a(e):r?i:o,t._then(n,_,void 0,e,void 0)}function c(t){var i=this.promise,o=this.handler,s=i._isBound()?o.call(i._boundTo):o();if(void 0!==s){var a=n(s,i);if(a instanceof e)return a=a._target(),u(a,t,i.isFulfilled())}return i.isRejected()?(r.e=t,r):t}function l(t){var r=this.promise,i=this.handler,o=r._isBound()?i.call(r._boundTo,t):i(t);if(void 0!==o){var s=n(o,r);if(s instanceof e)return s=s._target(),u(s,t,!0)}return t}var h=t("./util.js"),p=h.wrapsPrimitiveReceiver,f=h.isPrimitive,_=h.thrower;e.prototype._passThroughHandler=function(t,e){if("function"!=typeof t)return this.then();var r={promise:this,handler:t};return this._then(e?c:l,e?c:void 0,void 0,r,void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThroughHandler(t,!0)},e.prototype.tap=function(t){return this._passThroughHandler(t,!1)}}},{"./util.js":38}],17:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t,r,n){for(var o=0;o<r.length;++o){n._pushContext();var s=h(r[o])(t);if(n._popContext(),s===l){n._pushContext();var a=e.reject(l.e);return n._popContext(),a}var u=i(s,n);if(u instanceof e)return u}return null}function s(t,r,i,o){var s=this._promise=new e(n);s._captureStackTrace(),this._stack=o,this._generatorFunction=t,this._receiver=r,this._generator=void 0,this._yieldHandlers="function"==typeof i?[i].concat(p):p}var a=t("./errors.js"),u=a.TypeError,c=t("./util.js"),l=c.errorObj,h=c.tryCatch,p=[];s.prototype.promise=function(){return this._promise},s.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._next(void 0)},s.prototype._continue=function(t){if(t===l)return this._promise._rejectCallback(t.e,!1,!0);var r=t.value;if(t.done===!0)this._promise._resolveCallback(r);else{var n=i(r,this._promise);if(!(n instanceof e)&&(n=o(n,this._yieldHandlers,this._promise),null===n))return void this._throw(new u("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/4Y4pDk\n\n".replace("%s",r)+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")));n._then(this._next,this._throw,void 0,this,null)}},s.prototype._throw=function(t){this._promise._attachExtraTrace(t),this._promise._pushContext();var e=h(this._generator["throw"]).call(this._generator,t);this._promise._popContext(),this._continue(e)},s.prototype._next=function(t){this._promise._pushContext();var e=h(this._generator.next).call(this._generator,t);this._promise._popContext(),this._continue(e)},e.coroutine=function(t,e){if("function"!=typeof t)throw new u("generatorFunction must be a function\n\n See http://goo.gl/6Vqhm0\n");var r=Object(e).yieldHandler,n=s,i=(new Error).stack;return function(){var e=t.apply(this,arguments),o=new n(void 0,void 0,r,i);return o._generator=e,o._next(void 0),o.promise()}},e.coroutine.addYieldHandler=function(t){if("function"!=typeof t)throw new u("fn must be a function\n\n See http://goo.gl/916lJJ\n");p.push(t)},e.spawn=function(t){if("function"!=typeof t)return r("generatorFunction must be a function\n\n See http://goo.gl/6Vqhm0\n");var n=new s(t,this),i=n.promise();return n._run(e.spawn),i}}},{"./errors.js":13,"./util.js":38}],18:[function(t,e){"use strict";e.exports=function(e,r,n,i){{var o=t("./util.js");o.canEvaluate,o.tryCatch,o.errorObj}e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace(),this._callback=e,this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:_,c.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj,f={},_=[];l.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===f){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundTo;this._promise._pushContext();var l=h(u).call(c,t,r,o);if(this._promise._popContext(),l===p)return this._reject(l.e);var _=i(l,this._promise);if(_ instanceof e){if(_=_._target(),_._isPending())return a>=1&&this._inFlight++,n[r]=f,_._proxyPromiseArray(this,r);if(!_._isFulfilled())return this._reject(_._reason());l=_._value()}n[r]=l}var d=++this._totalResolved;d>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlight<e;){if(this._isResolved())return;var n=t.pop();this._promiseFulfilled(r[n],n)}},s.prototype._filter=function(t,e){for(var r=e.length,n=new Array(r),i=0,o=0;r>o;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e["try"]=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundTo,[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundTo,i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundTo,t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var l=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(l),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(t,e){"use strict";e.exports=function(){function e(t){if("function"!=typeof t)throw new c("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==e)throw new c("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==l&&this._resolveFromResolver(t)}function r(t){var r=new e(l);r._fulfillmentHandler0=t,r._rejectionHandler0=t,r._progressHandler0=t,r._promise0=t,r._receiver0=t,r._settledValue=t}var n=function(){return new c("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},i=function(){return new e.PromiseInspection(this._target())},o=function(t){return e.reject(new c(t))},s=t("./util.js"),a=t("./async.js"),u=t("./errors.js"),c=e.TypeError=u.TypeError;e.RangeError=u.RangeError,e.CancellationError=u.CancellationError,e.TimeoutError=u.TimeoutError,e.OperationalError=u.OperationalError,e.RejectionError=u.OperationalError,e.AggregateError=u.AggregateError;var l=function(){},h={},p={e:null},f=t("./thenables.js")(e,l),_=t("./promise_array.js")(e,l,f,o),d=t("./captured_trace.js")(),v=t("./debuggability.js")(e,d),y=t("./context.js")(e,d,v),g=t("./catch_filter.js")(p),m=t("./promise_resolver.js"),j=m._nodebackForPromise,b=s.errorObj,w=s.tryCatch;return e.prototype.toString=function(){return"[object Promise]"},e.prototype.caught=e.prototype["catch"]=function(t){var r=arguments.length;if(r>1){var n,i=new Array(r-1),o=0;for(n=0;r-1>n;++n){var s=arguments[n];if("function"!=typeof s)return e.reject(new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new g(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},e.prototype.reflect=function(){return this._then(i,i,void 0,this,void 0)},e.prototype.then=function(t,e,r){if(v()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+s.classString(t);arguments.length>1&&(n+=", "+s.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},e.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);n._setIsFinal()},e.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,h,void 0)},e.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()},e.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t
},e.prototype.all=function(){return new _(this).promise()},e.prototype.error=function(t){return this.caught(s.originatesFromRejection,t)},e.is=function(t){return t instanceof e},e.fromNode=function(t){var r=new e(l),n=w(t)(j(r));return n===b&&r._rejectCallback(n.e,!0,!0),r},e.all=function(t){return new _(t).promise()},e.defer=e.pending=function(){var t=new e(l);return new m(t)},e.cast=function(t){var r=f(t);if(!(r instanceof e)){var n=r;r=new e(l),r._fulfillUnchecked(n)}return r},e.resolve=e.fulfilled=e.cast,e.reject=e.rejected=function(t){var r=new e(l);return r._captureStackTrace(),r._rejectCallback(t,!0),r},e.setScheduler=function(t){if("function"!=typeof t)throw new c("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=a._schedule;return a._schedule=t,e},e.prototype._then=function(t,r,n,i,o){var s=void 0!==o,u=s?o:new e(l);s||(u._propagateFrom(this,5),u._captureStackTrace());var c=this._target();c!==this&&(void 0===i&&(i=this._boundTo),s||u._setIsMigrated());var h=c._addCallbacks(t,r,n,u,i);return c._isResolved()&&!c._isSettlePromisesQueued()&&a.invoke(c._settlePromiseAtPostResolution,c,h),u},e.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},e.prototype._length=function(){return 131071&this._bitField},e.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},e.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},e.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},e.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},e.prototype._setRejected=function(){this._bitField=134217728|this._bitField},e.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},e.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},e.prototype._isFinal=function(){return(33554432&this._bitField)>0},e.prototype._cancellable=function(){return(67108864&this._bitField)>0},e.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},e.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},e.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},e.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},e.prototype._isMigrated=function(){return(4194304&this._bitField)>0},e.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];return void 0===e&&this._isBound()?this._boundTo:e},e.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},e.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},e.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},e.prototype._migrateCallbacks=function(t,r){var n=t._fulfillmentHandlerAt(r),i=t._rejectionHandlerAt(r),o=t._progressHandlerAt(r),s=t._promiseAt(r),a=t._receiverAt(r);s instanceof e&&s._setIsMigrated(),this._addCallbacks(n,i,o,s,a)},e.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=131066&&(o=0,this._setLength(0)),0===o)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=t),"function"==typeof e&&(this._rejectionHandler0=e),"function"==typeof r&&(this._progressHandler0=r);else{var s=5*o-5;this[s+3]=n,this[s+4]=i,"function"==typeof t&&(this[s+0]=t),"function"==typeof e&&(this[s+1]=e),"function"==typeof r&&(this[s+2]=r)}return this._setLength(o+1),o},e.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},e.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},e.prototype._resolveCallback=function(t,r){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(n(),!1,!0);var i=f(t,this);if(!(i instanceof e))return this._fulfill(t);var o=1|(r?4:0);this._propagateFrom(i,o);var s=i._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},e.prototype._rejectCallback=function(t,e,r){r||s.markAsOriginatingFromRejection(t);var n=s.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},e.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=w(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===b&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},e.prototype._settlePromiseFromHandler=function(t,e,r,i){if(!i._isRejected()){i._pushContext();var o;if(o=e!==h||this._isRejected()?w(t).call(e,r):w(t).apply(this._boundTo,r),i._popContext(),o===b||o===i||o===p){var s=o===i?n():o.e;i._rejectCallback(s,!1,!0)}else i._resolveCallback(o)}},e.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},e.prototype._followee=function(){return this._rejectionHandler0},e.prototype._setFollowee=function(t){this._rejectionHandler0=t},e.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},e.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},e.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},e.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},e.prototype._settlePromiseAt=function(t){var r=this._promiseAt(t),n=r instanceof e;if(n&&r._isMigrated())return r._unsetIsMigrated(),a.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,u=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,u,s,r):i.call(u,s,r):u instanceof _?u._isResolved()||(this._isFulfilled()?u._promiseFulfilled(s,r):u._promiseRejected(s,r)):n&&(this._isFulfilled()?r._fulfill(s):r._reject(s,o)),t>=4&&4===(31&t)&&a.invokeLater(this._setLength,this,0)},e.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},e.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},e.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},e.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},e.prototype._queueSettlePromises=function(){a.settlePromises(this),this._setSettlePromisesQueued()},e.prototype._fulfillUnchecked=function(t){if(t===this){var e=n();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},e.prototype._rejectUncheckedCheckError=function(t){var e=s.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},e.prototype._rejectUnchecked=function(t,e){if(t===this){var r=n();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void a.throwLater(function(t){throw"stack"in t&&a.invokeFirst(d.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},e.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},e._makeSelfResolutionError=n,t("./progress.js")(e,_),t("./method.js")(e,l,f,o),t("./bind.js")(e,l,f),t("./finally.js")(e,p,f),t("./direct_resolve.js")(e),t("./synchronous_inspection.js")(e),t("./join.js")(e,_,f,l),e.Promise=e,t("./map.js")(e,_,o,f,l),t("./cancel.js")(e),t("./using.js")(e,o,f,y),t("./generators.js")(e,o,l,f),t("./nodeify.js")(e),t("./call_get.js")(e),t("./props.js")(e,_,f,o),t("./race.js")(e,l,f,o),t("./reduce.js")(e,_,o,f,l),t("./settle.js")(e,_),t("./some.js")(e,_,o),t("./promisify.js")(e,l),t("./any.js")(e),t("./each.js")(e,l),t("./timers.js")(e,l),t("./filter.js")(e,l),s.toFastProperties(e),s.toFastProperties(e.prototype),r({a:1}),r({b:2}),r({c:3}),r(1),r(function(){}),r(void 0),r(!1),r(new e(l)),d.setBounds(a.firstLineError,s.lastLineError),e}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function c(t,r){var s=n(this._values,this._promise);if(s instanceof e){if(s=s._target(),this._values=s,!s._isFulfilled())return s._isPending()?void s._then(c,this._reject,void 0,this,r):void this._reject(s._reason());if(s=s._value(),!u(s)){var a=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(a)}}else if(!u(s))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===s.length)return void(-5===r?this._resolveEmptyArray():this._resolve(o(r)));var l=this.getActualLength(s.length);this._length=l,this._values=this.shouldCopyValues()?new Array(l):this._values;for(var h=this._promise,p=0;l>p;++p){var f=this._isResolved(),_=n(s[p],h);_ instanceof e?(_=_._target(),f?_._unsetRejectionIsUnhandled():_._isPending()?_._proxyPromiseArray(this,p):_._isFulfilled()?this._promiseFulfilled(_._value(),p):this._promiseRejected(_._reason(),p)):f||this._promiseFulfilled(_,p)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e){"use strict";function r(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function n(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=p.keys(t),i=0;i<n.length;++i){var o=n[i];f.test(o)||(e[o]=t[o])}return e}return s.markAsOriginatingFromRejection(t),t}function i(t){return function(e,r){if(null!==t){if(e){var i=n(a(e));t._attachExtraTrace(i),t._reject(i)}else if(arguments.length>2){for(var o=arguments.length,s=new Array(o-1),u=1;o>u;++u)s[u-1]=arguments[u];t._fulfill(s)}else t._fulfill(r);t=null}}}var o,s=t("./util.js"),a=s.maybeWrapAsError,u=t("./errors.js"),c=u.TimeoutError,l=u.OperationalError,h=s.haveGetters,p=t("./es5.js"),f=/^(?:name|message|stack|cause)$/;if(o=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=i(t),this.callback=this.asCallback},h){var _={get:function(){return i(this.promise)}};p.defineProperty(o.prototype,"asCallback",_),p.defineProperty(o.prototype,"callback",_)}o._nodebackForPromise=i,o.prototype.toString=function(){return"[object PromiseResolver]"},o.prototype.resolve=o.prototype.fulfill=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},o.prototype.reject=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},o.prototype.progress=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},o.prototype.cancel=function(t){this.promise.cancel(t)},o.prototype.timeout=function(){this.reject(new c("timeout"))},o.prototype.isResolved=function(){return this.promise.isResolved()},o.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=o},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e){"use strict";e.exports=function(e,r){function n(t){return!b.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,r){var n=f.getDataPropertyOrDefault(t,e+r,j);return n?i(n):!1}function s(t,e,r){for(var n=0;n<t.length;n+=2){var i=t[n];if(r.test(i))for(var o=i.replace(r,""),s=0;s<t.length;s+=2)if(t[s]===o)throw new g("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/iWrZbw\n".replace("%s",e))}}function a(t,e,r,n){for(var a=f.inheritedDataKeys(t),u=[],c=0;c<a.length;++c){var l=a[c],h=t[l],p=n===w?!0:w(l,h,t);"function"!=typeof h||i(h)||o(t,l,e)||!n(l,h,t,p)||u.push(l,h)}return s(u,e,r),u}function u(t,n,i,o){function s(){var i=n;n===p&&(i=this);var o=new e(r);o._captureStackTrace();var s="string"==typeof u&&this!==a?this[u]:t,c=_(o);try{s.apply(i,d(arguments,c))}catch(l){o._rejectCallback(v(l),!0,!0)}return o}var a=function(){return this}(),u=t;return"string"==typeof u&&(t=o),s.__isPromisified__=!0,s}function c(t,e,r,n){for(var i=new RegExp(k(e)+"$"),o=a(t,e,i,r),s=0,u=o.length;u>s;s+=2){var c=o[s],l=o[s+1],h=c+e;t[h]=n===E?E(c,p,c,l,e):n(l,function(){return E(c,p,c,l,e)})}return f.toFastProperties(t),t}function l(t,e){return E(t,e,void 0,t)}var h,p={},f=t("./util.js"),_=t("./promise_resolver.js")._nodebackForPromise,d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",j={__isPromisified__:!0},b=/^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/,w=function(t,e){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&!f.isClass(e)},k=function(t){return t.replace(/([$])/,"\\$")},E=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new g("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=l(t,arguments.length<2?p:e);return f.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=w);var i=e.promisifier;if("function"!=typeof i&&(i=E),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=f.inheritedDataKeys(t),s=0;s<o.length;++s){var a=t[o[s]];"constructor"!==o[s]&&f.isClass(a)&&(c(a.prototype,r,n,i),c(a,r,n,i))}return c(t,r,n,i)}}},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var e=c.keys(t),r=e.length,n=new Array(2*r),i=0;r>i;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e){"use strict";function r(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacity<t},n.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1);var r=this._front+e&this._capacity-1;this[r]=t,this._length=e+1},n.prototype._unshiftOne=function(t){var e=this._capacity;this._checkCapacity(this.length()+1);var r=this._front,n=(r-1&e-1^e)-e;this[n]=t,this._front=n,this._length=this.length()+1},n.prototype.unshift=function(t,e,r){this._unshiftOne(r),this._unshiftOne(e),this._unshiftOne(t)},n.prototype.push=function(t,e,r){var n=this.length()+3;if(this._willBeOverCapacity(n))return this._pushOne(t),this._pushOne(e),void this._pushOne(r);var i=this._front+n-3;this._checkCapacity(n);var o=this._capacity-1;this[i+0&o]=t,this[i+1&o]=e,this[i+2&o]=r,this._length=n},n.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},n.prototype.length=function(){return this._length},n.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},n.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t;var n=this._front,i=this._length,o=n+i&e-1;r(this,0,this,e,o)},e.exports=n},{}],29:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t,o){var u=n(t);if(u instanceof e)return a(u);if(!s(t))return i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");var c=new e(r);void 0!==o&&c._propagateFrom(o,5);for(var l=c._fulfill,h=c._reject,p=0,f=t.length;f>p;++p){var _=t[p];(void 0!==_||p in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),l=!1,h=u instanceof e;h&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),l=!0)),h||this._zerothIsAccum||(this._gotAccum=!0),this._callback=r,this._accum=n,l||c.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj;l.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,l=this._valuesPhase;if(!l)for(l=this._valuesPhase=new Array(s),o=0;s>o;++o)l[o]=0;if(o=l[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,l[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?l[r]=1:(l[r]=2,this._accum=t),c){for(var f,_=this._callback,d=this._promise._boundTo,v=this._reducingIndex;s>v;++v)if(o=l[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),f=h(_).call(d,t,v,s)):f=h(_).call(d,this._accum,t,v,s),this._promise._popContext(),f===p)return this._reject(f.e);var y=i(f,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return l[v]=4,y._proxyPromiseArray(this,v);if(!y._isFulfilled())return this._reject(y._reason());f=y._value()}this._reducingIndex=v+1,this._accum=f}else this._reducingIndex=v+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(t,e){"use strict";var r,n=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(t("./util.js").isNode){var i=process.versions.node.split(".").map(Number);r=0===i[0]&&i[1]>10||i[0]>0?global.setImmediate:process.nextTick,r||(r="undefined"!=typeof setImmediate?setImmediate:"undefined"!=typeof setTimeout?setTimeout:n)}else"undefined"!=typeof MutationObserver?(r=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},r.isStatic=!0):r="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:n;e.exports=r},{"./util.js":38}],32:[function(t,e){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r<this._values.length;++r)e.push(this._values[r]);this._reject(e)}},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors.js":13,"./util.js":38}],34:[function(t,e){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValue=t._settledValue):(this._bitField=0,this._settledValue=void 0)}e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return this._settledValue},e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return this._settledValue},e.prototype.isFulfilled=t.prototype._isFulfilled=function(){return(268435456&this._bitField)>0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var l=new e(r);return t._then(l._fulfillUnchecked,l._rejectUncheckedCheckError,l._progressUnchecked,l,null),l}var h=a.tryCatch(i)(t);if(h===u){n&&n._pushContext();var l=e.reject(h.e);return n&&n._popContext(),l}if("function"==typeof h)return s(t,h,n)}return t}function i(t){return t.then}function o(t){return l.call(t,"_promise0")}function s(t,n,i){function o(r){l&&(t===r?l._rejectCallback(e._makeSelfResolutionError(),!1,!0):l._resolveCallback(r),l=null)}function s(t){l&&(l._rejectCallback(t,p,!0),l=null)}function c(t){l&&"function"==typeof l._progress&&l._progress(t)}var l=new e(r),h=l;i&&i._pushContext(),l._captureStackTrace(),i&&i._popContext();var p=!0,f=a.tryCatch(n).call(t,o,s,c);return p=!1,l&&f===u&&(l._rejectCallback(f.e,!0,!0),l=null),h}var a=t("./util.js"),u=a.errorObj,c=a.isObject,l={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){"string"!=typeof e&&(e="operation timed out");var r=new s(e);o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var l=a(t[o++]);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(h){return s(h)}if(l instanceof e)return l._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new v;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function l(t){var e=new v;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function h(t,e,r){this._data=t,this._promise=e,this._context=r}function p(t,e,r){this.constructor$(t,e,r)}function f(t){return h.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var _=t("./errors.js").TypeError,d=t("./util.js").inherits,v=e.PromiseInspection;h.prototype.data=function(){return this._data},h.prototype.promise=function(){return this._promise},h.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},h.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},h.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},d(p,h),p.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");t--;for(var s=new Array(t),a=0;t>a;++a){var u=arguments[a];if(h.isDisposer(u)){var p=u;u=u.promise(),u._setDisposable(p)}else{var _=n(u);_ instanceof e&&(u=_._then(f,null,null,{resources:s,index:a},void 0))}s[a]=u}var d=e.settle(s).then(o).then(function(t){d._pushContext();var e;try{e=i.apply(void 0,t)}finally{d._popContext()}return e})._then(c,l,void 0,s,void 0);return s.promise=d,d},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new _}}},{"./errors.js":13,"./util.js":38}],38:[function(t,e,r){"use strict";function n(){try{return C.apply(this,arguments)}catch(t){return F.e=t,F}}function i(t){return C=t,n}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return!o(t)}function a(t){return o(t)?new Error(v(t)):t}function u(t,e){var r,n=t.length,i=new Array(n+1);
for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function c(t,e,r){if(!w.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(o(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return w.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=w.names(t.prototype);return w.isES5?e.length>1:e.length>0&&!(1===e.length&&"constructor"===e[0])}return!1}catch(r){return!1}}function f(t){function e(){}return e.prototype=t,e}function _(t){return R.test(t)}function d(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{l(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&w.propertyIsWritable(t,"stack")}function j(t){return{}.toString.call(t)}function b(t,e,r){for(var n=w.names(t),i=0;i<n.length;++i){var o=n[i];r(o)&&w.defineProperty(e,o,w.getDescriptor(t,o))}}var w=t("./es5.js"),k="undefined"==typeof navigator,E=function(){try{var t={};return w.defineProperty(t,"f",{get:function(){return 3}}),3===t.f}catch(e){return!1}}(),F={e:{}},C,T=function(t,e){function r(){this.constructor=t,this.constructor$=e;for(var r in e.prototype)n.call(e.prototype,r)&&"$"!==r.charAt(r.length-1)&&(this[r+"$"]=e.prototype[r])}var n={}.hasOwnProperty;return r.prototype=e.prototype,t.prototype=new r,t.prototype},P=function(){return"string"!==this}.call("string"),x=function(){if(w.isES5){var t=Object.prototype,e=Object.getOwnPropertyNames;return function(r){for(var n=[],i=Object.create(null);null!=r&&r!==t;){var o;try{o=e(r)}catch(s){return n}for(var a=0;a<o.length;++a){var u=o[a];if(!i[u]){i[u]=!0;var c=Object.getOwnPropertyDescriptor(r,u);null!=c&&null==c.get&&null==c.set&&n.push(u)}}r=w.getPrototypeOf(r)}return n}}return function(t){var e=[];for(var r in t)e.push(r);return e}}(),R=/^[a-z$_][a-z$_0-9]*$/i,S=function(){return"stack"in new Error?function(t){return m(t)?t:new Error(v(t))}:function(t){if(m(t))return t;try{throw new Error(v(t))}catch(e){return e}}}(),A={isClass:p,isIdentifier:_,inheritedDataKeys:x,getDataPropertyOrDefault:c,thrower:h,isArray:w.isArray,haveGetters:E,notEnumerableProp:l,isPrimitive:o,isObject:s,canEvaluate:k,errorObj:F,tryCatch:i,inherits:T,withAppended:u,maybeWrapAsError:a,wrapsPrimitiveReceiver:P,toFastProperties:f,filledRange:d,toString:v,canAttachTrace:m,ensureErrorObject:S,originatesFromRejection:g,markAsOriginatingFromRejection:y,classString:j,copyDescriptors:b,hasDevTools:"undefined"!=typeof chrome&&chrome&&"function"==typeof chrome.loadTimes,isNode:"undefined"!=typeof process&&"[object process]"===j(process).toLowerCase()};try{throw new Error}catch(O){A.lastLineError=O}e.exports=A},{"./es5.js":14}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); | MenZil/jsdelivr | files/bluebird/2.9.22/bluebird.min.js | JavaScript | mit | 68,600 |
YUI.add('event-valuechange', function(Y) {
/**
* Adds a synthetic <code>valueChange</code> event that fires when the
* <code>value</code> property of an input field or textarea changes as a result
* of a keystroke, mouse operation, or input method editor (IME) input event.
*
* @module event-valuechange
*/
/**
* Provides the implementation for the synthetic <code>valueChange</code> event.
*
* @class ValueChange
* @static
*/
var YArray = Y.Array,
VALUE = 'value',
// Just a simple namespace to make methods overridable.
VC = {
// -- Static Constants -----------------------------------------------------
/**
* Interval (in milliseconds) at which to poll for changes to the value of
* an element with one or more <code>valueChange</code> subscribers when the
* user is likely to be interacting with it.
*
* @property POLL_INTERVAL
* @type Number
* @default 50
* @static
*/
POLL_INTERVAL: 50,
/**
* Timeout (in milliseconds) after which to stop polling when there hasn't
* been any new activity (keypresses, mouse clicks, etc.) on an element.
*
* @property TIMEOUT
* @type Number
* @default 10000
* @static
*/
TIMEOUT: 10000,
// -- Protected Static Properties ------------------------------------------
_history : {},
_intervals: {},
_notifiers: {},
_timeouts : {},
// -- Protected Static Methods ---------------------------------------------
/**
* Called at an interval to poll for changes to the value of the specified
* node.
*
* @method _poll
* @param {Node} node
* @param {String} stamp
* @param {EventFacade} e
* @protected
* @static
*/
_poll: function (node, stamp, e) {
var domNode = node._node, // performance cheat; getValue() is a big hit when polling
newVal = domNode && domNode.value,
prevVal = VC._history[stamp],
facade;
if (!domNode) {
Y.log('_poll: node ' + stamp + ' disappeared; stopping polling.', 'warn', 'event-valuechange');
VC._stopPolling(node, stamp);
return;
}
if (newVal !== prevVal) {
VC._history[stamp] = newVal;
facade = {
_event : e,
newVal : newVal,
prevVal: prevVal
};
YArray.each(VC._notifiers[stamp], function (notifier) {
notifier.fire(facade);
});
VC._refreshTimeout(node, stamp);
}
},
/**
* Restarts the inactivity timeout for the specified node.
*
* @method _refreshTimeout
* @param {Node} node
* @param {String} stamp
* @protected
* @static
*/
_refreshTimeout: function (node, stamp) {
VC._stopTimeout(node, stamp); // avoid dupes
// If we don't see any changes within the timeout period (10 seconds by
// default), stop polling.
VC._timeouts[stamp] = setTimeout(function () {
VC._stopPolling(node, stamp);
}, VC.TIMEOUT);
Y.log('_refreshTimeout: ' + stamp, 'info', 'event-valuechange');
},
/**
* Begins polling for changes to the <code>value</code> property of the
* specified node. If polling is already underway for the specified node,
* it will not be restarted unless the <i>force</i> parameter is
* <code>true</code>
*
* @method _startPolling
* @param {Node} node Node to watch.
* @param {String} stamp (optional) Object stamp for the node. Will be
* generated if not provided (provide it to improve performance).
* @param {EventFacade} e (optional) Event facade of the event that
* initiated the polling (if any).
* @param {Boolean} force (optional) If <code>true</code>, polling will be
* restarted even if we're already polling this node.
* @protected
* @static
*/
_startPolling: function (node, stamp, e, force) {
if (!stamp) {
stamp = Y.stamp(node);
}
// Don't bother continuing if we're already polling.
if (!force && VC._intervals[stamp]) {
return;
}
VC._stopPolling(node, stamp); // avoid dupes
// Poll for changes to the node's value. We can't rely on keyboard
// events for this, since the value may change due to a mouse-initiated
// paste event, an IME input event, or for some other reason that
// doesn't trigger a key event.
VC._intervals[stamp] = setInterval(function () {
VC._poll(node, stamp, e);
}, VC.POLL_INTERVAL);
VC._refreshTimeout(node, stamp, e);
Y.log('_startPolling: ' + stamp, 'info', 'event-valuechange');
},
/**
* Stops polling for changes to the specified node's <code>value</code>
* attribute.
*
* @method _stopPolling
* @param {Node} node
* @param {String} stamp (optional)
* @protected
* @static
*/
_stopPolling: function (node, stamp) {
if (!stamp) {
stamp = Y.stamp(node);
}
VC._intervals[stamp] = clearInterval(VC._intervals[stamp]);
VC._stopTimeout(node, stamp);
Y.log('_stopPolling: ' + stamp, 'info', 'event-valuechange');
},
/**
* Clears the inactivity timeout for the specified node, if any.
*
* @method _stopTimeout
* @param {Node} node
* @param {String} stamp (optional)
* @protected
* @static
*/
_stopTimeout: function (node, stamp) {
if (!stamp) {
stamp = Y.stamp(node);
}
VC._timeouts[stamp] = clearTimeout(VC._timeouts[stamp]);
},
// -- Protected Static Event Handlers --------------------------------------
/**
* Stops polling when a node's blur event fires.
*
* @method _onBlur
* @param {EventFacade} e
* @protected
* @static
*/
_onBlur: function (e) {
VC._stopPolling(e.currentTarget);
},
/**
* Resets a node's history and starts polling when a focus event occurs.
*
* @method _onFocus
* @param {EventFacade} e
* @protected
* @static
*/
_onFocus: function (e) {
var node = e.currentTarget;
VC._history[Y.stamp(node)] = node.get(VALUE);
VC._startPolling(node, null, e);
},
/**
* Starts polling when a node receives a keyDown event.
*
* @method _onKeyDown
* @param {EventFacade} e
* @protected
* @static
*/
_onKeyDown: function (e) {
VC._startPolling(e.currentTarget, null, e);
},
/**
* Starts polling when an IME-related keyUp event occurs on a node.
*
* @method _onKeyUp
* @param {EventFacade} e
* @protected
* @static
*/
_onKeyUp: function (e) {
// These charCodes indicate that an IME has started. We'll restart
// polling and give the IME up to 10 seconds (by default) to finish.
if (e.charCode === 229 || e.charCode === 197) {
VC._startPolling(e.currentTarget, null, e, true);
}
},
/**
* Starts polling when a node receives a mouseDown event.
*
* @method _onMouseDown
* @param {EventFacade} e
* @protected
* @static
*/
_onMouseDown: function (e) {
VC._startPolling(e.currentTarget, null, e);
},
/**
* Called when event-valuechange receives a new subscriber.
*
* @method _onSubscribe
* @param {Node} node
* @param {Subscription} subscription
* @param {SyntheticEvent.Notifier} notifier
* @protected
* @static
*/
_onSubscribe: function (node, subscription, notifier) {
var stamp = Y.stamp(node),
notifiers = VC._notifiers[stamp];
VC._history[stamp] = node.get(VALUE);
notifier._handles = node.on({
blur : VC._onBlur,
focus : VC._onFocus,
keydown : VC._onKeyDown,
keyup : VC._onKeyUp,
mousedown: VC._onMouseDown
});
if (!notifiers) {
notifiers = VC._notifiers[stamp] = [];
}
notifiers.push(notifier);
},
/**
* Called when event-valuechange loses a subscriber.
*
* @method _onUnsubscribe
* @param {Node} node
* @param {Subscription} subscription
* @param {SyntheticEvent.Notifier} notifier
* @protected
* @static
*/
_onUnsubscribe: function (node, subscription, notifier) {
var stamp = Y.stamp(node),
notifiers = VC._notifiers[stamp],
index = YArray.indexOf(notifiers, notifier);
notifier._handles.detach();
if (index !== -1) {
notifiers.splice(index, 1);
if (!notifiers.length) {
VC._stopPolling(node, stamp);
delete VC._notifiers[stamp];
delete VC._history[stamp];
}
}
}
};
/**
* <p>
* Synthetic event that fires when the <code>value</code> property of an input
* field or textarea changes as a result of a keystroke, mouse operation, or
* input method editor (IME) input event.
* </p>
*
* <p>
* Unlike the <code>onchange</code> event, this event fires when the value
* actually changes and not when the element loses focus. This event also
* reports IME and multi-stroke input more reliably than <code>oninput</code> or
* the various key events across browsers.
* </p>
*
* <p>
* This event is provided by the <code>event-valuechange</code> module.
* </p>
*
* <p>
* <strong>Usage example:</strong>
* </p>
*
* <code><pre>
* YUI().use('event-valuechange', function (Y) {
* Y.one('input').on('valueChange', function (e) {
* // Handle valueChange events on the first input element on the page.
* });
* });
* </pre></code>
*
* @event valueChange
* @param {EventFacade} e Event facade with the following additional
* properties:
*
* <dl>
* <dt>prevVal (String)</dt>
* <dd>
* Previous value before the latest change.
* </dd>
*
* <dt>newVal (String)</dt>
* <dd>
* New value after the latest change.
* </dd>
* </dl>
*
* @for YUI
*/
Y.Event.define('valueChange', {
detach: VC._onUnsubscribe,
on : VC._onSubscribe,
publishConfig: {
emitFacade: true
}
});
Y.ValueChange = VC;
}, '@VERSION@' ,{requires:['event-focus', 'event-synthetic']});
| victorjonsson/cdnjs | ajax/libs/yui/3.4.0pr2/event-valuechange/event-valuechange-debug.js | JavaScript | mit | 10,584 |
//this might was already extended by ES5 shim feature
(function($){
"use strict";
var webshims = window.webshims;
if(webshims.defineProperties){return;}
var defineProperty = 'defineProperty';
var has = Object.prototype.hasOwnProperty;
var descProps = ['configurable', 'enumerable', 'writable'];
var extendUndefined = function(prop){
for(var i = 0; i < 3; i++){
if(prop[descProps[i]] === undefined && (descProps[i] !== 'writable' || prop.value !== undefined)){
prop[descProps[i]] = true;
}
}
};
var extendProps = function(props){
if(props){
for(var i in props){
if(has.call(props, i)){
extendUndefined(props[i]);
}
}
}
};
if(Object.create){
webshims.objectCreate = function(proto, props, opts){
extendProps(props);
var o = Object.create(proto, props);
if(opts){
o.options = $.extend(true, {}, o.options || {}, opts);
opts = o.options;
}
if(o._create && $.isFunction(o._create)){
o._create(opts);
}
return o;
};
}
if(Object[defineProperty]){
webshims[defineProperty] = function(obj, prop, desc){
extendUndefined(desc);
return Object[defineProperty](obj, prop, desc);
};
}
if(Object.defineProperties){
webshims.defineProperties = function(obj, props){
extendProps(props);
return Object.defineProperties(obj, props);
};
}
webshims.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
webshims.getPrototypeOf = Object.getPrototypeOf;
})(window.webshims.$);
//DOM-Extension helper
webshims.register('dom-extend', function($, webshims, window, document, undefined){
"use strict";
var supportHrefNormalized = !('hrefNormalized' in $.support) || $.support.hrefNormalized;
var has = Object.prototype.hasOwnProperty;
webshims.assumeARIA = true;
if($('<input type="email" />').attr('type') == 'text' || $('<form />').attr('novalidate') === "" || ('required' in $('<input />')[0].attributes)){
webshims.error("IE browser modes are busted in IE10+. Make sure to run IE in edge mode (X-UA-Compatible). Please test your HTML/CSS/JS with a real IE version or at least IETester or similar tools. ");
}
if (!webshims.cfg.no$Switch) {
var switch$ = function(){
if (window.jQuery && (!window.$ || window.jQuery == window.$) && !window.jQuery.webshims) {
webshims.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'.");
if (window.$) {
window.$ = webshims.$;
}
window.jQuery = webshims.$;
}
};
switch$();
setTimeout(switch$, 90);
webshims.ready('DOM', switch$);
$(switch$);
webshims.ready('WINDOWLOAD', switch$);
}
//shortcus
var listReg = /\s*,\s*/;
//proxying attribute
var olds = {};
var havePolyfill = {};
var hasPolyfillMethod = {};
var extendedProps = {};
var extendQ = {};
var modifyProps = {};
var oldVal = $.fn.val;
var singleVal = function(elem, name, val, pass, _argless){
return (_argless) ? oldVal.call($(elem)) : oldVal.call($(elem), val);
};
//jquery mobile and jquery ui
if(!$.widget){
(function(){
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
if(!$.widget){
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
}
_cleanData( elems );
};
})();
}
$.fn.val = function(val){
var elem = this[0];
if(arguments.length && val == null){
val = '';
}
if(!arguments.length){
if(!elem || elem.nodeType !== 1){return oldVal.call(this);}
return $.prop(elem, 'value', val, 'val', true);
}
if($.isArray(val)){
return oldVal.apply(this, arguments);
}
var isFunction = $.isFunction(val);
return this.each(function(i){
elem = this;
if(elem.nodeType === 1){
if(isFunction){
var genVal = val.call( elem, i, $.prop(elem, 'value', undefined, 'val', true));
if(genVal == null){
genVal = '';
}
$.prop(elem, 'value', genVal, 'val') ;
} else {
$.prop(elem, 'value', val, 'val');
}
}
});
};
$.fn.onTrigger = function(evt, fn){
return this.on(evt, fn).each(fn);
};
$.fn.onWSOff = function(evt, fn, trigger, evtDel){
if(!evtDel){
evtDel = document;
}
$(evtDel)[trigger ? 'onTrigger' : 'on'](evt, fn);
this.on('remove', function(e){
if(!e.originalEvent){
$(evtDel).off(evt, fn);
}
});
return this;
};
var idCount = 0;
var dataID = '_webshims'+ (Math.round(Math.random() * 1000));
var elementData = function(elem, key, val){
elem = elem.jquery ? elem[0] : elem;
if(!elem){return val || {};}
var data = $.data(elem, dataID);
if(val !== undefined){
if(!data){
data = $.data(elem, dataID, {});
}
if(key){
data[key] = val;
}
}
return key ? data && data[key] : data;
};
[{name: 'getNativeElement', prop: 'nativeElement'}, {name: 'getShadowElement', prop: 'shadowElement'}, {name: 'getShadowFocusElement', prop: 'shadowFocusElement'}].forEach(function(data){
$.fn[data.name] = function(){
var elems = [];
this.each(function(){
var shadowData = elementData(this, 'shadowData');
var elem = shadowData && shadowData[data.prop] || this;
if($.inArray(elem, elems) == -1){
elems.push(elem);
}
});
return this.pushStack(elems);
};
});
function clone(elem, dataAndEvents, uniqueIds){
var cloned = $.clone( elem, dataAndEvents, false );
$(cloned.querySelectorAll('.'+webshims.shadowClass)).detach();
if(uniqueIds){
idCount++;
$(cloned.querySelectorAll('[id]')).prop('id', function(i, id){
return id +idCount;
});
} else {
$(cloned.querySelectorAll('audio[id^="ID-"], video[id^="ID-"], label[id^="ID-"]')).removeAttr('id');
}
return cloned;
}
$.fn.clonePolyfill = function(dataAndEvents, uniqueIds){
dataAndEvents = dataAndEvents || false;
return this
.map(function() {
var cloned = clone( this, dataAndEvents, uniqueIds );
setTimeout(function(){
if($.contains(document.body, cloned)){
$(cloned).updatePolyfill();
}
});
return cloned;
})
;
};
//add support for $('video').trigger('play') in case extendNative is set to false
if(!webshims.cfg.extendNative && !webshims.cfg.noTriggerOverride){
(function(oldTrigger){
$.event.trigger = function(event, data, elem, onlyHandlers){
if(!hasPolyfillMethod[event] || onlyHandlers || !elem || elem.nodeType !== 1){
return oldTrigger.apply(this, arguments);
}
var ret, isOrig, origName;
var origFn = elem[event];
var polyfilledFn = $.prop(elem, event);
var changeFn = polyfilledFn && origFn != polyfilledFn;
if(changeFn){
origName = '__ws'+event;
isOrig = (event in elem) && has.call(elem, event);
elem[event] = polyfilledFn;
elem[origName] = origFn;
}
ret = oldTrigger.apply(this, arguments);
if (changeFn) {
if(isOrig){
elem[event] = origFn;
} else {
delete elem[event];
}
delete elem[origName];
}
return ret;
};
})($.event.trigger);
}
['removeAttr', 'prop', 'attr'].forEach(function(type){
olds[type] = $[type];
$[type] = function(elem, name, value, pass, _argless){
var isVal = (pass == 'val');
var oldMethod = !isVal ? olds[type] : singleVal;
if( !elem || !havePolyfill[name] || elem.nodeType !== 1 || (!isVal && pass && type == 'attr' && $.attrFn[name]) ){
return oldMethod(elem, name, value, pass, _argless);
}
var nodeName = (elem.nodeName || '').toLowerCase();
var desc = extendedProps[nodeName];
var curType = (type == 'attr' && (value === false || value === null)) ? 'removeAttr' : type;
var propMethod;
var oldValMethod;
var ret;
if(!desc){
desc = extendedProps['*'];
}
if(desc){
desc = desc[name];
}
if(desc){
propMethod = desc[curType];
}
if(propMethod){
if(name == 'value'){
oldValMethod = propMethod.isVal;
propMethod.isVal = isVal;
}
if(curType === 'removeAttr'){
return propMethod.value.call(elem);
} else if(value === undefined){
return (propMethod.get) ?
propMethod.get.call(elem) :
propMethod.value
;
} else if(propMethod.set) {
if(type == 'attr' && value === true){
value = name;
}
ret = propMethod.set.call(elem, value);
}
if(name == 'value'){
propMethod.isVal = oldValMethod;
}
} else {
ret = oldMethod(elem, name, value, pass, _argless);
}
if((value !== undefined || curType === 'removeAttr') && modifyProps[nodeName] && modifyProps[nodeName][name]){
var boolValue;
if(curType == 'removeAttr'){
boolValue = false;
} else if(curType == 'prop'){
boolValue = !!(value);
} else {
boolValue = true;
}
modifyProps[nodeName][name].forEach(function(fn){
if(!fn.only || (fn.only = 'prop' && type == 'prop') || (fn.only == 'attr' && type != 'prop')){
fn.call(elem, value, boolValue, (isVal) ? 'val' : curType, type);
}
});
}
return ret;
};
extendQ[type] = function(nodeName, prop, desc){
if(!extendedProps[nodeName]){
extendedProps[nodeName] = {};
}
if(!extendedProps[nodeName][prop]){
extendedProps[nodeName][prop] = {};
}
var oldDesc = extendedProps[nodeName][prop][type];
var getSup = function(propType, descriptor, oDesc){
var origProp;
if(descriptor && descriptor[propType]){
return descriptor[propType];
}
if(oDesc && oDesc[propType]){
return oDesc[propType];
}
if(type == 'prop' && prop == 'value'){
return function(value){
var elem = this;
return (desc.isVal) ?
singleVal(elem, prop, value, false, (arguments.length === 0)) :
olds[type](elem, prop, value)
;
};
}
if(type == 'prop' && propType == 'value' && desc.value.apply){
origProp = '__ws'+prop;
hasPolyfillMethod[prop] = true;
return function(value){
var sup = this[origProp] || olds[type](this, prop);
if(sup && sup.apply){
sup = sup.apply(this, arguments);
}
return sup;
};
}
return function(value){
return olds[type](this, prop, value);
};
};
extendedProps[nodeName][prop][type] = desc;
if(desc.value === undefined){
if(!desc.set){
desc.set = desc.writeable ?
getSup('set', desc, oldDesc) :
(webshims.cfg.useStrict && prop == 'prop') ?
function(){throw(prop +' is readonly on '+ nodeName);} :
function(){webshims.info(prop +' is readonly on '+ nodeName);}
;
}
if(!desc.get){
desc.get = getSup('get', desc, oldDesc);
}
}
['value', 'get', 'set'].forEach(function(descProp){
if(desc[descProp]){
desc['_sup'+descProp] = getSup(descProp, oldDesc);
}
});
};
});
var extendNativeValue = (function(){
var UNKNOWN = webshims.getPrototypeOf(document.createElement('foobar'));
//see also: https://github.com/lojjic/PIE/issues/40 | https://prototype.lighthouseapp.com/projects/8886/tickets/1107-ie8-fatal-crash-when-prototypejs-is-loaded-with-rounded-cornershtc
var isExtendNativeSave = webshims.support.advancedObjectProperties && webshims.support.objectAccessor;
return function(nodeName, prop, desc){
var elem , elemProto;
if( isExtendNativeSave && (elem = document.createElement(nodeName)) && (elemProto = webshims.getPrototypeOf(elem)) && UNKNOWN !== elemProto && ( !elem[prop] || !has.call(elem, prop) ) ){
var sup = elem[prop];
desc._supvalue = function(){
if(sup && sup.apply){
return sup.apply(this, arguments);
}
return sup;
};
elemProto[prop] = desc.value;
} else {
desc._supvalue = function(){
var data = elementData(this, 'propValue');
if(data && data[prop] && data[prop].apply){
return data[prop].apply(this, arguments);
}
return data && data[prop];
};
initProp.extendValue(nodeName, prop, desc.value);
}
desc.value._supvalue = desc._supvalue;
};
})();
var initProp = (function(){
var initProps = {};
webshims.addReady(function(context, contextElem){
var nodeNameCache = {};
var getElementsByName = function(name){
if(!nodeNameCache[name]){
nodeNameCache[name] = $(context.getElementsByTagName(name));
if(contextElem[0] && $.nodeName(contextElem[0], name)){
nodeNameCache[name] = nodeNameCache[name].add(contextElem);
}
}
};
$.each(initProps, function(name, fns){
getElementsByName(name);
if(!fns || !fns.forEach){
webshims.warn('Error: with '+ name +'-property. methods: '+ fns);
return;
}
fns.forEach(function(fn){
nodeNameCache[name].each(fn);
});
});
nodeNameCache = null;
});
var tempCache;
var emptyQ = $([]);
var createNodeNameInit = function(nodeName, fn){
if(!initProps[nodeName]){
initProps[nodeName] = [fn];
} else {
initProps[nodeName].push(fn);
}
if($.isDOMReady){
(tempCache || $( document.getElementsByTagName(nodeName) )).each(fn);
}
};
return {
createTmpCache: function(nodeName){
if($.isDOMReady){
tempCache = tempCache || $( document.getElementsByTagName(nodeName) );
}
return tempCache || emptyQ;
},
flushTmpCache: function(){
tempCache = null;
},
content: function(nodeName, prop){
createNodeNameInit(nodeName, function(){
var val = $.attr(this, prop);
if(val != null){
$.attr(this, prop, val);
}
});
},
createElement: function(nodeName, fn){
createNodeNameInit(nodeName, fn);
},
extendValue: function(nodeName, prop, value){
createNodeNameInit(nodeName, function(){
$(this).each(function(){
var data = elementData(this, 'propValue', {});
data[prop] = this[prop];
this[prop] = value;
});
});
}
};
})();
var createPropDefault = function(descs, removeType){
if(descs.defaultValue === undefined){
descs.defaultValue = '';
}
if(!descs.removeAttr){
descs.removeAttr = {
value: function(){
descs[removeType || 'prop'].set.call(this, descs.defaultValue);
descs.removeAttr._supvalue.call(this);
}
};
}
if(!descs.attr){
descs.attr = {};
}
};
$.extend(webshims, {
xProps: havePolyfill,
getID: (function(){
var ID = new Date().getTime();
return function(elem){
elem = $(elem);
var id = elem.prop('id');
if(!id){
ID++;
id = 'ID-'+ ID;
elem.eq(0).prop('id', id);
}
return id;
};
})(),
domPrefixes: ["ws", "webkit", "moz", "ms", "o"],
prefixed: function (prop, obj){
var i, testProp;
var ret = false;
if(obj[prop]){
ret = prop;
}
if(!ret){
prop = prop.charAt(0).toUpperCase() + prop.slice(1);
for(i = 0; i < webshims.domPrefixes.length; i++){
testProp = webshims.domPrefixes[i]+prop;
if(testProp in obj){
ret = testProp;
break;
}
}
}
return ret;
},
shadowClass: 'wsshadow-'+(Date.now()),
implement: function(elem, type){
var data = elementData(elem, 'implemented') || elementData(elem, 'implemented', {});
if(data[type]){
webshims.warn(type +' already implemented for element #'+elem.id);
return false;
}
data[type] = true;
return !$(elem).hasClass('ws-nopolyfill');
},
extendUNDEFProp: function(obj, props){
$.each(props, function(name, prop){
if( !(name in obj) ){
obj[name] = prop;
}
});
},
getOptions: (function(){
var normalName = /\-([a-z])/g;
var regs = {};
var nameRegs = {};
var regFn = function(f, upper){
return upper.toLowerCase();
};
var nameFn = function(f, dashed){
return dashed.toUpperCase();
};
return function(elem, name, bases, stringAllowed){
if(nameRegs[name]){
name = nameRegs[name];
} else {
nameRegs[name] = name.replace(normalName, nameFn);
name = nameRegs[name];
}
var data = elementData(elem, 'cfg'+name);
var dataName;
var cfg = {};
if(data){
return data;
}
data = $(elem).data();
if(data && typeof data[name] == 'string'){
if(stringAllowed){
return elementData(elem, 'cfg'+name, data[name]);
}
webshims.error('data-'+ name +' attribute has to be a valid JSON, was: '+ data[name]);
}
if(!bases){
bases = [true, {}];
} else if(!Array.isArray(bases)){
bases = [true, {}, bases];
} else {
bases.unshift(true, {});
}
if(data && typeof data[name] == 'object'){
bases.push(data[name]);
}
if(!regs[name]){
regs[name] = new RegExp('^'+ name +'([A-Z])');
}
for(dataName in data){
if(regs[name].test(dataName)){
cfg[dataName.replace(regs[name], regFn)] = data[dataName];
}
}
bases.push(cfg);
return elementData(elem, 'cfg'+name, $.extend.apply($, bases));
};
})(),
//http://www.w3.org/TR/html5/common-dom-interfaces.html#reflect
createPropDefault: createPropDefault,
data: elementData,
moveToFirstEvent: function(elem, eventType, bindType){
var events = ($._data(elem, 'events') || {})[eventType];
var fn;
if(events && events.length > 1){
fn = events.pop();
if(!bindType){
bindType = 'bind';
}
if(bindType == 'bind' && events.delegateCount){
events.splice( events.delegateCount, 0, fn);
} else {
events.unshift( fn );
}
}
elem = null;
},
addShadowDom: (function(){
var resizeTimer;
var lastHeight;
var lastWidth;
var $window = $(window);
var docObserve = {
init: false,
runs: 0,
test: function(){
var height = docObserve.getHeight();
var width = docObserve.getWidth();
if(height != docObserve.height || width != docObserve.width){
docObserve.height = height;
docObserve.width = width;
docObserve.handler({type: 'docresize'});
docObserve.runs++;
if(docObserve.runs < 9){
setTimeout(docObserve.test, 90);
}
} else {
docObserve.runs = 0;
}
},
handler: (function(){
var evt;
var trigger = function(){
$(document).triggerHandler('updateshadowdom', [evt]);
};
var timed = function(){
if(evt && evt.type == 'resize'){
var width = $window.width();
var height = $window.width();
if(height == lastHeight && width == lastWidth){
return;
}
lastHeight = height;
lastWidth = width;
}
if(evt && evt.type != 'docresize'){
docObserve.height = docObserve.getHeight();
docObserve.width = docObserve.getWidth();
}
if(window.requestAnimationFrame){
requestAnimationFrame(trigger);
} else {
setTimeout(trigger, 0);
}
};
return function(e){
clearTimeout(resizeTimer);
evt = e;
resizeTimer = setTimeout(timed, (e.type == 'resize' && !window.requestAnimationFrame) ? 50 : 9);
};
})(),
_create: function(){
$.each({ Height: "getHeight", Width: "getWidth" }, function(name, type){
var body = document.body;
var doc = document.documentElement;
docObserve[type] = function (){
return Math.max(
body[ "scroll" + name ], doc[ "scroll" + name ],
body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
};
});
},
start: function(){
if(!this.init && document.body){
this.init = true;
this._create();
this.height = docObserve.getHeight();
this.width = docObserve.getWidth();
setInterval(this.test, 999);
$(this.test);
if($.support.boxSizing == null){
$(function(){
if($.support.boxSizing){
docObserve.handler({type: 'boxsizing'});
}
});
}
webshims.ready('WINDOWLOAD', this.test);
$(document).on('updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel playerdimensionchange', this.handler);
$(window).on('resize', this.handler);
}
}
};
webshims.docObserve = function(){
webshims.ready('DOM', function(){
docObserve.start();
});
};
return function(nativeElem, shadowElem, opts){
if(nativeElem && shadowElem){
opts = opts || {};
if(nativeElem.jquery){
nativeElem = nativeElem[0];
}
if(shadowElem.jquery){
shadowElem = shadowElem[0];
}
var nativeData = $.data(nativeElem, dataID) || $.data(nativeElem, dataID, {});
var shadowData = $.data(shadowElem, dataID) || $.data(shadowElem, dataID, {});
var shadowFocusElementData = {};
if(!opts.shadowFocusElement){
opts.shadowFocusElement = shadowElem;
} else if(opts.shadowFocusElement){
if(opts.shadowFocusElement.jquery){
opts.shadowFocusElement = opts.shadowFocusElement[0];
}
shadowFocusElementData = $.data(opts.shadowFocusElement, dataID) || $.data(opts.shadowFocusElement, dataID, shadowFocusElementData);
}
$(nativeElem).on('remove', function(e){
if (!e.originalEvent) {
setTimeout(function(){
$(shadowElem).remove();
}, 4);
}
});
nativeData.hasShadow = shadowElem;
shadowFocusElementData.nativeElement = shadowData.nativeElement = nativeElem;
shadowFocusElementData.shadowData = shadowData.shadowData = nativeData.shadowData = {
nativeElement: nativeElem,
shadowElement: shadowElem,
shadowFocusElement: opts.shadowFocusElement
};
if(opts.shadowChilds){
opts.shadowChilds.each(function(){
elementData(this, 'shadowData', shadowData.shadowData);
});
}
if(opts.data){
shadowFocusElementData.shadowData.data = shadowData.shadowData.data = nativeData.shadowData.data = opts.data;
}
opts = null;
}
webshims.docObserve();
};
})(),
propTypes: {
standard: function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
descs.attr.set.call(this, ''+val);
},
get: function(){
return descs.attr.get.call(this) || descs.defaultValue;
}
};
},
"boolean": function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
if(val){
descs.attr.set.call(this, "");
} else {
descs.removeAttr.value.call(this);
}
},
get: function(){
return descs.attr.get.call(this) != null;
}
};
},
"src": (function(){
var anchor = document.createElement('a');
anchor.style.display = "none";
return function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
descs.attr.set.call(this, val);
},
get: function(){
var href = this.getAttribute(name);
var ret;
if(href == null){return '';}
anchor.setAttribute('href', href+'' );
if(!supportHrefNormalized){
try {
$(anchor).insertAfter(this);
ret = anchor.getAttribute('href', 4);
} catch(er){
ret = anchor.getAttribute('href', 4);
}
$(anchor).detach();
}
return ret || anchor.href;
}
};
};
})(),
enumarated: function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
descs.attr.set.call(this, val);
},
get: function(){
var val = (descs.attr.get.call(this) || '').toLowerCase();
if(!val || descs.limitedTo.indexOf(val) == -1){
val = descs.defaultValue;
}
return val;
}
};
}
// ,unsignedLong: $.noop
// ,"doubble": $.noop
// ,"long": $.noop
// ,tokenlist: $.noop
// ,settableTokenlist: $.noop
},
reflectProperties: function(nodeNames, props){
if(typeof props == 'string'){
props = props.split(listReg);
}
props.forEach(function(prop){
webshims.defineNodeNamesProperty(nodeNames, prop, {
prop: {
set: function(val){
$.attr(this, prop, val);
},
get: function(){
return $.attr(this, prop) || '';
}
}
});
});
},
defineNodeNameProperty: function(nodeName, prop, descs){
havePolyfill[prop] = true;
if(descs.reflect){
if(descs.propType && !webshims.propTypes[descs.propType]){
webshims.error('could not finde propType '+ descs.propType);
} else {
webshims.propTypes[descs.propType || 'standard'](descs, prop);
}
}
['prop', 'attr', 'removeAttr'].forEach(function(type){
var desc = descs[type];
if(desc){
if(type === 'prop'){
desc = $.extend({writeable: true}, desc);
} else {
desc = $.extend({}, desc, {writeable: true});
}
extendQ[type](nodeName, prop, desc);
if(nodeName != '*' && webshims.cfg.extendNative && type == 'prop' && desc.value && $.isFunction(desc.value)){
extendNativeValue(nodeName, prop, desc);
}
descs[type] = desc;
}
});
if(descs.initAttr){
initProp.content(nodeName, prop);
}
return descs;
},
defineNodeNameProperties: function(name, descs, propType, _noTmpCache){
var olddesc;
for(var prop in descs){
if(!_noTmpCache && descs[prop].initAttr){
initProp.createTmpCache(name);
}
if(propType){
if(descs[prop][propType]){
//webshims.log('override: '+ name +'['+prop +'] for '+ propType);
} else {
descs[prop][propType] = {};
['value', 'set', 'get'].forEach(function(copyProp){
if(copyProp in descs[prop]){
descs[prop][propType][copyProp] = descs[prop][copyProp];
delete descs[prop][copyProp];
}
});
}
}
descs[prop] = webshims.defineNodeNameProperty(name, prop, descs[prop]);
}
if(!_noTmpCache){
initProp.flushTmpCache();
}
return descs;
},
createElement: function(nodeName, create, descs){
var ret;
if($.isFunction(create)){
create = {
after: create
};
}
initProp.createTmpCache(nodeName);
if(create.before){
initProp.createElement(nodeName, create.before);
}
if(descs){
ret = webshims.defineNodeNameProperties(nodeName, descs, false, true);
}
if(create.after){
initProp.createElement(nodeName, create.after);
}
initProp.flushTmpCache();
return ret;
},
onNodeNamesPropertyModify: function(nodeNames, props, desc, only){
if(typeof nodeNames == 'string'){
nodeNames = nodeNames.split(listReg);
}
if($.isFunction(desc)){
desc = {set: desc};
}
nodeNames.forEach(function(name){
if(!modifyProps[name]){
modifyProps[name] = {};
}
if(typeof props == 'string'){
props = props.split(listReg);
}
if(desc.initAttr){
initProp.createTmpCache(name);
}
props.forEach(function(prop){
if(!modifyProps[name][prop]){
modifyProps[name][prop] = [];
havePolyfill[prop] = true;
}
if(desc.set){
if(only){
desc.set.only = only;
}
modifyProps[name][prop].push(desc.set);
}
if(desc.initAttr){
initProp.content(name, prop);
}
});
initProp.flushTmpCache();
});
},
defineNodeNamesBooleanProperty: function(elementNames, prop, descs){
if(!descs){
descs = {};
}
if($.isFunction(descs)){
descs.set = descs;
}
webshims.defineNodeNamesProperty(elementNames, prop, {
attr: {
set: function(val){
if(descs.useContentAttribute){
webshims.contentAttr(this, prop, val);
} else {
this.setAttribute(prop, val);
}
if(descs.set){
descs.set.call(this, true);
}
},
get: function(){
var ret = (descs.useContentAttribute) ? webshims.contentAttr(this, prop) : this.getAttribute(prop);
return (ret == null) ? undefined : prop;
}
},
removeAttr: {
value: function(){
this.removeAttribute(prop);
if(descs.set){
descs.set.call(this, false);
}
}
},
reflect: true,
propType: 'boolean',
initAttr: descs.initAttr || false
});
},
contentAttr: function(elem, name, val){
if(!elem.nodeName){return;}
var attr;
if(val === undefined){
attr = (elem.attributes[name] || {});
val = attr.specified ? attr.value : null;
return (val == null) ? undefined : val;
}
if(typeof val == 'boolean'){
if(!val){
elem.removeAttribute(name);
} else {
elem.setAttribute(name, name);
}
} else {
elem.setAttribute(name, val);
}
},
activeLang: (function(){
var curLang = [];
var langDatas = [];
var loading = {};
var load = function(src, obj, loadingLang){
obj._isLoading = true;
if(loading[src]){
loading[src].push(obj);
} else {
loading[src] = [obj];
webshims.loader.loadScript(src, function(){
if(loadingLang == curLang.join()){
$.each(loading[src], function(i, obj){
select(obj);
});
}
delete loading[src];
});
}
};
var select = function(obj){
var oldLang = obj.__active;
var selectLang = function(i, lang){
obj._isLoading = false;
if(obj[lang] || obj.availableLangs.indexOf(lang) != -1){
if(obj[lang]){
obj.__active = obj[lang];
obj.__activeName = lang;
} else {
load(obj.langSrc+lang, obj, curLang.join());
}
return false;
}
};
$.each(curLang, selectLang);
if(!obj.__active){
obj.__active = obj[''];
obj.__activeName = '';
}
if(oldLang != obj.__active){
$(obj).trigger('change');
}
};
return function(lang){
var shortLang;
if(typeof lang == 'string'){
if(curLang[0] != lang){
curLang = [lang];
shortLang = curLang[0].split('-')[0];
if(shortLang && shortLang != lang){
curLang.push(shortLang);
}
langDatas.forEach(select);
}
} else if(typeof lang == 'object'){
if(!lang.__active){
langDatas.push(lang);
select(lang);
}
return lang.__active;
}
return curLang[0];
};
})()
});
$.each({
defineNodeNamesProperty: 'defineNodeNameProperty',
defineNodeNamesProperties: 'defineNodeNameProperties',
createElements: 'createElement'
}, function(name, baseMethod){
webshims[name] = function(names, a, b, c){
if(typeof names == 'string'){
names = names.split(listReg);
}
var retDesc = {};
names.forEach(function(nodeName){
retDesc[nodeName] = webshims[baseMethod](nodeName, a, b, c);
});
return retDesc;
};
});
webshims.isReady('webshimLocalization', true);
//html5a11y + hidden attribute
(function(){
if(('content' in document.createElement('template'))){return;}
$(function(){
var main = $('main').attr({role: 'main'});
if(main.length > 1){
webshims.error('only one main element allowed in document');
} else if(main.is('article *, section *')) {
webshims.error('main not allowed inside of article/section elements');
}
});
if(('hidden' in document.createElement('a'))){
return;
}
webshims.defineNodeNamesBooleanProperty(['*'], 'hidden');
var elemMappings = {
article: "article",
aside: "complementary",
section: "region",
nav: "navigation",
address: "contentinfo"
};
var addRole = function(elem, role){
var hasRole = elem.getAttribute('role');
if (!hasRole) {
elem.setAttribute('role', role);
}
};
$.webshims.addReady(function(context, contextElem){
$.each(elemMappings, function(name, role){
var elems = $(name, context).add(contextElem.filter(name));
for (var i = 0, len = elems.length; i < len; i++) {
addRole(elems[i], role);
}
});
if (context === document) {
var header = document.getElementsByTagName('header')[0];
var footers = document.getElementsByTagName('footer');
var footerLen = footers.length;
if (header && !$(header).closest('section, article')[0]) {
addRole(header, 'banner');
}
if (!footerLen) {
return;
}
var footer = footers[footerLen - 1];
if (!$(footer).closest('section, article')[0]) {
addRole(footer, 'contentinfo');
}
}
});
})();
});
;webshims.register('form-message', function($, webshims, window, document, undefined, options){
"use strict";
if(options.lazyCustomMessages){
options.customMessages = true;
}
var validityMessages = webshims.validityMessages;
var implementProperties = options.customMessages ? ['customValidationMessage'] : [];
validityMessages.en = $.extend(true, {
typeMismatch: {
defaultMessage: 'Please enter a valid value.',
email: 'Please enter an email address.',
url: 'Please enter a URL.'
},
badInput: {
defaultMessage: 'Please enter a valid value.',
number: 'Please enter a number.',
date: 'Please enter a date.',
time: 'Please enter a time.',
range: 'Invalid input.',
month: 'Please enter a valid value.',
"datetime-local": 'Please enter a datetime.'
},
rangeUnderflow: {
defaultMessage: 'Value must be greater than or equal to {%min}.'
},
rangeOverflow: {
defaultMessage: 'Value must be less than or equal to {%max}.'
},
stepMismatch: 'Invalid input.',
tooLong: 'Please enter at most {%maxlength} character(s). You entered {%valueLen}.',
tooShort: 'Please enter at least {%minlength} character(s). You entered {%valueLen}.',
patternMismatch: 'Invalid input. {%title}',
valueMissing: {
defaultMessage: 'Please fill out this field.',
checkbox: 'Please check this box if you want to proceed.'
}
}, (validityMessages.en || validityMessages['en-US'] || {}));
if(typeof validityMessages['en'].valueMissing == 'object'){
['select', 'radio'].forEach(function(type){
validityMessages.en.valueMissing[type] = validityMessages.en.valueMissing[type] || 'Please select an option.';
});
}
if(typeof validityMessages.en.rangeUnderflow == 'object'){
['date', 'time', 'datetime-local', 'month'].forEach(function(type){
validityMessages.en.rangeUnderflow[type] = validityMessages.en.rangeUnderflow[type] || 'Value must be at or after {%min}.';
});
}
if(typeof validityMessages.en.rangeOverflow == 'object'){
['date', 'time', 'datetime-local', 'month'].forEach(function(type){
validityMessages.en.rangeOverflow[type] = validityMessages.en.rangeOverflow[type] || 'Value must be at or before {%max}.';
});
}
if(!validityMessages['en-US']){
validityMessages['en-US'] = $.extend(true, {}, validityMessages.en);
}
if(!validityMessages['en-GB']){
validityMessages['en-GB'] = $.extend(true, {}, validityMessages.en);
}
if(!validityMessages['en-AU']){
validityMessages['en-AU'] = $.extend(true, {}, validityMessages.en);
}
validityMessages[''] = validityMessages[''] || validityMessages['en-US'];
validityMessages.de = $.extend(true, {
typeMismatch: {
defaultMessage: '{%value} ist in diesem Feld nicht zulässig.',
email: '{%value} ist keine gültige E-Mail-Adresse.',
url: '{%value} ist kein(e) gültige(r) Webadresse/Pfad.'
},
badInput: {
defaultMessage: 'Geben Sie einen zulässigen Wert ein.',
number: 'Geben Sie eine Nummer ein.',
date: 'Geben Sie ein Datum ein.',
time: 'Geben Sie eine Uhrzeit ein.',
month: 'Geben Sie einen Monat mit Jahr ein.',
range: 'Geben Sie eine Nummer.',
"datetime-local": 'Geben Sie ein Datum mit Uhrzeit ein.'
},
rangeUnderflow: {
defaultMessage: '{%value} ist zu niedrig. {%min} ist der unterste Wert, den Sie benutzen können.'
},
rangeOverflow: {
defaultMessage: '{%value} ist zu hoch. {%max} ist der oberste Wert, den Sie benutzen können.'
},
stepMismatch: 'Der Wert {%value} ist in diesem Feld nicht zulässig. Hier sind nur bestimmte Werte zulässig. {%title}',
tooLong: 'Der eingegebene Text ist zu lang! Sie haben {%valueLen} Zeichen eingegeben, dabei sind {%maxlength} das Maximum.',
tooShort: 'Der eingegebene Text ist zu kurz! Sie haben {%valueLen} Zeichen eingegeben, dabei sind {%minlength} das Minimum.',
patternMismatch: '{%value} hat für dieses Eingabefeld ein falsches Format. {%title}',
valueMissing: {
defaultMessage: 'Bitte geben Sie einen Wert ein.',
checkbox: 'Bitte aktivieren Sie das Kästchen.'
}
}, (validityMessages.de || {}));
if(typeof validityMessages.de.valueMissing == 'object'){
['select', 'radio'].forEach(function(type){
validityMessages.de.valueMissing[type] = validityMessages.de.valueMissing[type] || 'Bitte wählen Sie eine Option aus.';
});
}
if(typeof validityMessages.de.rangeUnderflow == 'object'){
['date', 'time', 'datetime-local', 'month'].forEach(function(type){
validityMessages.de.rangeUnderflow[type] = validityMessages.de.rangeUnderflow[type] || '{%value} ist zu früh. {%min} ist die früheste Zeit, die Sie benutzen können.';
});
}
if(typeof validityMessages.de.rangeOverflow == 'object'){
['date', 'time', 'datetime-local', 'month'].forEach(function(type){
validityMessages.de.rangeOverflow[type] = validityMessages.de.rangeOverflow[type] || '{%value} ist zu spät. {%max} ist die späteste Zeit, die Sie benutzen können.';
});
}
var currentValidationMessage = validityMessages[''];
var getMessageFromObj = function(message, elem){
if(message && typeof message !== 'string'){
message = message[ $.prop(elem, 'type') ] || message[ (elem.nodeName || '').toLowerCase() ] || message[ 'defaultMessage' ];
}
return message || '';
};
var lReg = /</g;
var gReg = />/g;
var valueVals = {
value: 1,
min: 1,
max: 1
};
var toLocale = (function(){
var monthFormatter;
var transforms = {
number: function(val){
var num = val * 1;
if(num.toLocaleString && !isNaN(num)){
val = num.toLocaleString() || val;
}
return val;
}
};
var _toLocale = function(val, elem, attr){
var type, widget;
if(valueVals[attr]){
type = $.prop(elem, 'type');
widget = $(elem).getShadowElement().data('wsWidget'+ type );
if(widget && widget.formatValue){
val = widget.formatValue(val, false);
} else if(transforms[type]){
val = transforms[type](val);
}
}
return val;
};
[{n: 'date', f: 'toLocaleDateString'}, {n: 'time', f: 'toLocaleTimeString'}, {n: 'datetime-local', f: 'toLocaleString'}].forEach(function(desc){
transforms[desc.n] = function(val){
var date = new Date(val);
if(date && date[desc.f]){
val = date[desc.f]() || val;
}
return val;
};
});
if(window.Intl && Intl.DateTimeFormat){
monthFormatter = new Intl.DateTimeFormat(navigator.browserLanguage || navigator.language, {year: "numeric", month: "2-digit"}).format(new Date());
if(monthFormatter && monthFormatter.format){
transforms.month = function(val){
var date = new Date(val);
if(date){
val = monthFormatter.format(date) || val;
}
return val;
};
}
}
webshims.format = {};
['date', 'number', 'month', 'time', 'datetime-local'].forEach(function(name){
webshims.format[name] = function(val, opts){
if(opts && opts.nodeType){
return _toLocale(val, opts, name);
}
if(name == 'number' && opts && opts.toFixed ){
val = (val * 1);
if(!opts.fixOnlyFloat || val % 1){
val = val.toFixed(opts.toFixed);
}
}
if(webshims._format && webshims._format[name]){
return webshims._format[name](val, opts);
}
return transforms[name](val);
};
});
return _toLocale;
})();
webshims.replaceValidationplaceholder = function(elem, message, name){
var val = $.prop(elem, 'title');
if(message){
if(name == 'patternMismatch' && !val){
webshims.error('no title for patternMismatch provided. Always add a title attribute.');
}
if(val){
val = '<span class="ws-titlevalue">'+ val.replace(lReg, '<').replace(gReg, '>') +'</span>';
}
if(message.indexOf('{%title}') != -1){
message = message.replace('{%title}', val);
} else if(val) {
message = message+' '+val;
}
}
if(message && message.indexOf('{%') != -1){
['value', 'min', 'max', 'maxlength', 'minlength', 'label'].forEach(function(attr){
if(message.indexOf('{%'+attr) === -1){return;}
var val = ((attr == 'label') ? $.trim($('label[for="'+ elem.id +'"]', elem.form).text()).replace(/\*$|:$/, '') : $.prop(elem, attr) || $.attr(elem, attr) || '') || '';
val = ''+val;
val = toLocale(val, elem, attr);
message = message.replace('{%'+ attr +'}', val.replace(lReg, '<').replace(gReg, '>'));
if('value' == attr){
message = message.replace('{%valueLen}', val.length);
}
});
}
return message;
};
webshims.createValidationMessage = function(elem, name){
var message = getMessageFromObj(currentValidationMessage[name], elem);
if(!message && name == 'badInput'){
message = getMessageFromObj(currentValidationMessage.typeMismatch, elem);
}
if(!message && name == 'typeMismatch'){
message = getMessageFromObj(currentValidationMessage.badInput, elem);
}
if(!message){
message = getMessageFromObj(validityMessages[''][name], elem) || $.prop(elem, 'validationMessage');
if(name != 'customError'){
webshims.info('could not find errormessage for: '+ name +' / '+ $.prop(elem, 'type') +'. in language: '+webshims.activeLang());
}
}
message = webshims.replaceValidationplaceholder(elem, message, name);
return message || '';
};
if(!webshims.support.formvalidation || webshims.bugs.bustedValidity){
implementProperties.push('validationMessage');
}
currentValidationMessage = webshims.activeLang(validityMessages);
$(validityMessages).on('change', function(e, data){
currentValidationMessage = validityMessages.__active;
});
implementProperties.forEach(function(messageProp){
webshims.defineNodeNamesProperty(['fieldset', 'output', 'button'], messageProp, {
prop: {
value: '',
writeable: false
}
});
['input', 'select', 'textarea'].forEach(function(nodeName){
var desc = webshims.defineNodeNameProperty(nodeName, messageProp, {
prop: {
get: function(){
var elem = this;
var message = '';
if(!$.prop(elem, 'willValidate')){
return message;
}
var validity = $.prop(elem, 'validity') || {valid: 1};
if(validity.valid){return message;}
message = webshims.getContentValidationMessage(elem, validity);
if(message){return message;}
if(validity.customError && elem.nodeName){
message = (webshims.support.formvalidation && !webshims.bugs.bustedValidity && desc.prop._supget) ? desc.prop._supget.call(elem) : webshims.data(elem, 'customvalidationMessage');
if(message){return message;}
}
$.each(validity, function(name, prop){
if(name == 'valid' || !prop){return;}
message = webshims.createValidationMessage(elem, name);
if(message){
return false;
}
});
return message || '';
},
writeable: false
}
});
});
});
});
| jamzgoodguy/cdnjs | ajax/libs/webshim/1.15.2/dev/shims/combos/4.js | JavaScript | mit | 43,315 |
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
return /^debug_/i.test(key);
}).reduce(function (obj, key) {
// camel-case
var prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
// coerce string value into JS value
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
else if (val === 'null') val = null;
else val = Number(val);
obj[prop] = val;
return obj;
}, {});
/**
* The file descriptor to write the `debug()` calls to.
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
*
* $ DEBUG_FD=3 node script.js 3>debug.log
*/
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
if (1 !== fd && 2 !== fd) {
util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()
}
var stream = 1 === fd ? process.stdout :
2 === fd ? process.stderr :
createWritableStdioStream(fd);
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts
? Boolean(exports.inspectOpts.colors)
: tty.isatty(fd);
}
/**
* Map %o to `util.inspect()`, all on a single line.
*/
exports.formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n').map(function(str) {
return str.trim()
}).join(' ');
};
/**
* Map %o to `util.inspect()`, allowing multiple lines if needed.
*/
exports.formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
var name = this.namespace;
var useColors = this.useColors;
if (useColors) {
var c = this.color;
var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
}
/**
* Invokes `util.format()` with the specified arguments and writes to `stream`.
*/
function log() {
return stream.write(util.format.apply(util, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (null == namespaces) {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
} else {
process.env.DEBUG = namespaces;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Copied from `node/src/node.js`.
*
* XXX: It's lame that node doesn't expose this API out-of-the-box. It also
* relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
*/
function createWritableStdioStream (fd) {
var stream;
var tty_wrap = process.binding('tty_wrap');
// Note stream._type is used for test-module-load-list.js
switch (tty_wrap.guessHandleType(fd)) {
case 'TTY':
stream = new tty.WriteStream(fd);
stream._type = 'tty';
// Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
case 'FILE':
var fs = require('fs');
stream = new fs.SyncWriteStream(fd, { autoClose: false });
stream._type = 'fs';
break;
case 'PIPE':
case 'TCP':
var net = require('net');
stream = new net.Socket({
fd: fd,
readable: false,
writable: true
});
// FIXME Should probably have an option in net.Socket to create a
// stream from an existing fd which is writable only. But for now
// we'll just add this hack and set the `readable` member to false.
// Test: ./node test/fixtures/echo.js < /etc/passwd
stream.readable = false;
stream.read = null;
stream._type = 'pipe';
// FIXME Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
default:
// Probably an error on in uv_guess_handle()
throw new Error('Implement me. Unknown stream file type!');
}
// For supporting legacy API we put the FD here.
stream.fd = fd;
stream._isStdio = true;
return stream;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init (debug) {
debug.inspectOpts = {};
var keys = Object.keys(exports.inspectOpts);
for (var i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
/**
* Enable namespaces listed in `process.env.DEBUG` initially.
*/
exports.enable(load());
| vishveshcoder/Login | node_modules/debug/src/node.js | JavaScript | mit | 6,015 |
package jwt
import (
"encoding/base64"
"encoding/json"
"strings"
"time"
)
// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time).
// You can override it to use another time value. This is useful for testing or if your
// server uses a different time zone than your tokens.
var TimeFunc = time.Now
// Parse methods use this callback function to supply
// the key for verification. The function receives the parsed,
// but unverified Token. This allows you to use properties in the
// Header of the token (such as `kid`) to identify which key to use.
type Keyfunc func(*Token) (interface{}, error)
// A JWT Token. Different fields will be used depending on whether you're
// creating or parsing/verifying a token.
type Token struct {
Raw string // The raw token. Populated when you Parse a token
Method SigningMethod // The signing method used or to be used
Header map[string]interface{} // The first segment of the token
Claims Claims // The second segment of the token
Signature string // The third segment of the token. Populated when you Parse a token
Valid bool // Is the token valid? Populated when you Parse/Verify a token
}
// Create a new Token. Takes a signing method
func New(method SigningMethod) *Token {
return NewWithClaims(method, MapClaims{})
}
func NewWithClaims(method SigningMethod, claims Claims) *Token {
return &Token{
Header: map[string]interface{}{
"typ": "JWT",
"alg": method.Alg(),
},
Claims: claims,
Method: method,
}
}
// Get the complete, signed token
func (t *Token) SignedString(key interface{}) (string, error) {
var sig, sstr string
var err error
if sstr, err = t.SigningString(); err != nil {
return "", err
}
if sig, err = t.Method.Sign(sstr, key); err != nil {
return "", err
}
return strings.Join([]string{sstr, sig}, "."), nil
}
// Generate the signing string. This is the
// most expensive part of the whole deal. Unless you
// need this for something special, just go straight for
// the SignedString.
func (t *Token) SigningString() (string, error) {
var err error
parts := make([]string, 2)
for i, _ := range parts {
var jsonValue []byte
if i == 0 {
if jsonValue, err = json.Marshal(t.Header); err != nil {
return "", err
}
} else {
if jsonValue, err = json.Marshal(t.Claims); err != nil {
return "", err
}
}
parts[i] = EncodeSegment(jsonValue)
}
return strings.Join(parts, "."), nil
}
// Parse, validate, and return a token.
// keyFunc will receive the parsed token and should return the key for validating.
// If everything is kosher, err will be nil
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
return new(Parser).Parse(tokenString, keyFunc)
}
func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
return new(Parser).ParseWithClaims(tokenString, claims, keyFunc)
}
// Encode JWT specific base64url encoding with padding stripped
func EncodeSegment(seg []byte) string {
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
}
// Decode JWT specific base64url encoding with padding stripped
func DecodeSegment(seg string) ([]byte, error) {
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(seg)
}
| geek1011/gitea | vendor/github.com/dgrijalva/jwt-go/token.go | GO | mit | 3,409 |
var postboxes;
(function($) {
postboxes = {
add_postbox_toggles : function(page, args) {
var self = this;
self.init(page, args);
$('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
if ( 'dashboard_browser_nag' == id )
return;
p.toggleClass('closed');
if ( page != 'press-this' )
self.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
self.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
self.pbhide(id);
}
});
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
});
$('.postbox a.dismiss').bind('click.postboxes', function(e) {
var hide_id = $(this).parents('.postbox').attr('id') + '-hide';
$( '#' + hide_id ).prop('checked', false).triggerHandler('click');
return false;
});
$('.hide-postbox-tog').bind('click.postboxes', function() {
var box = $(this).val();
if ( $(this).prop('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
self.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
self.pbhide( box );
}
self.save_state(page);
self._mark_area();
});
$('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){
var n = parseInt($(this).val(), 10);
if ( n ) {
self._pb_edit(n);
self.save_order(page);
}
});
},
init : function(page, args) {
var isMobile = $(document.body).hasClass('mobile');
$.extend( this, args || {} );
$('#wpbody-content').css('overflow','hidden');
$('.meta-box-sortables').sortable({
placeholder: 'sortable-placeholder',
connectWith: '.meta-box-sortables',
items: '.postbox',
handle: '.hndle',
cursor: 'move',
delay: ( isMobile ? 200 : 0 ),
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function(e,ui) {
if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) {
$(this).sortable('cancel');
return;
}
postboxes.save_order(page);
},
receive: function(e,ui) {
if ( 'dashboard_browser_nag' == ui.item[0].id )
$(ui.sender).sortable('cancel');
postboxes._mark_area();
}
});
if ( isMobile ) {
$(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); });
this._pb_change();
}
this._mark_area();
},
save_state : function(page) {
var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','),
hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
closed: closed,
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: page
});
},
save_order : function(page) {
var postVars, page_columns = $('.columns-prefs input:checked').val() || 0;
postVars = {
action: 'meta-box-order',
_ajax_nonce: $('#meta-box-order-nonce').val(),
page_columns: page_columns,
page: page
}
$('.meta-box-sortables').each( function() {
postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(',');
} );
$.post( ajaxurl, postVars );
},
_mark_area : function() {
var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables');
$('#dashboard-widgets .meta-box-sortables:visible').each(function(n, el){
var t = $(this);
if ( visible == 1 || t.children('.postbox:visible').length )
t.removeClass('empty-container');
else
t.addClass('empty-container');
});
if ( side.length ) {
if ( side.children('.postbox:visible').length )
side.removeClass('empty-container');
else if ( $('#postbox-container-1').css('width') == '280px' )
side.addClass('empty-container');
}
},
_pb_edit : function(n) {
var el = $('.metabox-holder').get(0);
el.className = el.className.replace(/columns-\d+/, 'columns-' + n);
},
_pb_change : function() {
var check = $( 'label.columns-prefs-1 input[type="radio"]' );
switch ( window.orientation ) {
case 90:
case -90:
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
break;
case 0:
case 180:
if ( $('#poststuff').length ) {
this._pb_edit(1);
} else {
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
}
break;
}
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
| CodeForKids/websitesByKids | subdomains/ibro/wp-admin/js/postbox.js | JavaScript | mit | 4,784 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/Main/Regular/Latin1Supplement.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({MathJax_Main:{160:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],168:[[3,1,-4],[4,2,-4],[4,2,-6],[5,2,-6],[6,2,-7],[7,3,-9],[8,3,-11],[10,3,-14],[12,4,-16],[14,4,-19],[16,5,-22],[19,6,-26],[23,7,-31],[27,8,-37]],172:[[5,3,0],[6,3,0],[6,4,0],[8,4,0],[9,4,-1],[11,5,-2],[12,6,-1],[15,7,-2],[17,8,-2],[21,10,-3],[24,11,-4],[29,13,-4],[34,16,-5],[41,18,-6]],175:[[3,1,-3],[4,1,-5],[5,1,-6],[6,1,-6],[6,1,-7],[8,1,-10],[9,1,-11],[10,2,-13],[12,3,-15],[15,2,-18],[17,2,-22],[20,3,-26],[24,3,-30],[29,4,-36]],176:[[3,2,-3],[3,2,-4],[4,2,-6],[5,2,-6],[5,3,-6],[6,3,-9],[7,4,-10],[9,5,-13],[10,6,-15],[12,7,-17],[14,8,-22],[17,8,-25],[20,10,-30],[24,12,-36]],177:[[5,5,0],[6,6,0],[8,8,0],[9,8,0],[10,9,0],[12,12,0],[15,14,0],[17,17,0],[20,20,0],[24,23,0],[29,27,0],[34,31,0],[40,37,0],[48,45,0]],180:[[3,2,-3],[4,2,-4],[4,3,-5],[5,3,-5],[6,3,-6],[7,4,-8],[8,5,-9],[10,6,-12],[11,7,-14],[13,7,-17],[16,9,-19],[19,10,-23],[22,12,-28],[26,13,-34]],215:[[5,4,0],[6,5,0],[7,6,0],[8,6,0],[9,7,0],[11,9,0],[13,10,0],[15,12,0],[18,14,0],[21,17,0],[25,20,0],[30,23,0],[36,27,-1],[42,33,-1]],247:[[5,4,0],[6,6,0],[8,7,0],[9,7,0],[10,8,0],[12,10,0],[15,12,0],[17,15,1],[20,18,1],[24,19,1],[29,23,1],[34,27,2],[40,32,2],[48,39,2]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Main/Regular"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/Latin1Supplement.js");
| sufuf3/cdnjs | ajax/libs/mathjax/2.7.5/fonts/HTML-CSS/TeX/png/Main/Regular/Latin1Supplement.js | JavaScript | mit | 1,864 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/Math/Italic/Main.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({"MathJax_Math-italic":{32:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],47:[[5,6,1],[6,8,2],[7,8,2],[8,10,2],[9,12,3],[11,14,3],[13,18,4],[15,21,5],[18,25,6],[21,31,7],[25,36,8],[30,45,10],[36,53,12],[42,61,14]],65:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[17,16,0],[21,19,0],[24,24,0],[29,28,0],[34,34,1],[41,41,1],[48,47,1]],66:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,19,0],[25,23,0],[30,27,0],[36,33,0],[42,39,0],[50,45,0]],67:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,20,1],[25,25,1],[30,29,1],[36,35,1],[42,41,1],[50,48,1]],68:[[6,5,0],[7,6,0],[8,6,0],[10,8,0],[12,10,0],[14,11,0],[16,14,0],[19,16,0],[23,19,0],[27,23,0],[32,27,0],[38,33,0],[45,39,0],[53,45,0]],69:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[22,19,0],[26,23,0],[30,27,0],[36,33,0],[43,39,0],[51,46,0]],70:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,19,0],[25,23,0],[30,27,0],[35,33,0],[42,39,0],[50,45,-1]],71:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,20,1],[25,25,1],[30,29,1],[36,35,1],[42,41,1],[50,48,1]],72:[[7,5,0],[8,7,0],[9,7,0],[11,9,0],[13,10,0],[15,12,0],[18,15,0],[21,17,0],[25,20,0],[30,24,0],[35,28,0],[42,34,0],[50,40,0],[59,46,0]],73:[[4,5,0],[5,6,0],[5,6,0],[6,8,0],[7,9,0],[9,11,0],[10,14,0],[12,16,0],[14,19,0],[17,23,0],[20,27,0],[24,33,0],[28,39,0],[34,45,0]],74:[[5,5,0],[6,7,0],[7,6,0],[8,9,0],[9,10,0],[11,12,0],[13,15,0],[15,17,0],[18,21,1],[21,25,1],[25,29,1],[30,35,1],[35,41,1],[42,47,1]],75:[[7,5,0],[8,6,0],[9,6,0],[11,8,0],[13,10,0],[15,11,0],[18,14,0],[21,16,0],[25,19,0],[30,23,0],[35,27,0],[42,33,0],[50,39,0],[59,45,0]],76:[[5,5,0],[6,6,0],[7,6,0],[8,8,0],[9,9,0],[11,11,0],[13,14,0],[15,16,0],[18,19,0],[22,23,0],[26,27,0],[30,33,0],[36,39,0],[43,45,-1]],77:[[8,5,0],[9,6,0],[11,6,0],[13,8,0],[15,10,0],[18,11,0],[21,14,0],[25,16,0],[29,19,0],[35,24,0],[42,27,0],[49,33,0],[58,39,0],[70,45,-1]],78:[[7,5,0],[8,7,0],[9,6,0],[11,9,0],[13,10,0],[15,12,0],[18,15,0],[21,17,0],[25,20,0],[30,24,0],[35,28,0],[42,34,0],[50,39,0],[59,46,0]],79:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,20,1],[25,25,1],[29,29,1],[35,35,2],[41,41,1],[49,48,1]],80:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,19,0],[25,23,0],[30,27,0],[35,33,0],[42,39,0],[50,45,0]],81:[[6,6,1],[7,8,2],[8,8,2],[9,10,2],[11,12,3],[13,14,3],[15,18,4],[18,21,5],[21,25,6],[25,31,7],[29,36,8],[35,44,10],[41,51,11],[49,59,13]],82:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,20,1],[25,24,1],[30,28,1],[35,34,1],[42,40,1],[50,46,1]],83:[[5,5,0],[6,6,0],[7,6,0],[8,8,0],[9,9,0],[11,11,0],[13,14,0],[15,16,0],[18,20,1],[22,25,1],[26,29,1],[31,35,2],[36,41,1],[43,48,2]],84:[[5,5,0],[6,6,0],[7,6,0],[9,8,0],[10,9,0],[12,11,0],[14,14,0],[17,16,0],[20,19,0],[24,23,0],[28,26,0],[33,32,0],[40,38,0],[47,44,0]],85:[[6,5,0],[7,6,0],[8,7,0],[10,9,0],[11,10,0],[13,12,0],[15,15,0],[18,17,0],[22,21,1],[26,25,1],[31,29,1],[36,35,1],[43,41,1],[51,48,1]],86:[[6,6,1],[7,7,1],[8,7,1],[10,9,1],[11,10,1],[13,12,1],[15,15,1],[18,17,1],[22,20,1],[26,24,1],[31,28,1],[36,35,2],[43,41,2],[51,47,1]],87:[[8,5,0],[9,6,0],[11,6,0],[13,8,0],[15,9,0],[18,11,0],[21,14,0],[25,16,0],[29,20,1],[35,24,1],[41,28,1],[49,34,1],[58,41,2],[69,48,2]],88:[[6,5,0],[8,7,1],[9,7,1],[10,9,1],[12,10,1],[15,12,1],[17,15,1],[20,17,1],[24,20,1],[28,24,1],[34,28,1],[40,34,1],[48,40,1],[56,46,1]],89:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[22,19,0],[26,23,0],[30,27,0],[36,33,0],[43,39,0],[51,45,-1]],90:[[5,5,0],[6,6,0],[8,6,0],[9,8,0],[10,9,0],[12,11,0],[15,14,0],[17,16,0],[20,19,0],[24,23,0],[29,27,0],[34,33,0],[40,39,0],[48,45,0]],97:[[4,3,0],[5,4,0],[5,4,0],[6,5,0],[7,6,0],[9,7,0],[10,9,0],[12,10,0],[14,12,0],[17,15,0],[20,17,0],[24,22,1],[28,26,1],[34,30,1]],98:[[3,5,0],[4,6,0],[5,6,0],[5,8,0],[6,9,0],[7,11,0],[9,14,0],[10,16,0],[12,19,0],[14,24,0],[17,27,0],[20,34,1],[24,40,1],[28,47,1]],99:[[3,3,0],[4,4,0],[5,4,0],[6,5,0],[6,6,0],[8,7,0],[9,9,0],[10,10,0],[12,12,0],[15,15,0],[17,17,0],[21,22,1],[24,26,1],[29,30,1]],100:[[4,5,0],[5,6,0],[6,6,0],[7,8,0],[8,9,0],[9,11,0],[11,14,0],[13,16,0],[15,19,0],[18,24,0],[21,27,0],[25,34,1],[30,40,1],[35,47,1]],101:[[3,3,0],[4,4,0],[5,4,0],[6,5,0],[6,6,0],[8,7,0],[9,9,0],[10,10,0],[12,12,0],[15,15,0],[17,17,0],[20,22,1],[24,26,1],[29,30,1]],102:[[4,6,1],[5,8,2],[6,8,2],[7,10,2],[8,12,3],[10,14,3],[11,18,4],[13,21,5],[16,25,6],[19,31,7],[22,36,8],[26,43,10],[31,51,12],[37,60,13]],103:[[4,4,1],[4,6,2],[5,6,2],[6,7,2],[7,9,3],[8,10,3],[10,13,4],[12,15,5],[14,18,6],[16,22,7],[19,25,8],[23,31,10],[27,37,12],[32,42,13]],104:[[4,5,0],[5,6,0],[6,6,0],[7,8,0],[8,9,0],[10,11,0],[11,14,0],[13,16,0],[16,19,0],[19,24,0],[22,27,0],[26,34,1],[31,40,1],[37,47,1]],105:[[3,5,0],[3,6,0],[3,6,0],[4,8,0],[5,10,0],[5,11,0],[6,14,0],[7,16,0],[9,18,0],[10,23,0],[12,26,0],[14,32,1],[17,38,1],[20,44,1]],106:[[4,6,1],[5,8,2],[5,8,2],[6,10,2],[7,13,3],[8,14,3],[9,18,4],[11,20,5],[13,24,6],[15,30,7],[17,33,8],[20,41,10],[24,49,12],[28,57,13]],107:[[4,5,0],[5,6,0],[5,6,0],[6,8,0],[7,9,0],[9,11,0],[10,14,0],[12,16,0],[14,19,0],[17,24,0],[20,27,0],[24,34,1],[28,40,1],[33,47,1]],108:[[2,6,0],[3,7,0],[3,7,0],[4,9,0],[4,10,0],[5,12,0],[6,15,0],[7,17,0],[8,20,0],[9,24,0],[11,28,0],[13,35,1],[15,40,1],[18,47,1]],109:[[6,3,0],[8,4,0],[9,4,0],[10,5,0],[12,6,0],[15,7,0],[17,9,0],[20,10,0],[24,12,0],[28,15,0],[34,17,0],[40,22,1],[48,26,1],[56,30,1]],110:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[10,7,0],[12,9,0],[14,10,0],[16,12,0],[19,15,0],[23,17,0],[27,22,1],[32,26,1],[38,30,1]],111:[[4,3,0],[4,4,0],[5,4,0],[6,5,0],[7,6,0],[8,7,0],[10,9,0],[12,10,0],[14,12,0],[16,15,0],[19,17,0],[23,22,1],[27,26,1],[32,30,1]],112:[[5,4,1],[6,6,2],[6,6,2],[7,7,2],[8,9,3],[10,10,3],[11,13,4],[13,15,5],[16,18,6],[19,22,7],[22,25,8],[26,31,10],[31,37,12],[36,43,14]],113:[[4,4,1],[4,6,2],[5,6,2],[6,7,2],[7,9,3],[8,10,3],[9,13,4],[11,15,5],[13,18,6],[16,22,7],[18,24,7],[22,31,10],[26,37,12],[31,42,13]],114:[[3,3,0],[4,4,0],[5,4,0],[6,5,0],[6,6,0],[8,7,0],[9,9,0],[10,10,0],[12,12,0],[15,15,0],[17,17,0],[20,22,1],[24,26,1],[29,30,1]],115:[[3,3,0],[4,4,0],[5,4,0],[5,5,0],[6,6,0],[7,7,0],[9,9,0],[10,10,0],[12,12,0],[14,15,0],[17,17,0],[20,22,1],[24,26,1],[28,30,1]],116:[[3,5,0],[3,6,0],[4,6,0],[4,7,0],[5,9,0],[6,10,0],[7,13,0],[8,15,0],[10,18,0],[11,22,0],[13,25,0],[16,30,1],[19,36,1],[22,42,1]],117:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[10,7,0],[11,9,0],[13,10,0],[16,12,0],[19,15,0],[22,17,0],[26,22,1],[31,26,1],[37,30,1]],118:[[4,3,0],[4,4,0],[5,4,0],[6,5,0],[7,6,0],[8,7,0],[10,9,0],[11,10,0],[13,12,0],[16,15,0],[19,17,0],[22,22,1],[26,26,1],[31,30,1]],119:[[5,3,0],[6,4,0],[7,4,0],[9,5,0],[10,6,0],[12,7,0],[14,9,0],[16,10,0],[20,12,0],[23,15,0],[27,17,0],[32,22,1],[39,26,1],[46,30,1]],120:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[9,7,0],[11,9,0],[13,10,0],[15,12,0],[18,15,0],[21,17,0],[25,22,1],[29,26,1],[35,30,1]],121:[[4,4,1],[5,6,2],[5,6,2],[6,7,2],[7,9,3],[9,10,3],[10,13,4],[12,15,5],[14,18,6],[17,22,7],[20,25,8],[23,31,10],[28,37,12],[33,42,13]],122:[[4,3,0],[4,4,0],[5,4,0],[6,5,0],[7,6,0],[8,7,0],[10,9,0],[11,10,0],[13,12,0],[16,15,0],[19,17,0],[22,22,1],[26,26,1],[31,30,1]],160:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],915:[[5,5,0],[6,6,0],[8,6,0],[9,8,0],[10,9,0],[12,11,0],[14,14,0],[17,16,0],[20,19,0],[24,23,0],[29,27,0],[34,33,0],[40,39,0],[48,45,0]],916:[[6,5,0],[7,6,0],[8,6,0],[10,8,0],[11,9,0],[14,11,0],[16,14,0],[19,16,0],[22,19,0],[26,24,0],[31,28,0],[37,34,0],[44,41,0],[52,47,0]],920:[[6,5,0],[7,6,0],[8,6,0],[9,8,0],[11,9,0],[13,11,0],[15,14,0],[18,16,0],[21,20,1],[25,25,1],[29,29,1],[35,35,2],[41,41,1],[49,48,1]],923:[[5,5,0],[6,7,0],[7,7,0],[8,8,0],[10,10,0],[12,12,0],[14,15,0],[16,16,0],[19,20,0],[23,24,0],[27,28,0],[32,34,1],[38,41,1],[45,47,0]],926:[[6,5,0],[7,6,0],[8,6,0],[10,8,0],[11,9,0],[13,11,0],[16,14,0],[19,16,0],[22,19,0],[26,23,0],[31,27,0],[37,32,0],[43,38,0],[52,45,0]],928:[[7,5,0],[8,6,0],[9,6,0],[11,8,0],[13,9,0],[15,11,0],[18,14,0],[21,16,0],[25,19,0],[30,23,0],[35,27,0],[42,33,0],[50,39,0],[59,45,0]],931:[[6,5,0],[7,6,0],[8,6,0],[10,8,0],[12,9,0],[14,11,0],[16,14,0],[19,16,0],[23,19,0],[27,23,0],[32,27,0],[38,33,0],[45,39,0],[54,46,0]],933:[[5,5,0],[6,6,0],[7,6,0],[9,8,0],[10,9,0],[12,11,0],[14,14,0],[17,16,0],[20,19,0],[23,24,0],[28,28,0],[33,34,0],[39,40,0],[46,46,0]],934:[[5,5,0],[6,6,0],[7,6,0],[8,8,0],[9,9,0],[11,11,0],[13,14,0],[15,16,0],[18,19,0],[22,23,0],[26,27,0],[30,32,-1],[36,39,0],[43,45,-1]],936:[[5,5,0],[6,6,0],[7,6,0],[9,8,0],[10,9,0],[12,11,0],[14,14,0],[17,16,0],[20,19,0],[23,23,0],[28,27,0],[33,32,-1],[39,39,0],[46,45,-1]],937:[[6,5,0],[7,6,0],[8,6,0],[10,8,0],[11,9,0],[14,11,0],[16,14,0],[19,16,0],[22,19,0],[26,24,0],[31,28,0],[37,34,0],[44,40,0],[52,47,0]],945:[[5,3,0],[5,4,0],[6,4,0],[8,5,0],[9,6,0],[10,7,0],[12,9,0],[14,10,0],[17,12,0],[20,15,0],[24,17,0],[28,22,1],[34,26,1],[40,30,1]],946:[[4,6,1],[5,8,2],[6,8,2],[7,10,2],[8,12,3],[10,14,3],[12,18,4],[14,21,5],[16,25,6],[19,31,7],[23,36,8],[27,43,10],[32,52,12],[38,59,13]],947:[[4,4,1],[5,6,2],[6,6,2],[7,7,2],[8,9,3],[10,10,3],[11,13,4],[13,15,5],[16,18,6],[18,22,7],[22,25,8],[26,32,11],[31,38,13],[36,44,15]],948:[[4,5,0],[4,6,0],[5,6,0],[6,8,0],[7,9,0],[8,11,0],[9,14,0],[11,16,0],[13,19,0],[15,24,0],[18,28,0],[21,35,1],[25,41,1],[30,48,1]],949:[[3,3,0],[4,4,0],[5,4,0],[6,5,0],[6,6,0],[8,7,0],[9,9,0],[10,10,0],[12,13,1],[15,16,1],[17,18,1],[20,22,1],[24,27,2],[29,31,1]],950:[[4,6,1],[4,8,2],[5,8,2],[6,10,2],[7,12,3],[8,14,3],[10,18,4],[11,21,5],[13,25,6],[16,31,7],[19,36,8],[22,43,10],[26,52,12],[31,60,13]],951:[[4,4,1],[5,6,2],[5,6,2],[6,7,2],[7,9,3],[9,10,3],[10,13,4],[12,15,5],[14,18,6],[17,22,7],[20,25,8],[24,32,11],[28,38,13],[33,44,15]],952:[[4,5,0],[4,6,0],[5,6,0],[6,8,0],[7,9,0],[8,11,0],[9,14,0],[11,16,0],[13,19,0],[16,24,0],[19,28,0],[22,34,1],[26,41,1],[31,47,1]],953:[[3,3,0],[3,4,0],[4,4,0],[4,5,0],[5,6,0],[6,7,0],[7,9,0],[8,10,0],[10,12,0],[11,15,0],[13,17,0],[16,22,1],[19,26,1],[22,30,1]],954:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[10,7,0],[11,9,0],[13,10,0],[16,12,0],[19,15,0],[22,17,0],[26,22,1],[31,26,1],[37,30,1]],955:[[4,5,0],[5,6,0],[6,6,0],[7,8,0],[8,9,0],[10,11,0],[11,14,0],[13,16,0],[16,19,0],[19,24,0],[22,27,0],[26,34,1],[31,40,1],[37,47,1]],956:[[4,4,1],[5,6,2],[6,6,2],[7,7,2],[8,9,3],[10,10,3],[12,13,4],[14,15,5],[16,18,6],[20,22,7],[23,25,8],[27,32,11],[33,38,13],[39,44,15]],957:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[9,7,0],[11,9,0],[13,10,0],[15,12,0],[18,15,0],[21,17,0],[25,22,1],[30,25,0],[35,29,0]],958:[[4,6,1],[4,8,2],[5,8,2],[6,10,2],[7,12,3],[8,14,3],[9,18,4],[11,21,5],[13,25,6],[15,31,7],[18,36,8],[21,43,10],[25,52,12],[30,60,13]],959:[[4,3,0],[4,4,0],[5,4,0],[6,5,0],[7,6,0],[8,7,0],[10,9,0],[12,10,0],[14,12,0],[16,15,0],[19,17,0],[23,22,1],[27,26,1],[32,30,1]],960:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[10,7,0],[12,9,0],[14,10,0],[16,12,0],[19,15,0],[23,17,0],[27,22,1],[32,25,1],[38,29,1]],961:[[4,4,1],[5,6,2],[5,6,2],[6,7,2],[7,9,3],[9,10,3],[10,13,4],[12,15,5],[14,18,6],[17,22,7],[20,25,8],[24,32,11],[28,38,13],[34,44,15]],962:[[3,4,1],[4,5,1],[5,5,1],[5,7,2],[6,8,2],[7,9,2],[8,11,2],[10,13,3],[12,15,3],[14,19,4],[17,22,5],[20,26,5],[23,32,7],[27,36,7]],963:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[10,7,0],[12,9,0],[14,10,0],[16,12,0],[19,15,0],[23,17,0],[27,22,1],[32,25,1],[38,29,1]],964:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[9,7,0],[10,9,0],[12,10,0],[15,12,0],[17,15,0],[21,17,0],[24,21,1],[29,26,1],[34,29,1]],965:[[4,3,0],[5,4,0],[6,4,0],[7,5,0],[8,6,0],[9,7,0],[11,9,0],[13,10,0],[15,12,0],[18,15,0],[21,17,0],[25,22,1],[29,26,1],[35,30,1]],966:[[5,4,1],[6,6,2],[7,6,2],[8,7,2],[9,9,3],[11,10,3],[13,13,4],[15,15,5],[18,18,6],[21,22,7],[25,25,8],[29,32,11],[35,38,13],[41,44,15]],967:[[5,4,1],[5,6,2],[6,6,2],[8,7,2],[9,9,3],[10,10,3],[12,13,4],[14,15,5],[17,18,6],[20,22,7],[24,25,8],[28,31,10],[34,37,12],[40,42,13]],968:[[5,6,1],[6,8,2],[7,8,2],[8,10,2],[9,12,3],[11,14,3],[13,18,4],[15,21,5],[18,25,6],[21,31,7],[25,35,8],[30,43,10],[35,51,12],[42,59,13]],969:[[5,3,0],[6,4,0],[6,4,0],[8,5,0],[9,6,0],[11,7,0],[12,9,0],[15,10,0],[17,12,0],[20,15,0],[24,17,0],[29,22,1],[34,26,1],[40,30,1]],977:[[4,5,0],[5,6,0],[6,6,0],[7,8,0],[8,9,0],[10,11,0],[11,14,0],[14,16,0],[16,19,0],[19,24,0],[23,28,0],[27,34,1],[32,41,1],[38,47,1]],981:[[4,6,1],[5,8,2],[6,8,2],[7,10,2],[8,12,3],[10,14,3],[12,18,4],[14,21,5],[16,25,6],[20,31,7],[23,35,8],[27,43,10],[32,51,12],[39,59,13]],982:[[6,3,0],[7,4,0],[9,4,0],[10,5,0],[12,6,0],[14,7,0],[17,9,0],[20,10,0],[23,12,0],[28,15,0],[33,17,0],[39,22,1],[46,25,1],[55,29,1]],1009:[[4,4,1],[5,6,2],[5,6,2],[6,7,2],[8,9,3],[9,10,3],[10,13,4],[12,15,5],[15,18,6],[17,22,7],[20,25,8],[24,31,10],[29,37,12],[34,42,13]],1013:[[3,3,0],[4,4,0],[4,4,0],[5,5,0],[6,6,0],[7,7,0],[8,9,0],[9,10,0],[11,12,0],[13,15,0],[15,17,0],[18,21,1],[21,25,1],[25,30,1]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Math/Italic"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/Main.js");
| MMore/cdnjs | ajax/libs/mathjax/2.3.0/fonts/HTML-CSS/TeX/png/Math/Italic/Main.js | JavaScript | mit | 13,613 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0635",
"\u0645"
],
"DAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"MONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"SHORTDAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"SHORTMONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0623\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0633\u0637\u0633",
"\u0633\u0628\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u064a\u0633\u0645\u0628\u0631"
],
"fullDate": "EEEE\u060c d MMMM\u060c y",
"longDate": "d MMMM\u060c y",
"medium": "dd\u200f/MM\u200f/y h:mm:ss a",
"mediumDate": "dd\u200f/MM\u200f/y",
"mediumTime": "h:mm:ss a",
"short": "d\u200f/M\u200f/y h:mm a",
"shortDate": "d\u200f/M\u200f/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u00a3",
"DECIMAL_SEP": "\u066b",
"GROUP_SEP": "\u066c",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "ar-dj",
"pluralCat": function (n, opt_precision) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;}
});
}]); | emmy41124/cdnjs | ajax/libs/angular-i18n/1.3.0-beta.19/angular-locale_ar-dj.js | JavaScript | mit | 3,384 |
/*
* Copyright (c) 2013, Leap Motion, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Version 0.2.0 - http://js.leapmotion.com/0.2.0/leap.min.js
* Grab latest versions from http://js.leapmotion.com/
*/
!function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i}({1:[function(require,module,exports){var chooseProtocol=require("./protocol").chooseProtocol,EventEmitter=require("events").EventEmitter,_=require("underscore");var BaseConnection=module.exports=function(opts){this.opts=_.defaults(opts||{},{host:"127.0.0.1",enableGestures:false,port:6437,enableHeartbeat:true,heartbeatInterval:100,requestProtocolVersion:3});this.host=opts.host;this.port=opts.port;this.on("ready",function(){this.enableGestures(this.opts.enableGestures);if(this.opts.enableHeartbeat)this.startHeartbeat()});this.on("disconnect",function(){if(this.opts.enableHeartbeat)this.stopHeartbeat()});this.heartbeatTimer=null};BaseConnection.prototype.getUrl=function(){return"ws://"+this.host+":"+this.port+"/v"+this.opts.requestProtocolVersion+".json"};BaseConnection.prototype.sendHeartbeat=function(){if(this.protocol){this.setHeartbeatState(true);this.protocol.sendHeartbeat(this)}};BaseConnection.prototype.handleOpen=function(){this.emit("connect")};BaseConnection.prototype.enableGestures=function(enabled){this.gesturesEnabled=enabled?true:false;this.send(this.protocol.encode({enableGestures:this.gesturesEnabled}))};BaseConnection.prototype.handleClose=function(){this.disconnect();this.startReconnection()};BaseConnection.prototype.startReconnection=function(){var connection=this;setTimeout(function(){connection.connect()},1e3)};BaseConnection.prototype.disconnect=function(){if(!this.socket)return;this.socket.close();delete this.socket;delete this.protocol;this.emit("disconnect")};BaseConnection.prototype.handleData=function(data){var message=JSON.parse(data);var messageEvent;if(this.protocol===undefined){messageEvent=this.protocol=chooseProtocol(message);this.emit("ready")}else{messageEvent=this.protocol(message)}this.emit(messageEvent.type,messageEvent)};BaseConnection.prototype.connect=function(){if(this.socket)return;this.socket=this.setupSocket();return true};BaseConnection.prototype.send=function(data){this.socket.send(data)};BaseConnection.prototype.stopHeartbeat=function(){if(!this.heartbeatTimer)return;clearInterval(this.heartbeatTimer);delete this.heartbeatTimer;this.setHeartbeatState(false)};BaseConnection.prototype.setHeartbeatState=function(state){if(this.heartbeatState===state)return;this.heartbeatState=state;this.emit(this.heartbeatState?"focus":"blur")};_.extend(BaseConnection.prototype,EventEmitter.prototype)},{"./protocol":12,events:17,underscore:20}],2:[function(require,module,exports){var CircularBuffer=module.exports=function(size){this.pos=0;this._buf=[];this.size=size};CircularBuffer.prototype.get=function(i){if(i==undefined)i=0;if(i>=this.size)return undefined;if(i>=this._buf.length)return undefined;return this._buf[(this.pos-i-1)%this.size]};CircularBuffer.prototype.push=function(o){this._buf[this.pos%this.size]=o;return this.pos++}},{}],3:[function(require,module,exports){var Connection=module.exports=require("./base_connection");Connection.prototype.setupSocket=function(){var connection=this;var socket=new WebSocket(this.getUrl());socket.onopen=function(){connection.handleOpen()};socket.onmessage=function(message){connection.handleData(message.data)};socket.onclose=function(){connection.handleClose()};return socket};Connection.prototype.startHeartbeat=function(){if(!this.protocol.sendHeartbeat||this.heartbeatTimer)return;var connection=this;var propertyName=null;if(typeof document.hidden!=="undefined"){propertyName="hidden"}else if(typeof document.mozHidden!=="undefined"){propertyName="mozHidden"}else if(typeof document.msHidden!=="undefined"){propertyName="msHidden"}else if(typeof document.webkitHidden!=="undefined"){propertyName="webkitHidden"}else{propertyName=undefined}var windowVisible=true;var focusListener=window.addEventListener("focus",function(e){windowVisible=true});var blurListener=window.addEventListener("blur",function(e){windowVisible=false});this.on("disconnect",function(){if(connection.heartbeatTimer){clearTimeout(connection.heartbeatTimer);delete connection.heartbeatTimer}window.removeEventListener(focusListener);window.removeEventListener(blurListener)});this.heartbeatTimer=setInterval(function(){var isVisible=propertyName===undefined?true:document[propertyName]===false;if(isVisible&&windowVisible){connection.sendHeartbeat()}else{connection.setHeartbeatState(false)}},this.opts.heartbeatInterval)}},{"./base_connection":1}],4:[function(require,module,exports){!function(process){var Frame=require("./frame"),CircularBuffer=require("./circular_buffer"),Pipeline=require("./pipeline"),EventEmitter=require("events").EventEmitter,gestureListener=require("./gesture").gestureListener,_=require("underscore");var Controller=module.exports=function(opts){var inNode=typeof process!=="undefined"&&process.title==="node";opts=_.defaults(opts||{},{inNode:inNode});this.inNode=opts.inNode;opts=_.defaults(opts||{},{frameEventName:this.useAnimationLoop()?"animationFrame":"deviceFrame",supressAnimationLoop:false});this.supressAnimationLoop=opts.supressAnimationLoop;this.frameEventName=opts.frameEventName;this.history=new CircularBuffer(200);this.lastFrame=Frame.Invalid;this.lastValidFrame=Frame.Invalid;this.lastConnectionFrame=Frame.Invalid;this.accumulatedGestures=[];if(opts.connectionType===undefined){this.connectionType=this.inBrowser()?require("./connection"):require("./node_connection")}else{this.connectionType=opts.connectionType}this.connection=new this.connectionType(opts);this.setupConnectionEvents()};Controller.prototype.gesture=function(type,cb){var creator=gestureListener(this,type);if(cb!==undefined){creator.stop(cb)}return creator};Controller.prototype.inBrowser=function(){return!this.inNode};Controller.prototype.useAnimationLoop=function(){return this.inBrowser()&&typeof chrome==="undefined"};Controller.prototype.connect=function(){var controller=this;if(this.connection.connect()&&this.inBrowser()&&!controller.supressAnimationLoop){var callback=function(){controller.emit("animationFrame",controller.lastConnectionFrame);window.requestAnimFrame(callback)};window.requestAnimFrame(callback)}};Controller.prototype.disconnect=function(){this.connection.disconnect()};Controller.prototype.frame=function(num){return this.history.get(num)||Frame.Invalid};Controller.prototype.loop=function(callback){switch(callback.length){case 1:this.on(this.frameEventName,callback);break;case 2:var controller=this;var scheduler=null;var immediateRunnerCallback=function(frame){callback(frame,function(){if(controller.lastFrame!=frame){immediateRunnerCallback(controller.lastFrame)}else{controller.once(controller.frameEventName,immediateRunnerCallback)}})};this.once(this.frameEventName,immediateRunnerCallback);break}this.connect()};Controller.prototype.addStep=function(step){if(!this.pipeline)this.pipeline=new Pipeline(this);this.pipeline.addStep(step)};Controller.prototype.processFrame=function(frame){if(frame.gestures){this.accumulatedGestures=this.accumulatedGestures.concat(frame.gestures)}if(this.pipeline){frame=this.pipeline.run(frame);if(!frame)frame=Frame.Invalid}this.lastConnectionFrame=frame;this.emit("deviceFrame",frame)};Controller.prototype.processFinishedFrame=function(frame){this.lastFrame=frame;if(frame.valid){this.lastValidFrame=frame}frame.controller=this;frame.historyIdx=this.history.push(frame);if(frame.gestures){frame.gestures=this.accumulatedGestures;this.accumulatedGestures=[];for(var gestureIdx=0;gestureIdx!=frame.gestures.length;gestureIdx++){this.emit("gesture",frame.gestures[gestureIdx],frame)}}this.emit("frame",frame)};Controller.prototype.setupConnectionEvents=function(){var controller=this;this.connection.on("frame",function(frame){controller.processFrame(frame)});this.on(this.frameEventName,function(frame){controller.processFinishedFrame(frame)});this.connection.on("disconnect",function(){controller.emit("disconnect")});this.connection.on("ready",function(){controller.emit("ready")});this.connection.on("connect",function(){controller.emit("connect")});this.connection.on("focus",function(){controller.emit("focus")});this.connection.on("blur",function(){controller.emit("blur")});this.connection.on("protocol",function(protocol){controller.emit("protocol",protocol)});this.connection.on("deviceConnect",function(evt){controller.emit(evt.state?"deviceConnected":"deviceDisconnected")})};_.extend(Controller.prototype,EventEmitter.prototype)}(require("__browserify_process"))},{"./circular_buffer":2,"./connection":3,"./frame":5,"./gesture":6,"./node_connection":16,"./pipeline":10,__browserify_process:18,events:17,underscore:20}],5:[function(require,module,exports){var Hand=require("./hand"),Pointable=require("./pointable"),createGesture=require("./gesture").createGesture,glMatrix=require("gl-matrix"),mat3=glMatrix.mat3,vec3=glMatrix.vec3,InteractionBox=require("./interaction_box"),_=require("underscore");var Frame=module.exports=function(data){this.valid=true;this.id=data.id;this.timestamp=data.timestamp;this.hands=[];this.handsMap={};this.pointables=[];this.tools=[];this.fingers=[];if(data.interactionBox){this.interactionBox=new InteractionBox(data.interactionBox)}this.gestures=[];this.pointablesMap={};this._translation=data.t;this._rotation=_.flatten(data.r);this._scaleFactor=data.s;this.data=data;this.type="frame";this.currentFrameRate=data.currentFrameRate;var handMap={};for(var handIdx=0,handCount=data.hands.length;handIdx!=handCount;handIdx++){var hand=new Hand(data.hands[handIdx]);hand.frame=this;this.hands.push(hand);this.handsMap[hand.id]=hand;handMap[hand.id]=handIdx}for(var pointableIdx=0,pointableCount=data.pointables.length;pointableIdx!=pointableCount;pointableIdx++){var pointable=new Pointable(data.pointables[pointableIdx]);pointable.frame=this;this.pointables.push(pointable);this.pointablesMap[pointable.id]=pointable;(pointable.tool?this.tools:this.fingers).push(pointable);if(pointable.handId!==undefined&&handMap.hasOwnProperty(pointable.handId)){var hand=this.hands[handMap[pointable.handId]];hand.pointables.push(pointable);(pointable.tool?hand.tools:hand.fingers).push(pointable)}}if(data.gestures){for(var gestureIdx=0,gestureCount=data.gestures.length;gestureIdx!=gestureCount;gestureIdx++){this.gestures.push(createGesture(data.gestures[gestureIdx]))}}};Frame.prototype.tool=function(id){var pointable=this.pointable(id);return pointable.tool?pointable:Pointable.Invalid};Frame.prototype.pointable=function(id){return this.pointablesMap[id]||Pointable.Invalid};Frame.prototype.finger=function(id){var pointable=this.pointable(id);return!pointable.tool?pointable:Pointable.Invalid};Frame.prototype.hand=function(id){return this.handsMap[id]||Hand.Invalid};Frame.prototype.rotationAngle=function(sinceFrame,axis){if(!this.valid||!sinceFrame.valid)return 0;var rot=this.rotationMatrix(sinceFrame);var cs=(rot[0]+rot[4]+rot[8]-1)*.5;var angle=Math.acos(cs);angle=isNaN(angle)?0:angle;if(axis!==undefined){var rotAxis=this.rotationAxis(sinceFrame);angle*=vec3.dot(rotAxis,vec3.normalize(vec3.create(),axis))}return angle};Frame.prototype.rotationAxis=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();return vec3.normalize(vec3.create(),[this._rotation[7]-sinceFrame._rotation[5],this._rotation[2]-sinceFrame._rotation[6],this._rotation[3]-sinceFrame._rotation[1]])};Frame.prototype.rotationMatrix=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return mat3.create();var transpose=mat3.transpose(mat3.create(),this._rotation);return mat3.multiply(mat3.create(),sinceFrame._rotation,transpose)};Frame.prototype.scaleFactor=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return 1;return Math.exp(this._scaleFactor-sinceFrame._scaleFactor)};Frame.prototype.translation=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();return vec3.subtract(vec3.create(),this._translation,sinceFrame._translation)};Frame.prototype.toString=function(){var str="Frame [ id:"+this.id+" | timestamp:"+this.timestamp+" | Hand count:("+this.hands.length+") | Pointable count:("+this.pointables.length+")";if(this.gestures)str+=" | Gesture count:("+this.gestures.length+")";str+=" ]";return str};Frame.prototype.dump=function(){var out="";out+="Frame Info:<br/>";out+=this.toString();out+="<br/><br/>Hands:<br/>";for(var handIdx=0,handCount=this.hands.length;handIdx!=handCount;handIdx++){out+=" "+this.hands[handIdx].toString()+"<br/>"}out+="<br/><br/>Pointables:<br/>";for(var pointableIdx=0,pointableCount=this.pointables.length;pointableIdx!=pointableCount;pointableIdx++){out+=" "+this.pointables[pointableIdx].toString()+"<br/>"}if(this.gestures){out+="<br/><br/>Gestures:<br/>";for(var gestureIdx=0,gestureCount=this.gestures.length;gestureIdx!=gestureCount;gestureIdx++){out+=" "+this.gestures[gestureIdx].toString()+"<br/>"}}out+="<br/><br/>Raw JSON:<br/>";out+=JSON.stringify(this.data);return out};Frame.Invalid={valid:false,hands:[],fingers:[],tools:[],gestures:[],pointables:[],pointable:function(){return Pointable.Invalid},finger:function(){return Pointable.Invalid},hand:function(){return Hand.Invalid},toString:function(){return"invalid frame"},dump:function(){return this.toString()},rotationAngle:function(){return 0},rotationMatrix:function(){return mat3.create()},rotationAxis:function(){return vec3.create()},scaleFactor:function(){return 1},translation:function(){return vec3.create()}}},{"./gesture":6,"./hand":7,"./interaction_box":9,"./pointable":11,"gl-matrix":19,underscore:20}],6:[function(require,module,exports){var glMatrix=require("gl-matrix"),vec3=glMatrix.vec3,EventEmitter=require("events").EventEmitter,_=require("underscore");var createGesture=exports.createGesture=function(data){var gesture;switch(data.type){case"circle":gesture=new CircleGesture(data);break;case"swipe":gesture=new SwipeGesture(data);break;case"screenTap":gesture=new ScreenTapGesture(data);break;case"keyTap":gesture=new KeyTapGesture(data);break;default:throw"unkown gesture type"}gesture.id=data.id;gesture.handIds=data.handIds;gesture.pointableIds=data.pointableIds;gesture.duration=data.duration;gesture.state=data.state;gesture.type=data.type;return gesture};var gestureListener=exports.gestureListener=function(controller,type){var handlers={};var gestureMap={};var gestureCreator=function(){var candidateGesture=gestureMap[gesture.id];if(candidateGesture!==undefined)gesture.update(gesture,frame);if(gesture.state=="start"||gesture.state=="stop"){if(type==gesture.type&&gestureMap[gesture.id]===undefined){gestureMap[gesture.id]=new Gesture(gesture,frame);gesture.update(gesture,frame)}if(gesture.state=="stop"){delete gestureMap[gesture.id]}}};controller.on("gesture",function(gesture,frame){if(gesture.type==type){if(gesture.state=="start"||gesture.state=="stop"){if(gestureMap[gesture.id]===undefined){var gestureTracker=new Gesture(gesture,frame);gestureMap[gesture.id]=gestureTracker;_.each(handlers,function(cb,name){gestureTracker.on(name,cb)})}}gestureMap[gesture.id].update(gesture,frame);if(gesture.state=="stop"){delete gestureMap[gesture.id]}}});var builder={start:function(cb){handlers["start"]=cb;return builder},stop:function(cb){handlers["stop"]=cb;return builder},complete:function(cb){handlers["stop"]=cb;return builder},update:function(cb){handlers["update"]=cb;return builder}};return builder};var Gesture=exports.Gesture=function(gesture,frame){this.gestures=[gesture];this.frames=[frame]};Gesture.prototype.update=function(gesture,frame){this.gestures.push(gesture);this.frames.push(frame);this.emit(gesture.state,this)};_.extend(Gesture.prototype,EventEmitter.prototype);var CircleGesture=function(data){this.center=data.center;this.normal=data.normal;this.progress=data.progress;this.radius=data.radius};CircleGesture.prototype.toString=function(){return"CircleGesture ["+JSON.stringify(this)+"]"};var SwipeGesture=function(data){this.startPosition=data.startPosition;this.position=data.position;this.direction=data.direction;this.speed=data.speed};SwipeGesture.prototype.toString=function(){return"SwipeGesture ["+JSON.stringify(this)+"]"};var ScreenTapGesture=function(data){this.position=data.position;this.direction=data.direction;this.progress=data.progress};ScreenTapGesture.prototype.toString=function(){return"ScreenTapGesture ["+JSON.stringify(this)+"]"};var KeyTapGesture=function(data){this.position=data.position;this.direction=data.direction;this.progress=data.progress};KeyTapGesture.prototype.toString=function(){return"KeyTapGesture ["+JSON.stringify(this)+"]"}},{events:17,"gl-matrix":19,underscore:20}],7:[function(require,module,exports){var Pointable=require("./pointable"),glMatrix=require("gl-matrix"),mat3=glMatrix.mat3,vec3=glMatrix.vec3,_=require("underscore");var Hand=module.exports=function(data){this.id=data.id;this.palmPosition=data.palmPosition;this.direction=data.direction;this.palmVelocity=data.palmVelocity;this.palmNormal=data.palmNormal;this.sphereCenter=data.sphereCenter;this.sphereRadius=data.sphereRadius;this.valid=true;this.pointables=[];this.fingers=[];this.tools=[];this._translation=data.t;this._rotation=_.flatten(data.r);this._scaleFactor=data.s;this.timeVisible=data.timeVisible;this.stabilizedPalmPosition=data.stabilizedPalmPosition};Hand.prototype.finger=function(id){var finger=this.frame.finger(id);return finger&&finger.handId==this.id?finger:Pointable.Invalid};Hand.prototype.rotationAngle=function(sinceFrame,axis){if(!this.valid||!sinceFrame.valid)return 0;var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return 0;var rot=this.rotationMatrix(sinceFrame);var cs=(rot[0]+rot[4]+rot[8]-1)*.5;var angle=Math.acos(cs);angle=isNaN(angle)?0:angle;if(axis!==undefined){var rotAxis=this.rotationAxis(sinceFrame);angle*=vec3.dot(rotAxis,vec3.normalize(vec3.create(),axis))}return angle};Hand.prototype.rotationAxis=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return vec3.create();return vec3.normalize(vec3.create(),[this._rotation[7]-sinceHand._rotation[5],this._rotation[2]-sinceHand._rotation[6],this._rotation[3]-sinceHand._rotation[1]])};Hand.prototype.rotationMatrix=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return mat3.create();var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return mat3.create();var transpose=mat3.transpose(mat3.create(),this._rotation);var m=mat3.multiply(mat3.create(),sinceHand._rotation,transpose);return m};Hand.prototype.scaleFactor=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return 1;var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return 1;return Math.exp(this._scaleFactor-sinceHand._scaleFactor)};Hand.prototype.translation=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return vec3.create();return[this._translation[0]-sinceHand._translation[0],this._translation[1]-sinceHand._translation[1],this._translation[2]-sinceHand._translation[2]]};Hand.prototype.toString=function(){return"Hand [ id: "+this.id+" | palm velocity:"+this.palmVelocity+" | sphere center:"+this.sphereCenter+" ] "};Hand.Invalid={valid:false,fingers:[],tools:[],pointables:[],pointable:function(){return Pointable.Invalid},finger:function(){return Pointable.Invalid},toString:function(){return"invalid frame"},dump:function(){return this.toString()},rotationAngle:function(){return 0},rotationMatrix:function(){return mat3.create()},rotationAxis:function(){return vec3.create()},scaleFactor:function(){return 1},translation:function(){return vec3.create()}}},{"./pointable":11,"gl-matrix":19,underscore:20}],8:[function(require,module,exports){!function(){module.exports={Controller:require("./controller"),Frame:require("./frame"),Gesture:require("./gesture"),Hand:require("./hand"),Pointable:require("./pointable"),InteractionBox:require("./interaction_box"),Connection:require("./connection"),CircularBuffer:require("./circular_buffer"),UI:require("./ui"),glMatrix:require("gl-matrix"),mat3:require("gl-matrix").mat3,vec3:require("gl-matrix").vec3,loopController:undefined,loop:function(opts,callback){if(callback===undefined){callback=opts;opts={}}if(!this.loopController)this.loopController=new this.Controller(opts);this.loopController.loop(callback)}}}()},{"./circular_buffer":2,"./connection":3,"./controller":4,"./frame":5,"./gesture":6,"./hand":7,"./interaction_box":9,"./pointable":11,"./ui":13,"gl-matrix":19}],9:[function(require,module,exports){var glMatrix=require("gl-matrix"),vec3=glMatrix.vec3;var InteractionBox=module.exports=function(data){this.valid=true;this.center=data.center;this.size=data.size;this.width=data.size[0];this.height=data.size[1];this.depth=data.size[2]};InteractionBox.prototype.denormalizePoint=function(normalizedPosition){return vec3.fromValues((normalizedPosition[0]-.5)*this.size[0]+this.center[0],(normalizedPosition[1]-.5)*this.size[1]+this.center[1],(normalizedPosition[2]-.5)*this.size[2]+this.center[2])};InteractionBox.prototype.normalizePoint=function(position,clamp){var vec=vec3.fromValues((position[0]-this.center[0])/this.size[0]+.5,(position[1]-this.center[1])/this.size[1]+.5,(position[2]-this.center[2])/this.size[2]+.5);if(clamp){vec[0]=Math.min(Math.max(vec[0],0),1);vec[1]=Math.min(Math.max(vec[1],0),1);vec[2]=Math.min(Math.max(vec[2],0),1)}return vec};InteractionBox.prototype.toString=function(){return"InteractionBox [ width:"+this.width+" | height:"+this.height+" | depth:"+this.depth+" ]"};InteractionBox.Invalid={valid:false}},{"gl-matrix":19}],10:[function(require,module,exports){var Pipeline=module.exports=function(){this.steps=[]};Pipeline.prototype.addStep=function(step){this.steps.push(step)};Pipeline.prototype.run=function(frame){var stepsLength=this.steps.length;for(var i=0;i!=stepsLength;i++){if(!frame)break;frame=this.steps[i](frame)}return frame}},{}],11:[function(require,module,exports){var glMatrix=require("gl-matrix"),vec3=glMatrix.vec3;var Pointable=module.exports=function(data){this.valid=true;this.id=data.id;this.handId=data.handId;this.length=data.length;this.tool=data.tool;this.width=data.width;this.direction=data.direction;this.stabilizedTipPosition=data.stabilizedTipPosition;this.tipPosition=data.tipPosition;this.tipVelocity=data.tipVelocity;this.touchZone=data.touchZone;this.touchDistance=data.touchDistance;this.timeVisible=data.timeVisible};Pointable.prototype.toString=function(){if(this.tool==true){return"Pointable [ id:"+this.id+" "+this.length+"mmx | with:"+this.width+"mm | direction:"+this.direction+" ]"}else{return"Pointable [ id:"+this.id+" "+this.length+"mmx | direction: "+this.direction+" ]"}};Pointable.Invalid={valid:false}},{"gl-matrix":19}],12:[function(require,module,exports){var Frame=require("./frame");var Event=function(data){this.type=data.type;this.state=data.state};var chooseProtocol=exports.chooseProtocol=function(header){var protocol;switch(header.version){case 1:protocol=JSONProtocol(1,function(data){return new Frame(data)});break;case 2:protocol=JSONProtocol(2,function(data){return new Frame(data)});protocol.sendHeartbeat=function(connection){connection.send(protocol.encode({heartbeat:true}))};break;case 3:protocol=JSONProtocol(3,function(data){return data.event?new Event(data.event):new Frame(data)});protocol.sendHeartbeat=function(connection){connection.send(protocol.encode({heartbeat:true}))};break;default:throw"unrecognized version"}return protocol};var JSONProtocol=function(version,cb){var protocol=cb;protocol.encode=function(message){return JSON.stringify(message)};protocol.version=version;protocol.versionLong="Version "+version;protocol.type="protocol";return protocol}},{"./frame":5}],13:[function(require,module,exports){exports.UI={Region:require("./ui/region"),Cursor:require("./ui/cursor")}},{"./ui/cursor":14,"./ui/region":15}],14:[function(require,module,exports){var Cursor=module.exports=function(){return function(frame){var pointable=frame.pointables.sort(function(a,b){return a.z-b.z})[0];if(pointable&&pointable.valid){frame.cursorPosition=pointable.tipPosition}return frame}}},{}],15:[function(require,module,exports){var EventEmitter=require("events").EventEmitter,_=require("underscore");var Region=module.exports=function(start,end){this.start=new Vector(start);this.end=new Vector(end);this.enteredFrame=null};Region.prototype.hasPointables=function(frame){for(var i=0;i!=frame.pointables.length;i++){var position=frame.pointables[i].tipPosition;if(position.x>=this.start.x&&position.x<=this.end.x&&position.y>=this.start.y&&position.y<=this.end.y&&position.z>=this.start.z&&position.z<=this.end.z){return true}}return false};Region.prototype.listener=function(opts){var region=this;if(opts&&opts.nearThreshold)this.setupNearRegion(opts.nearThreshold);return function(frame){return region.updatePosition(frame)}};Region.prototype.clipper=function(){var region=this;return function(frame){region.updatePosition(frame);return region.enteredFrame?frame:null}};Region.prototype.setupNearRegion=function(distance){var nearRegion=this.nearRegion=new Region([this.start.x-distance,this.start.y-distance,this.start.z-distance],[this.end.x+distance,this.end.y+distance,this.end.z+distance]);var region=this;nearRegion.on("enter",function(frame){region.emit("near",frame)});nearRegion.on("exit",function(frame){region.emit("far",frame)});region.on("exit",function(frame){region.emit("near",frame)})};Region.prototype.updatePosition=function(frame){if(this.nearRegion)this.nearRegion.updatePosition(frame);if(this.hasPointables(frame)&&this.enteredFrame==null){this.enteredFrame=frame;this.emit("enter",this.enteredFrame)}else if(!this.hasPointables(frame)&&this.enteredFrame!=null){this.enteredFrame=null;this.emit("exit",this.enteredFrame)}return frame};Region.prototype.normalize=function(position){return new Vector([(position.x-this.start.x)/(this.end.x-this.start.x),(position.y-this.start.y)/(this.end.y-this.start.y),(position.z-this.start.z)/(this.end.z-this.start.z)])};Region.prototype.mapToXY=function(position,width,height){var normalized=this.normalize(position);var x=normalized.x,y=normalized.y;if(x>1)x=1;else if(x<-1)x=-1;if(y>1)y=1;else if(y<-1)y=-1;return[(x+1)/2*width,(1-y)/2*height,normalized.z]};_.extend(Region.prototype,EventEmitter.prototype)},{events:17,underscore:20}],16:[function(require,module,exports){},{}],17:[function(require,module,exports){!function(process){if(!process.EventEmitter)process.EventEmitter=function(){};var EventEmitter=exports.EventEmitter=process.EventEmitter;var isArray=typeof Array.isArray==="function"?Array.isArray:function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function indexOf(xs,x){if(xs.indexOf)return xs.indexOf(x);for(var i=0;i<xs.length;i++){if(x===xs[i])return i}return-1}var defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!this._events)this._events={};this._events.maxListeners=n};EventEmitter.prototype.emit=function(type){if(type==="error"){if(!this._events||!this._events.error||isArray(this._events.error)&&!this._events.error.length){if(arguments[1]instanceof Error){throw arguments[1]}else{throw new Error("Uncaught, unspecified 'error' event.")}return false}}if(!this._events)return false;var handler=this._events[type];if(!handler)return false;if(typeof handler=="function"){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:var args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}return true}else if(isArray(handler)){var args=Array.prototype.slice.call(arguments,1);var listeners=handler.slice();for(var i=0,l=listeners.length;i<l;i++){listeners[i].apply(this,args)}return true}else{return false}};EventEmitter.prototype.addListener=function(type,listener){if("function"!==typeof listener){throw new Error("addListener only takes instances of Function")}if(!this._events)this._events={};this.emit("newListener",type,listener);if(!this._events[type]){this._events[type]=listener}else if(isArray(this._events[type])){if(!this._events[type].warned){var m;if(this._events.maxListeners!==undefined){m=this._events.maxListeners}else{m=defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);console.trace()}}this._events[type].push(listener)}else{this._events[type]=[this._events[type],listener]}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){var self=this;self.on(type,function g(){self.removeListener(type,g);listener.apply(this,arguments)});return this};EventEmitter.prototype.removeListener=function(type,listener){if("function"!==typeof listener){throw new Error("removeListener only takes instances of Function")}if(!this._events||!this._events[type])return this;var list=this._events[type];if(isArray(list)){var i=indexOf(list,listener);if(i<0)return this;list.splice(i,1);if(list.length==0)delete this._events[type]}else if(this._events[type]===listener){delete this._events[type]}return this};EventEmitter.prototype.removeAllListeners=function(type){if(arguments.length===0){this._events={};return this}if(type&&this._events&&this._events[type])this._events[type]=null;return this};EventEmitter.prototype.listeners=function(type){if(!this._events)this._events={};if(!this._events[type])this._events[type]=[];if(!isArray(this._events[type])){this._events[type]=[this._events[type]]}return this._events[type]}}(require("__browserify_process"))},{__browserify_process:18}],18:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){if(ev.source===window&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],19:[function(require,module,exports){!function(){!function(){"use strict";var shim={};if(typeof exports==="undefined"){if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){shim.exports={};define(function(){return shim.exports})}else{shim.exports=window}}else{shim.exports=exports}!function(exports){var vec2={};if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}vec2.create=function(){return new Float32Array(2)};vec2.clone=function(a){var out=new Float32Array(2);out[0]=a[0];out[1]=a[1];return out};vec2.fromValues=function(x,y){var out=new Float32Array(2);out[0]=x;out[1]=y;return out};vec2.copy=function(out,a){out[0]=a[0];out[1]=a[1];return out};vec2.set=function(out,x,y){out[0]=x;out[1]=y;return out};vec2.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];return out};vec2.sub=vec2.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];return out};vec2.mul=vec2.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];return out};vec2.div=vec2.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];return out};vec2.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);
out[1]=Math.min(a[1],b[1]);return out};vec2.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);return out};vec2.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;return out};vec2.dist=vec2.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)};vec2.sqrDist=vec2.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y};vec2.len=vec2.length=function(a){var x=a[0],y=a[1];return Math.sqrt(x*x+y*y)};vec2.sqrLen=vec2.squaredLength=function(a){var x=a[0],y=a[1];return x*x+y*y};vec2.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];return out};vec2.normalize=function(out,a){var x=a[0],y=a[1];var len=x*x+y*y;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len}return out};vec2.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]};vec2.cross=function(out,a,b){var z=a[0]*b[1]-a[1]*b[0];out[0]=out[1]=0;out[2]=z;return out};vec2.lerp=function(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out};vec2.transformMat2=function(out,a,m){var x=a[0],y=a[1];out[0]=x*m[0]+y*m[1];out[1]=x*m[2]+y*m[3];return out};vec2.forEach=function(){var vec=new Float32Array(2);return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=2}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1]}return a}}();vec2.str=function(a){return"vec2("+a[0]+", "+a[1]+")"};if(typeof exports!=="undefined"){exports.vec2=vec2}var vec3={};if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}vec3.create=function(){return new Float32Array(3)};vec3.clone=function(a){var out=new Float32Array(3);out[0]=a[0];out[1]=a[1];out[2]=a[2];return out};vec3.fromValues=function(x,y,z){var out=new Float32Array(3);out[0]=x;out[1]=y;out[2]=z;return out};vec3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];return out};vec3.set=function(out,x,y,z){out[0]=x;out[1]=y;out[2]=z;return out};vec3.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];return out};vec3.sub=vec3.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];return out};vec3.mul=vec3.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];return out};vec3.div=vec3.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];return out};vec3.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);return out};vec3.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);return out};vec3.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;return out};vec3.dist=vec3.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)};vec3.sqrDist=vec3.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z};vec3.len=vec3.length=function(a){var x=a[0],y=a[1],z=a[2];return Math.sqrt(x*x+y*y+z*z)};vec3.sqrLen=vec3.squaredLength=function(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z};vec3.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];return out};vec3.normalize=function(out,a){var x=a[0],y=a[1],z=a[2];var len=x*x+y*y+z*z;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len}return out};vec3.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};vec3.cross=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out};vec3.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);return out};vec3.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12];out[1]=m[1]*x+m[5]*y+m[9]*z+m[13];out[2]=m[2]*x+m[6]*y+m[10]*z+m[14];return out};vec3.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return out};vec3.forEach=function(){var vec=new Float32Array(3);return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=3}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2]}return a}}();vec3.str=function(a){return"vec3("+a[0]+", "+a[1]+", "+a[2]+")"};if(typeof exports!=="undefined"){exports.vec3=vec3}var vec4={};if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}vec4.create=function(){return new Float32Array(4)};vec4.clone=function(a){var out=new Float32Array(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};vec4.fromValues=function(x,y,z,w){var out=new Float32Array(4);out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out};vec4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};vec4.set=function(out,x,y,z,w){out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out};vec4.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out};vec4.sub=vec4.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];return out};vec4.mul=vec4.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];out[3]=a[3]*b[3];return out};vec4.div=vec4.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];out[3]=a[3]/b[3];return out};vec4.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);out[3]=Math.min(a[3],b[3]);return out};vec4.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);out[3]=Math.max(a[3],b[3]);return out};vec4.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out};vec4.dist=vec4.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return Math.sqrt(x*x+y*y+z*z+w*w)};vec4.sqrDist=vec4.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return x*x+y*y+z*z+w*w};vec4.len=vec4.length=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return Math.sqrt(x*x+y*y+z*z+w*w)};vec4.sqrLen=vec4.squaredLength=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return x*x+y*y+z*z+w*w};vec4.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=-a[3];return out};vec4.normalize=function(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var len=x*x+y*y+z*z+w*w;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;out[3]=a[3]*len}return out};vec4.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]};vec4.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out};vec4.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out};vec4.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return out};vec4.forEach=function(){var vec=new Float32Array(4);return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=4}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];vec[3]=a[i+3];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];a[i+3]=vec[3]}return a}}();vec4.str=function(a){return"vec4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"};if(typeof exports!=="undefined"){exports.vec4=vec4}var mat2={};var mat2Identity=new Float32Array([1,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}mat2.create=function(){return new Float32Array(mat2Identity)};mat2.clone=function(a){var out=new Float32Array(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};mat2.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};mat2.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out};mat2.transpose=function(out,a){if(out===a){var a1=a[1];out[1]=a[2];out[2]=a1}else{out[0]=a[0];out[1]=a[2];out[2]=a[1];out[3]=a[3]}return out};mat2.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],det=a0*a3-a2*a1;if(!det){return null}det=1/det;out[0]=a3*det;out[1]=-a1*det;out[2]=-a2*det;out[3]=a0*det;return out};mat2.adjoint=function(out,a){var a0=a[0];out[0]=a[3];out[1]=-a[1];out[2]=-a[2];out[3]=a0;return out};mat2.determinant=function(a){return a[0]*a[3]-a[2]*a[1]};mat2.mul=mat2.multiply=function(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=a0*b0+a1*b2;out[1]=a0*b1+a1*b3;out[2]=a2*b0+a3*b2;out[3]=a2*b1+a3*b3;return out};mat2.rotate=function(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],s=Math.sin(rad),c=Math.cos(rad);out[0]=a0*c+a1*s;out[1]=a0*-s+a1*c;out[2]=a2*c+a3*s;out[3]=a2*-s+a3*c;return out};mat2.scale=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v1;out[2]=a2*v0;out[3]=a3*v1;return out};mat2.str=function(a){return"mat2("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"};if(typeof exports!=="undefined"){exports.mat2=mat2}var mat3={};var mat3Identity=new Float32Array([1,0,0,0,1,0,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}mat3.create=function(){return new Float32Array(mat3Identity)};mat3.clone=function(a){var out=new Float32Array(9);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out};mat3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out};mat3.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out};mat3.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a12=a[5];out[1]=a[3];out[2]=a[6];out[3]=a01;out[5]=a[7];out[6]=a02;out[7]=a12}else{out[0]=a[0];out[1]=a[3];out[2]=a[6];out[3]=a[1];out[4]=a[4];out[5]=a[7];out[6]=a[2];out[7]=a[5];out[8]=a[8]}return out};mat3.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b01=a22*a11-a12*a21,b11=-a22*a10+a12*a20,b21=a21*a10-a11*a20,det=a00*b01+a01*b11+a02*b21;if(!det){return null}det=1/det;out[0]=b01*det;out[1]=(-a22*a01+a02*a21)*det;out[2]=(a12*a01-a02*a11)*det;out[3]=b11*det;out[4]=(a22*a00-a02*a20)*det;out[5]=(-a12*a00+a02*a10)*det;out[6]=b21*det;out[7]=(-a21*a00+a01*a20)*det;out[8]=(a11*a00-a01*a10)*det;return out};mat3.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];out[0]=a11*a22-a12*a21;out[1]=a02*a21-a01*a22;out[2]=a01*a12-a02*a11;out[3]=a12*a20-a10*a22;out[4]=a00*a22-a02*a20;out[5]=a02*a10-a00*a12;out[6]=a10*a21-a11*a20;out[7]=a01*a20-a00*a21;out[8]=a00*a11-a01*a10;return out};mat3.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];return a00*(a22*a11-a12*a21)+a01*(-a22*a10+a12*a20)+a02*(a21*a10-a11*a20)};mat3.mul=mat3.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b00=b[0],b01=b[1],b02=b[2],b10=b[3],b11=b[4],b12=b[5],b20=b[6],b21=b[7],b22=b[8];out[0]=b00*a00+b01*a10+b02*a20;out[1]=b00*a01+b01*a11+b02*a21;out[2]=b00*a02+b01*a12+b02*a22;out[3]=b10*a00+b11*a10+b12*a20;out[4]=b10*a01+b11*a11+b12*a21;out[5]=b10*a02+b11*a12+b12*a22;out[6]=b20*a00+b21*a10+b22*a20;out[7]=b20*a01+b21*a11+b22*a21;out[8]=b20*a02+b21*a12+b22*a22;return out};mat3.str=function(a){return"mat3("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+")"};if(typeof exports!=="undefined"){exports.mat3=mat3}var mat4={};var mat4Identity=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}mat4.create=function(){return new Float32Array(mat4Identity)};mat4.clone=function(a){var out=new Float32Array(16);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out};mat4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out};mat4.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out};mat4.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a03=a[3],a12=a[6],a13=a[7],a23=a[11];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a01;out[6]=a[9];out[7]=a[13];out[8]=a02;out[9]=a12;out[11]=a[14];out[12]=a03;out[13]=a13;out[14]=a23}else{out[0]=a[0];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a[1];out[5]=a[5];out[6]=a[9];out[7]=a[13];out[8]=a[2];out[9]=a[6];out[10]=a[10];out[11]=a[14];out[12]=a[3];out[13]=a[7];out[14]=a[11];out[15]=a[15]}return out};mat4.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32,det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null}det=1/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a02*b10-a01*b11-a03*b09)*det;out[2]=(a31*b05-a32*b04+a33*b03)*det;out[3]=(a22*b04-a21*b05-a23*b03)*det;out[4]=(a12*b08-a10*b11-a13*b07)*det;out[5]=(a00*b11-a02*b08+a03*b07)*det;out[6]=(a32*b02-a30*b05-a33*b01)*det;out[7]=(a20*b05-a22*b02+a23*b01)*det;out[8]=(a10*b10-a11*b08+a13*b06)*det;out[9]=(a01*b08-a00*b10-a03*b06)*det;out[10]=(a30*b04-a31*b02+a33*b00)*det;out[11]=(a21*b02-a20*b04-a23*b00)*det;out[12]=(a11*b07-a10*b09-a12*b06)*det;out[13]=(a00*b09-a01*b07+a02*b06)*det;out[14]=(a31*b01-a30*b03-a32*b00)*det;out[15]=(a20*b03-a21*b01+a22*b00)*det;return out};mat4.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];out[0]=a11*(a22*a33-a23*a32)-a21*(a12*a33-a13*a32)+a31*(a12*a23-a13*a22);out[1]=-(a01*(a22*a33-a23*a32)-a21*(a02*a33-a03*a32)+a31*(a02*a23-a03*a22));out[2]=a01*(a12*a33-a13*a32)-a11*(a02*a33-a03*a32)+a31*(a02*a13-a03*a12);out[3]=-(a01*(a12*a23-a13*a22)-a11*(a02*a23-a03*a22)+a21*(a02*a13-a03*a12));out[4]=-(a10*(a22*a33-a23*a32)-a20*(a12*a33-a13*a32)+a30*(a12*a23-a13*a22));out[5]=a00*(a22*a33-a23*a32)-a20*(a02*a33-a03*a32)+a30*(a02*a23-a03*a22);out[6]=-(a00*(a12*a33-a13*a32)-a10*(a02*a33-a03*a32)+a30*(a02*a13-a03*a12));out[7]=a00*(a12*a23-a13*a22)-a10*(a02*a23-a03*a22)+a20*(a02*a13-a03*a12);out[8]=a10*(a21*a33-a23*a31)-a20*(a11*a33-a13*a31)+a30*(a11*a23-a13*a21);out[9]=-(a00*(a21*a33-a23*a31)-a20*(a01*a33-a03*a31)+a30*(a01*a23-a03*a21));out[10]=a00*(a11*a33-a13*a31)-a10*(a01*a33-a03*a31)+a30*(a01*a13-a03*a11);out[11]=-(a00*(a11*a23-a13*a21)-a10*(a01*a23-a03*a21)+a20*(a01*a13-a03*a11));out[12]=-(a10*(a21*a32-a22*a31)-a20*(a11*a32-a12*a31)+a30*(a11*a22-a12*a21));out[13]=a00*(a21*a32-a22*a31)-a20*(a01*a32-a02*a31)+a30*(a01*a22-a02*a21);out[14]=-(a00*(a11*a32-a12*a31)-a10*(a01*a32-a02*a31)+a30*(a01*a12-a02*a11));out[15]=a00*(a11*a22-a12*a21)-a10*(a01*a22-a02*a21)+a20*(a01*a12-a02*a11);return out};mat4.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;return b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06};mat4.mul=mat4.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=b0*a00+b1*a10+b2*a20+b3*a30;out[1]=b0*a01+b1*a11+b2*a21+b3*a31;out[2]=b0*a02+b1*a12+b2*a22+b3*a32;out[3]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[4];b1=b[5];b2=b[6];b3=b[7];out[4]=b0*a00+b1*a10+b2*a20+b3*a30;out[5]=b0*a01+b1*a11+b2*a21+b3*a31;out[6]=b0*a02+b1*a12+b2*a22+b3*a32;out[7]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[8];b1=b[9];b2=b[10];b3=b[11];out[8]=b0*a00+b1*a10+b2*a20+b3*a30;out[9]=b0*a01+b1*a11+b2*a21+b3*a31;out[10]=b0*a02+b1*a12+b2*a22+b3*a32;out[11]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[12];b1=b[13];b2=b[14];b3=b[15];out[12]=b0*a00+b1*a10+b2*a20+b3*a30;out[13]=b0*a01+b1*a11+b2*a21+b3*a31;out[14]=b0*a02+b1*a12+b2*a22+b3*a32;out[15]=b0*a03+b1*a13+b2*a23+b3*a33;return out};mat4.translate=function(out,a,v){var x=v[0],y=v[1],z=v[2],a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;if(a===out){out[12]=a[0]*x+a[4]*y+a[8]*z+a[12];out[13]=a[1]*x+a[5]*y+a[9]*z+a[13];out[14]=a[2]*x+a[6]*y+a[10]*z+a[14];out[15]=a[3]*x+a[7]*y+a[11]*z+a[15]}else{a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a03;out[4]=a10;out[5]=a11;out[6]=a12;out[7]=a13;out[8]=a20;out[9]=a21;out[10]=a22;out[11]=a23;out[12]=a00*x+a10*y+a20*z+a[12];out[13]=a01*x+a11*y+a21*z+a[13];out[14]=a02*x+a12*y+a22*z+a[14];out[15]=a03*x+a13*y+a23*z+a[15]}return out};mat4.scale=function(out,a,v){var x=v[0],y=v[1],z=v[2];out[0]=a[0]*x;out[1]=a[1]*x;out[2]=a[2]*x;out[3]=a[3]*x;out[4]=a[4]*y;out[5]=a[5]*y;out[6]=a[6]*y;out[7]=a[7]*y;out[8]=a[8]*z;out[9]=a[9]*z;out[10]=a[10]*z;out[11]=a[11]*z;out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out};mat4.rotate=function(out,a,rad,axis){var x=axis[0],y=axis[1],z=axis[2],len=Math.sqrt(x*x+y*y+z*z),s,c,t,a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23,b00,b01,b02,b10,b11,b12,b20,b21,b22;if(Math.abs(len)<GLMAT_EPSILON){return null}len=1/len;x*=len;y*=len;z*=len;s=Math.sin(rad);c=Math.cos(rad);t=1-c;a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];b00=x*x*t+c;b01=y*x*t+z*s;b02=z*x*t-y*s;b10=x*y*t-z*s;b11=y*y*t+c;b12=z*y*t+x*s;b20=x*z*t+y*s;b21=y*z*t-x*s;b22=z*z*t+c;out[0]=a00*b00+a10*b01+a20*b02;out[1]=a01*b00+a11*b01+a21*b02;out[2]=a02*b00+a12*b01+a22*b02;out[3]=a03*b00+a13*b01+a23*b02;out[4]=a00*b10+a10*b11+a20*b12;out[5]=a01*b10+a11*b11+a21*b12;out[6]=a02*b10+a12*b11+a22*b12;out[7]=a03*b10+a13*b11+a23*b12;out[8]=a00*b20+a10*b21+a20*b22;out[9]=a01*b20+a11*b21+a21*b22;out[10]=a02*b20+a12*b21+a22*b22;out[11]=a03*b20+a13*b21+a23*b22;if(a!==out){out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}return out};mat4.rotateX=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}out[4]=a10*c+a20*s;out[5]=a11*c+a21*s;out[6]=a12*c+a22*s;out[7]=a13*c+a23*s;out[8]=a20*c-a10*s;out[9]=a21*c-a11*s;out[10]=a22*c-a12*s;out[11]=a23*c-a13*s;return out};mat4.rotateY=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}out[0]=a00*c-a20*s;out[1]=a01*c-a21*s;out[2]=a02*c-a22*s;out[3]=a03*c-a23*s;out[8]=a00*s+a20*c;out[9]=a01*s+a21*c;out[10]=a02*s+a22*c;out[11]=a03*s+a23*c;return out};mat4.rotateZ=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7];if(a!==out){out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}out[0]=a00*c+a10*s;out[1]=a01*c+a11*s;out[2]=a02*c+a12*s;out[3]=a03*c+a13*s;out[4]=a10*c-a00*s;out[5]=a11*c-a01*s;out[6]=a12*c-a02*s;out[7]=a13*c-a03*s;return out};mat4.fromRotationTranslation=function(out,q,v){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,xy=x*y2,xz=x*z2,yy=y*y2,yz=y*z2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-(yy+zz);out[1]=xy+wz;out[2]=xz-wy;out[3]=0;out[4]=xy-wz;out[5]=1-(xx+zz);out[6]=yz+wx;out[7]=0;out[8]=xz+wy;out[9]=yz-wx;out[10]=1-(xx+yy);out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out};mat4.frustum=function(out,left,right,bottom,top,near,far){var rl=1/(right-left),tb=1/(top-bottom),nf=1/(near-far);out[0]=near*2*rl;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=near*2*tb;out[6]=0;out[7]=0;out[8]=(right+left)*rl;out[9]=(top+bottom)*tb;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=far*near*2*nf;out[15]=0;return out};mat4.perspective=function(out,fovy,aspect,near,far){var f=1/Math.tan(fovy/2),nf=1/(near-far);out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=2*far*near*nf;out[15]=0;return out};mat4.ortho=function(out,left,right,bottom,top,near,far){var lr=1/(left-right),bt=1/(bottom-top),nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=2*nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=(far+near)*nf;out[15]=1;return out};mat4.lookAt=function(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len,eyex=eye[0],eyey=eye[1],eyez=eye[2],upx=up[0],upy=up[1],upz=up[2],centerx=center[0],centery=center[1],centerz=center[2];if(Math.abs(eyex-centerx)<GLMAT_EPSILON&&Math.abs(eyey-centery)<GLMAT_EPSILON&&Math.abs(eyez-centerz)<GLMAT_EPSILON){return mat4.identity(out)}z0=eyex-centerx;z1=eyey-centery;z2=eyez-centerz;len=1/Math.sqrt(z0*z0+z1*z1+z2*z2);z0*=len;z1*=len;z2*=len;x0=upy*z2-upz*z1;x1=upz*z0-upx*z2;x2=upx*z1-upy*z0;len=Math.sqrt(x0*x0+x1*x1+x2*x2);if(!len){x0=0;x1=0;x2=0}else{len=1/len;x0*=len;x1*=len;x2*=len}y0=z1*x2-z2*x1;y1=z2*x0-z0*x2;y2=z0*x1-z1*x0;len=Math.sqrt(y0*y0+y1*y1+y2*y2);if(!len){y0=0;y1=0;y2=0}else{len=1/len;y0*=len;y1*=len;y2*=len}out[0]=x0;out[1]=y0;out[2]=z0;out[3]=0;out[4]=x1;out[5]=y1;out[6]=z1;out[7]=0;out[8]=x2;out[9]=y2;out[10]=z2;out[11]=0;out[12]=-(x0*eyex+x1*eyey+x2*eyez);out[13]=-(y0*eyex+y1*eyey+y2*eyez);out[14]=-(z0*eyex+z1*eyey+z2*eyez);out[15]=1;return out};mat4.str=function(a){return"mat4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+")"};if(typeof exports!=="undefined"){exports.mat4=mat4}var quat={};var quatIdentity=new Float32Array([0,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}quat.create=function(){return new Float32Array(quatIdentity)};quat.clone=vec4.clone;quat.fromValues=vec4.fromValues;quat.copy=vec4.copy;quat.set=vec4.set;quat.identity=function(out){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out};quat.setAxisAngle=function(out,axis,rad){rad=rad*.5;var s=Math.sin(rad);out[0]=s*axis[0];out[1]=s*axis[1];out[2]=s*axis[2];out[3]=Math.cos(rad);return out};quat.add=vec4.add;quat.mul=quat.multiply=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out};quat.scale=vec4.scale;quat.rotateX=function(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out};quat.rotateY=function(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out};quat.rotateZ=function(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out};quat.calculateW=function(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=-Math.sqrt(Math.abs(1-x*x-y*y-z*z));return out};quat.dot=vec4.dot;quat.lerp=vec4.lerp;quat.slerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=a[3];var cosHalfTheta=ax*bx+ay*by+az*bz+aw*bw,halfTheta,sinHalfTheta,ratioA,ratioB;if(Math.abs(cosHalfTheta)>=1){if(out!==a){out[0]=ax;out[1]=ay;out[2]=az;out[3]=aw}return out}halfTheta=Math.acos(cosHalfTheta);sinHalfTheta=Math.sqrt(1-cosHalfTheta*cosHalfTheta);if(Math.abs(sinHalfTheta)<.001){out[0]=ax*.5+bx*.5;out[1]=ay*.5+by*.5;out[2]=az*.5+bz*.5;out[3]=aw*.5+bw*.5;return out}ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta;ratioB=Math.sin(t*halfTheta)/sinHalfTheta;out[0]=ax*ratioA+bx*ratioB;out[1]=ay*ratioA+by*ratioB;out[2]=az*ratioA+bz*ratioB;out[3]=aw*ratioA+bw*ratioB;return out};quat.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],dot=a0*a0+a1*a1+a2*a2+a3*a3,invDot=dot?1/dot:0;out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out};quat.conjugate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out};quat.len=quat.length=vec4.length;quat.sqrLen=quat.squaredLength=vec4.squaredLength;quat.normalize=vec4.normalize;quat.str=function(a){return"quat("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"};if(typeof exports!=="undefined"){exports.quat=quat}}(shim.exports)}()}()},{}],20:[function(require,module,exports){!function(){!function(){var root=this;var previousUnderscore=root._;var breaker={};var ArrayProto=Array.prototype,ObjProto=Object.prototype,FuncProto=Function.prototype;var push=ArrayProto.push,slice=ArrayProto.slice,concat=ArrayProto.concat,toString=ObjProto.toString,hasOwnProperty=ObjProto.hasOwnProperty;var nativeForEach=ArrayProto.forEach,nativeMap=ArrayProto.map,nativeReduce=ArrayProto.reduce,nativeReduceRight=ArrayProto.reduceRight,nativeFilter=ArrayProto.filter,nativeEvery=ArrayProto.every,nativeSome=ArrayProto.some,nativeIndexOf=ArrayProto.indexOf,nativeLastIndexOf=ArrayProto.lastIndexOf,nativeIsArray=Array.isArray,nativeKeys=Object.keys,nativeBind=FuncProto.bind;var _=function(obj){if(obj instanceof _)return obj;if(!(this instanceof _))return new _(obj);this._wrapped=obj};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=_}exports._=_}else{root._=_}_.VERSION="1.4.4";var each=_.each=_.forEach=function(obj,iterator,context){if(obj==null)return;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context)}else if(obj.length===+obj.length){for(var i=0,l=obj.length;i<l;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return}}else{for(var key in obj){if(_.has(obj,key)){if(iterator.call(context,obj[key],key,obj)===breaker)return}}}};_.map=_.collect=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeMap&&obj.map===nativeMap)return obj.map(iterator,context);each(obj,function(value,index,list){results[results.length]=iterator.call(context,value,index,list)});return results};var reduceError="Reduce of empty array with no initial value";_.reduce=_.foldl=_.inject=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduce&&obj.reduce===nativeReduce){if(context)iterator=_.bind(iterator,context);return initial?obj.reduce(iterator,memo):obj.reduce(iterator)}each(obj,function(value,index,list){if(!initial){memo=value;initial=true}else{memo=iterator.call(context,memo,value,index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.reduceRight=_.foldr=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduceRight&&obj.reduceRight===nativeReduceRight){if(context)iterator=_.bind(iterator,context);return initial?obj.reduceRight(iterator,memo):obj.reduceRight(iterator)}var length=obj.length;if(length!==+length){var keys=_.keys(obj);length=keys.length}each(obj,function(value,index,list){index=keys?keys[--length]:--length;if(!initial){memo=obj[index];initial=true}else{memo=iterator.call(context,memo,obj[index],index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.find=_.detect=function(obj,iterator,context){var result;any(obj,function(value,index,list){if(iterator.call(context,value,index,list)){result=value;return true}});return result};_.filter=_.select=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeFilter&&obj.filter===nativeFilter)return obj.filter(iterator,context);each(obj,function(value,index,list){if(iterator.call(context,value,index,list))results[results.length]=value});return results};_.reject=function(obj,iterator,context){return _.filter(obj,function(value,index,list){return!iterator.call(context,value,index,list)},context)};_.every=_.all=function(obj,iterator,context){iterator||(iterator=_.identity);var result=true;if(obj==null)return result;if(nativeEvery&&obj.every===nativeEvery)return obj.every(iterator,context);each(obj,function(value,index,list){if(!(result=result&&iterator.call(context,value,index,list)))return breaker});return!!result};var any=_.some=_.any=function(obj,iterator,context){iterator||(iterator=_.identity);var result=false;if(obj==null)return result;if(nativeSome&&obj.some===nativeSome)return obj.some(iterator,context);each(obj,function(value,index,list){if(result||(result=iterator.call(context,value,index,list)))return breaker});return!!result};_.contains=_.include=function(obj,target){if(obj==null)return false;if(nativeIndexOf&&obj.indexOf===nativeIndexOf)return obj.indexOf(target)!=-1;return any(obj,function(value){return value===target})};_.invoke=function(obj,method){var args=slice.call(arguments,2);var isFunc=_.isFunction(method);return _.map(obj,function(value){return(isFunc?method:value[method]).apply(value,args)})};_.pluck=function(obj,key){return _.map(obj,function(value){return value[key]})};_.where=function(obj,attrs,first){if(_.isEmpty(attrs))return first?null:[];return _[first?"find":"filter"](obj,function(value){for(var key in attrs){if(attrs[key]!==value[key])return false}return true})};_.findWhere=function(obj,attrs){return _.where(obj,attrs,true)};_.max=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.max.apply(Math,obj)}if(!iterator&&_.isEmpty(obj))return-Infinity;var result={computed:-Infinity,value:-Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed>=result.computed&&(result={value:value,computed:computed})});return result.value};_.min=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.min.apply(Math,obj)}if(!iterator&&_.isEmpty(obj))return Infinity;var result={computed:Infinity,value:Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed<result.computed&&(result={value:value,computed:computed})});return result.value};_.shuffle=function(obj){var rand;var index=0;var shuffled=[];each(obj,function(value){rand=_.random(index++);shuffled[index-1]=shuffled[rand];shuffled[rand]=value});return shuffled};var lookupIterator=function(value){return _.isFunction(value)?value:function(obj){return obj[value]}};_.sortBy=function(obj,value,context){var iterator=lookupIterator(value);return _.pluck(_.map(obj,function(value,index,list){return{value:value,index:index,criteria:iterator.call(context,value,index,list)}}).sort(function(left,right){var a=left.criteria;
var b=right.criteria;if(a!==b){if(a>b||a===void 0)return 1;if(a<b||b===void 0)return-1}return left.index<right.index?-1:1}),"value")};var group=function(obj,value,context,behavior){var result={};var iterator=lookupIterator(value||_.identity);each(obj,function(value,index){var key=iterator.call(context,value,index,obj);behavior(result,key,value)});return result};_.groupBy=function(obj,value,context){return group(obj,value,context,function(result,key,value){(_.has(result,key)?result[key]:result[key]=[]).push(value)})};_.countBy=function(obj,value,context){return group(obj,value,context,function(result,key){if(!_.has(result,key))result[key]=0;result[key]++})};_.sortedIndex=function(array,obj,iterator,context){iterator=iterator==null?_.identity:lookupIterator(iterator);var value=iterator.call(context,obj);var low=0,high=array.length;while(low<high){var mid=low+high>>>1;iterator.call(context,array[mid])<value?low=mid+1:high=mid}return low};_.toArray=function(obj){if(!obj)return[];if(_.isArray(obj))return slice.call(obj);if(obj.length===+obj.length)return _.map(obj,_.identity);return _.values(obj)};_.size=function(obj){if(obj==null)return 0;return obj.length===+obj.length?obj.length:_.keys(obj).length};_.first=_.head=_.take=function(array,n,guard){if(array==null)return void 0;return n!=null&&!guard?slice.call(array,0,n):array[0]};_.initial=function(array,n,guard){return slice.call(array,0,array.length-(n==null||guard?1:n))};_.last=function(array,n,guard){if(array==null)return void 0;if(n!=null&&!guard){return slice.call(array,Math.max(array.length-n,0))}else{return array[array.length-1]}};_.rest=_.tail=_.drop=function(array,n,guard){return slice.call(array,n==null||guard?1:n)};_.compact=function(array){return _.filter(array,_.identity)};var flatten=function(input,shallow,output){each(input,function(value){if(_.isArray(value)){shallow?push.apply(output,value):flatten(value,shallow,output)}else{output.push(value)}});return output};_.flatten=function(array,shallow){return flatten(array,shallow,[])};_.without=function(array){return _.difference(array,slice.call(arguments,1))};_.uniq=_.unique=function(array,isSorted,iterator,context){if(_.isFunction(isSorted)){context=iterator;iterator=isSorted;isSorted=false}var initial=iterator?_.map(array,iterator,context):array;var results=[];var seen=[];each(initial,function(value,index){if(isSorted?!index||seen[seen.length-1]!==value:!_.contains(seen,value)){seen.push(value);results.push(array[index])}});return results};_.union=function(){return _.uniq(concat.apply(ArrayProto,arguments))};_.intersection=function(array){var rest=slice.call(arguments,1);return _.filter(_.uniq(array),function(item){return _.every(rest,function(other){return _.indexOf(other,item)>=0})})};_.difference=function(array){var rest=concat.apply(ArrayProto,slice.call(arguments,1));return _.filter(array,function(value){return!_.contains(rest,value)})};_.zip=function(){var args=slice.call(arguments);var length=_.max(_.pluck(args,"length"));var results=new Array(length);for(var i=0;i<length;i++){results[i]=_.pluck(args,""+i)}return results};_.object=function(list,values){if(list==null)return{};var result={};for(var i=0,l=list.length;i<l;i++){if(values){result[list[i]]=values[i]}else{result[list[i][0]]=list[i][1]}}return result};_.indexOf=function(array,item,isSorted){if(array==null)return-1;var i=0,l=array.length;if(isSorted){if(typeof isSorted=="number"){i=isSorted<0?Math.max(0,l+isSorted):isSorted}else{i=_.sortedIndex(array,item);return array[i]===item?i:-1}}if(nativeIndexOf&&array.indexOf===nativeIndexOf)return array.indexOf(item,isSorted);for(;i<l;i++)if(array[i]===item)return i;return-1};_.lastIndexOf=function(array,item,from){if(array==null)return-1;var hasIndex=from!=null;if(nativeLastIndexOf&&array.lastIndexOf===nativeLastIndexOf){return hasIndex?array.lastIndexOf(item,from):array.lastIndexOf(item)}var i=hasIndex?from:array.length;while(i--)if(array[i]===item)return i;return-1};_.range=function(start,stop,step){if(arguments.length<=1){stop=start||0;start=0}step=arguments[2]||1;var len=Math.max(Math.ceil((stop-start)/step),0);var idx=0;var range=new Array(len);while(idx<len){range[idx++]=start;start+=step}return range};_.bind=function(func,context){if(func.bind===nativeBind&&nativeBind)return nativeBind.apply(func,slice.call(arguments,1));var args=slice.call(arguments,2);return function(){return func.apply(context,args.concat(slice.call(arguments)))}};_.partial=function(func){var args=slice.call(arguments,1);return function(){return func.apply(this,args.concat(slice.call(arguments)))}};_.bindAll=function(obj){var funcs=slice.call(arguments,1);if(funcs.length===0)funcs=_.functions(obj);each(funcs,function(f){obj[f]=_.bind(obj[f],obj)});return obj};_.memoize=function(func,hasher){var memo={};hasher||(hasher=_.identity);return function(){var key=hasher.apply(this,arguments);return _.has(memo,key)?memo[key]:memo[key]=func.apply(this,arguments)}};_.delay=function(func,wait){var args=slice.call(arguments,2);return setTimeout(function(){return func.apply(null,args)},wait)};_.defer=function(func){return _.delay.apply(_,[func,1].concat(slice.call(arguments,1)))};_.throttle=function(func,wait){var context,args,timeout,result;var previous=0;var later=function(){previous=new Date;timeout=null;result=func.apply(context,args)};return function(){var now=new Date;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args)}else if(!timeout){timeout=setTimeout(later,remaining)}return result}};_.debounce=function(func,wait,immediate){var timeout,result;return function(){var context=this,args=arguments;var later=function(){timeout=null;if(!immediate)result=func.apply(context,args)};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow)result=func.apply(context,args);return result}};_.once=function(func){var ran=false,memo;return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo}};_.wrap=function(func,wrapper){return function(){var args=[func];push.apply(args,arguments);return wrapper.apply(this,args)}};_.compose=function(){var funcs=arguments;return function(){var args=arguments;for(var i=funcs.length-1;i>=0;i--){args=[funcs[i].apply(this,args)]}return args[0]}};_.after=function(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}};_.keys=nativeKeys||function(obj){if(obj!==Object(obj))throw new TypeError("Invalid object");var keys=[];for(var key in obj)if(_.has(obj,key))keys[keys.length]=key;return keys};_.values=function(obj){var values=[];for(var key in obj)if(_.has(obj,key))values.push(obj[key]);return values};_.pairs=function(obj){var pairs=[];for(var key in obj)if(_.has(obj,key))pairs.push([key,obj[key]]);return pairs};_.invert=function(obj){var result={};for(var key in obj)if(_.has(obj,key))result[obj[key]]=key;return result};_.functions=_.methods=function(obj){var names=[];for(var key in obj){if(_.isFunction(obj[key]))names.push(key)}return names.sort()};_.extend=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){obj[prop]=source[prop]}}});return obj};_.pick=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));each(keys,function(key){if(key in obj)copy[key]=obj[key]});return copy};_.omit=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));for(var key in obj){if(!_.contains(keys,key))copy[key]=obj[key]}return copy};_.defaults=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){if(obj[prop]==null)obj[prop]=source[prop]}}});return obj};_.clone=function(obj){if(!_.isObject(obj))return obj;return _.isArray(obj)?obj.slice():_.extend({},obj)};_.tap=function(obj,interceptor){interceptor(obj);return obj};var eq=function(a,b,aStack,bStack){if(a===b)return a!==0||1/a==1/b;if(a==null||b==null)return a===b;if(a instanceof _)a=a._wrapped;if(b instanceof _)b=b._wrapped;var className=toString.call(a);if(className!=toString.call(b))return false;switch(className){case"[object String]":return a==String(b);case"[object Number]":return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case"[object Date]":case"[object Boolean]":return+a==+b;case"[object RegExp]":return a.source==b.source&&a.global==b.global&&a.multiline==b.multiline&&a.ignoreCase==b.ignoreCase}if(typeof a!="object"||typeof b!="object")return false;var length=aStack.length;while(length--){if(aStack[length]==a)return bStack[length]==b}aStack.push(a);bStack.push(b);var size=0,result=true;if(className=="[object Array]"){size=a.length;result=size==b.length;if(result){while(size--){if(!(result=eq(a[size],b[size],aStack,bStack)))break}}}else{var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&aCtor instanceof aCtor&&_.isFunction(bCtor)&&bCtor instanceof bCtor)){return false}for(var key in a){if(_.has(a,key)){size++;if(!(result=_.has(b,key)&&eq(a[key],b[key],aStack,bStack)))break}}if(result){for(key in b){if(_.has(b,key)&&!size--)break}result=!size}}aStack.pop();bStack.pop();return result};_.isEqual=function(a,b){return eq(a,b,[],[])};_.isEmpty=function(obj){if(obj==null)return true;if(_.isArray(obj)||_.isString(obj))return obj.length===0;for(var key in obj)if(_.has(obj,key))return false;return true};_.isElement=function(obj){return!!(obj&&obj.nodeType===1)};_.isArray=nativeIsArray||function(obj){return toString.call(obj)=="[object Array]"};_.isObject=function(obj){return obj===Object(obj)};each(["Arguments","Function","String","Number","Date","RegExp"],function(name){_["is"+name]=function(obj){return toString.call(obj)=="[object "+name+"]"}});if(!_.isArguments(arguments)){_.isArguments=function(obj){return!!(obj&&_.has(obj,"callee"))}}if(typeof/./!=="function"){_.isFunction=function(obj){return typeof obj==="function"}}_.isFinite=function(obj){return isFinite(obj)&&!isNaN(parseFloat(obj))};_.isNaN=function(obj){return _.isNumber(obj)&&obj!=+obj};_.isBoolean=function(obj){return obj===true||obj===false||toString.call(obj)=="[object Boolean]"};_.isNull=function(obj){return obj===null};_.isUndefined=function(obj){return obj===void 0};_.has=function(obj,key){return hasOwnProperty.call(obj,key)};_.noConflict=function(){root._=previousUnderscore;return this};_.identity=function(value){return value};_.times=function(n,iterator,context){var accum=Array(n);for(var i=0;i<n;i++)accum[i]=iterator.call(context,i);return accum};_.random=function(min,max){if(max==null){max=min;min=0}return min+Math.floor(Math.random()*(max-min+1))};var entityMap={escape:{"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"}};entityMap.unescape=_.invert(entityMap.escape);var entityRegexes={escape:new RegExp("["+_.keys(entityMap.escape).join("")+"]","g"),unescape:new RegExp("("+_.keys(entityMap.unescape).join("|")+")","g")};_.each(["escape","unescape"],function(method){_[method]=function(string){if(string==null)return"";return(""+string).replace(entityRegexes[method],function(match){return entityMap[method][match]})}});_.result=function(object,property){if(object==null)return null;var value=object[property];return _.isFunction(value)?value.call(object):value};_.mixin=function(obj){each(_.functions(obj),function(name){var func=_[name]=obj[name];_.prototype[name]=function(){var args=[this._wrapped];push.apply(args,arguments);return result.call(this,func.apply(_,args))}})};var idCounter=0;_.uniqueId=function(prefix){var id=++idCounter+"";return prefix?prefix+id:id};_.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var noMatch=/(.)^/;var escapes={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"};var escaper=/\\|'|\r|\n|\t|\u2028|\u2029/g;_.template=function(text,data,settings){var render;settings=_.defaults({},settings,_.templateSettings);var matcher=new RegExp([(settings.escape||noMatch).source,(settings.interpolate||noMatch).source,(settings.evaluate||noMatch).source].join("|")+"|$","g");var index=0;var source="__p+='";text.replace(matcher,function(match,escape,interpolate,evaluate,offset){source+=text.slice(index,offset).replace(escaper,function(match){return"\\"+escapes[match]});if(escape){source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'"}if(interpolate){source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'"}if(evaluate){source+="';\n"+evaluate+"\n__p+='"}index=offset+match.length;return match});source+="';\n";if(!settings.variable)source="with(obj||{}){\n"+source+"}\n";source="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+source+"return __p;\n";try{render=new Function(settings.variable||"obj","_",source)}catch(e){e.source=source;throw e}if(data)return render(data,_);var template=function(data){return render.call(this,data,_)};template.source="function("+(settings.variable||"obj")+"){\n"+source+"}";return template};_.chain=function(obj){return _(obj).chain()};var result=function(obj){return this._chain?_(obj).chain():obj};_.mixin(_);each(["pop","push","reverse","shift","sort","splice","unshift"],function(name){var method=ArrayProto[name];_.prototype[name]=function(){var obj=this._wrapped;method.apply(obj,arguments);if((name=="shift"||name=="splice")&&obj.length===0)delete obj[0];return result.call(this,obj)}});each(["concat","join","slice"],function(name){var method=ArrayProto[name];_.prototype[name]=function(){return result.call(this,method.apply(this._wrapped,arguments))}});_.extend(_.prototype,{chain:function(){this._chain=true;return this},value:function(){return this._wrapped}})}.call(this)}()},{}],21:[function(require,module,exports){window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1e3/60)}}();Leap=require("../lib/index")},{"../lib/index":8}]},{},[21]);
/*
* Leap Motion integration for Reveal.js.
* James Sun [sun16]
* Rory Hardy [gneatgeek]
*/
(function () {
var body = document.body,
controller = new Leap.Controller({ enableGestures: true }),
lastGesture = 0,
leapConfig = Reveal.getConfig().leap,
pointer = document.createElement( 'div' ),
config = {
autoCenter : true, // Center pointer around detected position.
gestureDelay : 500, // How long to delay between gestures.
naturalSwipe : true, // Swipe as if it were a touch screen.
pointerColor : '#00aaff', // Default color of the pointer.
pointerOpacity : 0.7, // Default opacity of the pointer.
pointerSize : 15, // Default minimum height/width of the pointer.
pointerTolerance : 120 // Bigger = slower pointer.
},
entered, enteredPosition, now, size, tipPosition; // Other vars we need later, but don't need to redeclare.
// Merge user defined settings with defaults
if( leapConfig ) {
for( key in leapConfig ) {
config[key] = leapConfig[key];
}
}
pointer.id = 'leap';
pointer.style.position = 'absolute';
pointer.style.visibility = 'hidden';
pointer.style.zIndex = 50;
pointer.style.opacity = config.pointerOpacity;
pointer.style.backgroundColor = config.pointerColor;
body.appendChild( pointer );
// Leap's loop
controller.on( 'frame', function ( frame ) {
// Timing code to rate limit gesture execution
now = new Date().getTime();
// Pointer: 1 to 2 fingers. Strictly one finger works but may cause innaccuracies.
// The innaccuracies were observed on a development model and may not be an issue with consumer models.
if( frame.fingers.length > 0 && frame.fingers.length < 3 ) {
// Invert direction and multiply by 3 for greater effect.
size = -3 * frame.fingers[0].tipPosition[2];
if( size < config.pointerSize ) {
size = config.pointerSize;
}
pointer.style.width = size + 'px';
pointer.style.height = size + 'px';
pointer.style.borderRadius = size - 5 + 'px';
pointer.style.visibility = 'visible';
if( config.autoCenter ) {
tipPosition = frame.fingers[0].tipPosition;
// Check whether the finger has entered the z range of the Leap Motion. Used for the autoCenter option.
if( !entered ) {
entered = true;
enteredPosition = frame.fingers[0].tipPosition;
}
pointer.style.top =
(-1 * (( tipPosition[1] - enteredPosition[1] ) * body.offsetHeight / config.pointerTolerance )) +
( body.offsetHeight / 2 ) + 'px';
pointer.style.left =
(( tipPosition[0] - enteredPosition[0] ) * body.offsetWidth / config.pointerTolerance ) +
( body.offsetWidth / 2 ) + 'px';
}
else {
pointer.style.top = ( 1 - (( tipPosition[1] - 50) / config.pointerTolerance )) *
body.offsetHeight + 'px';
pointer.style.left = ( tipPosition[0] * body.offsetWidth / config.pointerTolerance ) +
( body.offsetWidth / 2 ) + 'px';
}
}
else {
// Hide pointer on exit
entered = false;
pointer.style.visibility = 'hidden';
}
// Gestures
if( frame.gestures.length > 0 && (now - lastGesture) > config.gestureDelay ) {
var gesture = frame.gestures[0];
// One hand gestures
if( frame.hands.length === 1 ) {
// Swipe gestures. 3+ fingers.
if( frame.fingers.length > 2 && gesture.type === 'swipe' ) {
// Define here since some gestures will throw undefined for these.
var x = gesture.direction[0],
y = gesture.direction[1];
// Left/right swipe gestures
if( Math.abs( x ) > Math.abs( y )) {
if( x > 0 ) {
config.naturalSwipe ? Reveal.left() : Reveal.right();
}
else {
config.naturalSwipe ? Reveal.right() : Reveal.left();
}
}
// Up/down swipe gestures
else {
if( y > 0 ) {
config.naturalSwipe ? Reveal.down() : Reveal.up();
}
else {
config.naturalSwipe ? Reveal.up() : Reveal.down();
}
}
lastGesture = now;
}
}
// Two hand gestures
else if( frame.hands.length === 2 ) {
// Upward two hand swipe gesture
if( gesture.direction[1] > 0 && gesture.type === 'swipe' ) {
Reveal.toggleOverview();
}
lastGesture = now;
}
}
});
controller.connect();
})();
| zhurni-man/innoprez | plugin/leap/leap.js | JavaScript | mit | 84,420 |
/*
* Copyright (c) 2013, Leap Motion, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Version 0.2.0 - http://js.leapmotion.com/0.2.0/leap.min.js
* Grab latest versions from http://js.leapmotion.com/
*/
!function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i}({1:[function(require,module,exports){var chooseProtocol=require("./protocol").chooseProtocol,EventEmitter=require("events").EventEmitter,_=require("underscore");var BaseConnection=module.exports=function(opts){this.opts=_.defaults(opts||{},{host:"127.0.0.1",enableGestures:false,port:6437,enableHeartbeat:true,heartbeatInterval:100,requestProtocolVersion:3});this.host=opts.host;this.port=opts.port;this.on("ready",function(){this.enableGestures(this.opts.enableGestures);if(this.opts.enableHeartbeat)this.startHeartbeat()});this.on("disconnect",function(){if(this.opts.enableHeartbeat)this.stopHeartbeat()});this.heartbeatTimer=null};BaseConnection.prototype.getUrl=function(){return"ws://"+this.host+":"+this.port+"/v"+this.opts.requestProtocolVersion+".json"};BaseConnection.prototype.sendHeartbeat=function(){if(this.protocol){this.setHeartbeatState(true);this.protocol.sendHeartbeat(this)}};BaseConnection.prototype.handleOpen=function(){this.emit("connect")};BaseConnection.prototype.enableGestures=function(enabled){this.gesturesEnabled=enabled?true:false;this.send(this.protocol.encode({enableGestures:this.gesturesEnabled}))};BaseConnection.prototype.handleClose=function(){this.disconnect();this.startReconnection()};BaseConnection.prototype.startReconnection=function(){var connection=this;setTimeout(function(){connection.connect()},1e3)};BaseConnection.prototype.disconnect=function(){if(!this.socket)return;this.socket.close();delete this.socket;delete this.protocol;this.emit("disconnect")};BaseConnection.prototype.handleData=function(data){var message=JSON.parse(data);var messageEvent;if(this.protocol===undefined){messageEvent=this.protocol=chooseProtocol(message);this.emit("ready")}else{messageEvent=this.protocol(message)}this.emit(messageEvent.type,messageEvent)};BaseConnection.prototype.connect=function(){if(this.socket)return;this.socket=this.setupSocket();return true};BaseConnection.prototype.send=function(data){this.socket.send(data)};BaseConnection.prototype.stopHeartbeat=function(){if(!this.heartbeatTimer)return;clearInterval(this.heartbeatTimer);delete this.heartbeatTimer;this.setHeartbeatState(false)};BaseConnection.prototype.setHeartbeatState=function(state){if(this.heartbeatState===state)return;this.heartbeatState=state;this.emit(this.heartbeatState?"focus":"blur")};_.extend(BaseConnection.prototype,EventEmitter.prototype)},{"./protocol":12,events:17,underscore:20}],2:[function(require,module,exports){var CircularBuffer=module.exports=function(size){this.pos=0;this._buf=[];this.size=size};CircularBuffer.prototype.get=function(i){if(i==undefined)i=0;if(i>=this.size)return undefined;if(i>=this._buf.length)return undefined;return this._buf[(this.pos-i-1)%this.size]};CircularBuffer.prototype.push=function(o){this._buf[this.pos%this.size]=o;return this.pos++}},{}],3:[function(require,module,exports){var Connection=module.exports=require("./base_connection");Connection.prototype.setupSocket=function(){var connection=this;var socket=new WebSocket(this.getUrl());socket.onopen=function(){connection.handleOpen()};socket.onmessage=function(message){connection.handleData(message.data)};socket.onclose=function(){connection.handleClose()};return socket};Connection.prototype.startHeartbeat=function(){if(!this.protocol.sendHeartbeat||this.heartbeatTimer)return;var connection=this;var propertyName=null;if(typeof document.hidden!=="undefined"){propertyName="hidden"}else if(typeof document.mozHidden!=="undefined"){propertyName="mozHidden"}else if(typeof document.msHidden!=="undefined"){propertyName="msHidden"}else if(typeof document.webkitHidden!=="undefined"){propertyName="webkitHidden"}else{propertyName=undefined}var windowVisible=true;var focusListener=window.addEventListener("focus",function(e){windowVisible=true});var blurListener=window.addEventListener("blur",function(e){windowVisible=false});this.on("disconnect",function(){if(connection.heartbeatTimer){clearTimeout(connection.heartbeatTimer);delete connection.heartbeatTimer}window.removeEventListener(focusListener);window.removeEventListener(blurListener)});this.heartbeatTimer=setInterval(function(){var isVisible=propertyName===undefined?true:document[propertyName]===false;if(isVisible&&windowVisible){connection.sendHeartbeat()}else{connection.setHeartbeatState(false)}},this.opts.heartbeatInterval)}},{"./base_connection":1}],4:[function(require,module,exports){!function(process){var Frame=require("./frame"),CircularBuffer=require("./circular_buffer"),Pipeline=require("./pipeline"),EventEmitter=require("events").EventEmitter,gestureListener=require("./gesture").gestureListener,_=require("underscore");var Controller=module.exports=function(opts){var inNode=typeof process!=="undefined"&&process.title==="node";opts=_.defaults(opts||{},{inNode:inNode});this.inNode=opts.inNode;opts=_.defaults(opts||{},{frameEventName:this.useAnimationLoop()?"animationFrame":"deviceFrame",supressAnimationLoop:false});this.supressAnimationLoop=opts.supressAnimationLoop;this.frameEventName=opts.frameEventName;this.history=new CircularBuffer(200);this.lastFrame=Frame.Invalid;this.lastValidFrame=Frame.Invalid;this.lastConnectionFrame=Frame.Invalid;this.accumulatedGestures=[];if(opts.connectionType===undefined){this.connectionType=this.inBrowser()?require("./connection"):require("./node_connection")}else{this.connectionType=opts.connectionType}this.connection=new this.connectionType(opts);this.setupConnectionEvents()};Controller.prototype.gesture=function(type,cb){var creator=gestureListener(this,type);if(cb!==undefined){creator.stop(cb)}return creator};Controller.prototype.inBrowser=function(){return!this.inNode};Controller.prototype.useAnimationLoop=function(){return this.inBrowser()&&typeof chrome==="undefined"};Controller.prototype.connect=function(){var controller=this;if(this.connection.connect()&&this.inBrowser()&&!controller.supressAnimationLoop){var callback=function(){controller.emit("animationFrame",controller.lastConnectionFrame);window.requestAnimFrame(callback)};window.requestAnimFrame(callback)}};Controller.prototype.disconnect=function(){this.connection.disconnect()};Controller.prototype.frame=function(num){return this.history.get(num)||Frame.Invalid};Controller.prototype.loop=function(callback){switch(callback.length){case 1:this.on(this.frameEventName,callback);break;case 2:var controller=this;var scheduler=null;var immediateRunnerCallback=function(frame){callback(frame,function(){if(controller.lastFrame!=frame){immediateRunnerCallback(controller.lastFrame)}else{controller.once(controller.frameEventName,immediateRunnerCallback)}})};this.once(this.frameEventName,immediateRunnerCallback);break}this.connect()};Controller.prototype.addStep=function(step){if(!this.pipeline)this.pipeline=new Pipeline(this);this.pipeline.addStep(step)};Controller.prototype.processFrame=function(frame){if(frame.gestures){this.accumulatedGestures=this.accumulatedGestures.concat(frame.gestures)}if(this.pipeline){frame=this.pipeline.run(frame);if(!frame)frame=Frame.Invalid}this.lastConnectionFrame=frame;this.emit("deviceFrame",frame)};Controller.prototype.processFinishedFrame=function(frame){this.lastFrame=frame;if(frame.valid){this.lastValidFrame=frame}frame.controller=this;frame.historyIdx=this.history.push(frame);if(frame.gestures){frame.gestures=this.accumulatedGestures;this.accumulatedGestures=[];for(var gestureIdx=0;gestureIdx!=frame.gestures.length;gestureIdx++){this.emit("gesture",frame.gestures[gestureIdx],frame)}}this.emit("frame",frame)};Controller.prototype.setupConnectionEvents=function(){var controller=this;this.connection.on("frame",function(frame){controller.processFrame(frame)});this.on(this.frameEventName,function(frame){controller.processFinishedFrame(frame)});this.connection.on("disconnect",function(){controller.emit("disconnect")});this.connection.on("ready",function(){controller.emit("ready")});this.connection.on("connect",function(){controller.emit("connect")});this.connection.on("focus",function(){controller.emit("focus")});this.connection.on("blur",function(){controller.emit("blur")});this.connection.on("protocol",function(protocol){controller.emit("protocol",protocol)});this.connection.on("deviceConnect",function(evt){controller.emit(evt.state?"deviceConnected":"deviceDisconnected")})};_.extend(Controller.prototype,EventEmitter.prototype)}(require("__browserify_process"))},{"./circular_buffer":2,"./connection":3,"./frame":5,"./gesture":6,"./node_connection":16,"./pipeline":10,__browserify_process:18,events:17,underscore:20}],5:[function(require,module,exports){var Hand=require("./hand"),Pointable=require("./pointable"),createGesture=require("./gesture").createGesture,glMatrix=require("gl-matrix"),mat3=glMatrix.mat3,vec3=glMatrix.vec3,InteractionBox=require("./interaction_box"),_=require("underscore");var Frame=module.exports=function(data){this.valid=true;this.id=data.id;this.timestamp=data.timestamp;this.hands=[];this.handsMap={};this.pointables=[];this.tools=[];this.fingers=[];if(data.interactionBox){this.interactionBox=new InteractionBox(data.interactionBox)}this.gestures=[];this.pointablesMap={};this._translation=data.t;this._rotation=_.flatten(data.r);this._scaleFactor=data.s;this.data=data;this.type="frame";this.currentFrameRate=data.currentFrameRate;var handMap={};for(var handIdx=0,handCount=data.hands.length;handIdx!=handCount;handIdx++){var hand=new Hand(data.hands[handIdx]);hand.frame=this;this.hands.push(hand);this.handsMap[hand.id]=hand;handMap[hand.id]=handIdx}for(var pointableIdx=0,pointableCount=data.pointables.length;pointableIdx!=pointableCount;pointableIdx++){var pointable=new Pointable(data.pointables[pointableIdx]);pointable.frame=this;this.pointables.push(pointable);this.pointablesMap[pointable.id]=pointable;(pointable.tool?this.tools:this.fingers).push(pointable);if(pointable.handId!==undefined&&handMap.hasOwnProperty(pointable.handId)){var hand=this.hands[handMap[pointable.handId]];hand.pointables.push(pointable);(pointable.tool?hand.tools:hand.fingers).push(pointable)}}if(data.gestures){for(var gestureIdx=0,gestureCount=data.gestures.length;gestureIdx!=gestureCount;gestureIdx++){this.gestures.push(createGesture(data.gestures[gestureIdx]))}}};Frame.prototype.tool=function(id){var pointable=this.pointable(id);return pointable.tool?pointable:Pointable.Invalid};Frame.prototype.pointable=function(id){return this.pointablesMap[id]||Pointable.Invalid};Frame.prototype.finger=function(id){var pointable=this.pointable(id);return!pointable.tool?pointable:Pointable.Invalid};Frame.prototype.hand=function(id){return this.handsMap[id]||Hand.Invalid};Frame.prototype.rotationAngle=function(sinceFrame,axis){if(!this.valid||!sinceFrame.valid)return 0;var rot=this.rotationMatrix(sinceFrame);var cs=(rot[0]+rot[4]+rot[8]-1)*.5;var angle=Math.acos(cs);angle=isNaN(angle)?0:angle;if(axis!==undefined){var rotAxis=this.rotationAxis(sinceFrame);angle*=vec3.dot(rotAxis,vec3.normalize(vec3.create(),axis))}return angle};Frame.prototype.rotationAxis=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();return vec3.normalize(vec3.create(),[this._rotation[7]-sinceFrame._rotation[5],this._rotation[2]-sinceFrame._rotation[6],this._rotation[3]-sinceFrame._rotation[1]])};Frame.prototype.rotationMatrix=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return mat3.create();var transpose=mat3.transpose(mat3.create(),this._rotation);return mat3.multiply(mat3.create(),sinceFrame._rotation,transpose)};Frame.prototype.scaleFactor=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return 1;return Math.exp(this._scaleFactor-sinceFrame._scaleFactor)};Frame.prototype.translation=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();return vec3.subtract(vec3.create(),this._translation,sinceFrame._translation)};Frame.prototype.toString=function(){var str="Frame [ id:"+this.id+" | timestamp:"+this.timestamp+" | Hand count:("+this.hands.length+") | Pointable count:("+this.pointables.length+")";if(this.gestures)str+=" | Gesture count:("+this.gestures.length+")";str+=" ]";return str};Frame.prototype.dump=function(){var out="";out+="Frame Info:<br/>";out+=this.toString();out+="<br/><br/>Hands:<br/>";for(var handIdx=0,handCount=this.hands.length;handIdx!=handCount;handIdx++){out+=" "+this.hands[handIdx].toString()+"<br/>"}out+="<br/><br/>Pointables:<br/>";for(var pointableIdx=0,pointableCount=this.pointables.length;pointableIdx!=pointableCount;pointableIdx++){out+=" "+this.pointables[pointableIdx].toString()+"<br/>"}if(this.gestures){out+="<br/><br/>Gestures:<br/>";for(var gestureIdx=0,gestureCount=this.gestures.length;gestureIdx!=gestureCount;gestureIdx++){out+=" "+this.gestures[gestureIdx].toString()+"<br/>"}}out+="<br/><br/>Raw JSON:<br/>";out+=JSON.stringify(this.data);return out};Frame.Invalid={valid:false,hands:[],fingers:[],tools:[],gestures:[],pointables:[],pointable:function(){return Pointable.Invalid},finger:function(){return Pointable.Invalid},hand:function(){return Hand.Invalid},toString:function(){return"invalid frame"},dump:function(){return this.toString()},rotationAngle:function(){return 0},rotationMatrix:function(){return mat3.create()},rotationAxis:function(){return vec3.create()},scaleFactor:function(){return 1},translation:function(){return vec3.create()}}},{"./gesture":6,"./hand":7,"./interaction_box":9,"./pointable":11,"gl-matrix":19,underscore:20}],6:[function(require,module,exports){var glMatrix=require("gl-matrix"),vec3=glMatrix.vec3,EventEmitter=require("events").EventEmitter,_=require("underscore");var createGesture=exports.createGesture=function(data){var gesture;switch(data.type){case"circle":gesture=new CircleGesture(data);break;case"swipe":gesture=new SwipeGesture(data);break;case"screenTap":gesture=new ScreenTapGesture(data);break;case"keyTap":gesture=new KeyTapGesture(data);break;default:throw"unkown gesture type"}gesture.id=data.id;gesture.handIds=data.handIds;gesture.pointableIds=data.pointableIds;gesture.duration=data.duration;gesture.state=data.state;gesture.type=data.type;return gesture};var gestureListener=exports.gestureListener=function(controller,type){var handlers={};var gestureMap={};var gestureCreator=function(){var candidateGesture=gestureMap[gesture.id];if(candidateGesture!==undefined)gesture.update(gesture,frame);if(gesture.state=="start"||gesture.state=="stop"){if(type==gesture.type&&gestureMap[gesture.id]===undefined){gestureMap[gesture.id]=new Gesture(gesture,frame);gesture.update(gesture,frame)}if(gesture.state=="stop"){delete gestureMap[gesture.id]}}};controller.on("gesture",function(gesture,frame){if(gesture.type==type){if(gesture.state=="start"||gesture.state=="stop"){if(gestureMap[gesture.id]===undefined){var gestureTracker=new Gesture(gesture,frame);gestureMap[gesture.id]=gestureTracker;_.each(handlers,function(cb,name){gestureTracker.on(name,cb)})}}gestureMap[gesture.id].update(gesture,frame);if(gesture.state=="stop"){delete gestureMap[gesture.id]}}});var builder={start:function(cb){handlers["start"]=cb;return builder},stop:function(cb){handlers["stop"]=cb;return builder},complete:function(cb){handlers["stop"]=cb;return builder},update:function(cb){handlers["update"]=cb;return builder}};return builder};var Gesture=exports.Gesture=function(gesture,frame){this.gestures=[gesture];this.frames=[frame]};Gesture.prototype.update=function(gesture,frame){this.gestures.push(gesture);this.frames.push(frame);this.emit(gesture.state,this)};_.extend(Gesture.prototype,EventEmitter.prototype);var CircleGesture=function(data){this.center=data.center;this.normal=data.normal;this.progress=data.progress;this.radius=data.radius};CircleGesture.prototype.toString=function(){return"CircleGesture ["+JSON.stringify(this)+"]"};var SwipeGesture=function(data){this.startPosition=data.startPosition;this.position=data.position;this.direction=data.direction;this.speed=data.speed};SwipeGesture.prototype.toString=function(){return"SwipeGesture ["+JSON.stringify(this)+"]"};var ScreenTapGesture=function(data){this.position=data.position;this.direction=data.direction;this.progress=data.progress};ScreenTapGesture.prototype.toString=function(){return"ScreenTapGesture ["+JSON.stringify(this)+"]"};var KeyTapGesture=function(data){this.position=data.position;this.direction=data.direction;this.progress=data.progress};KeyTapGesture.prototype.toString=function(){return"KeyTapGesture ["+JSON.stringify(this)+"]"}},{events:17,"gl-matrix":19,underscore:20}],7:[function(require,module,exports){var Pointable=require("./pointable"),glMatrix=require("gl-matrix"),mat3=glMatrix.mat3,vec3=glMatrix.vec3,_=require("underscore");var Hand=module.exports=function(data){this.id=data.id;this.palmPosition=data.palmPosition;this.direction=data.direction;this.palmVelocity=data.palmVelocity;this.palmNormal=data.palmNormal;this.sphereCenter=data.sphereCenter;this.sphereRadius=data.sphereRadius;this.valid=true;this.pointables=[];this.fingers=[];this.tools=[];this._translation=data.t;this._rotation=_.flatten(data.r);this._scaleFactor=data.s;this.timeVisible=data.timeVisible;this.stabilizedPalmPosition=data.stabilizedPalmPosition};Hand.prototype.finger=function(id){var finger=this.frame.finger(id);return finger&&finger.handId==this.id?finger:Pointable.Invalid};Hand.prototype.rotationAngle=function(sinceFrame,axis){if(!this.valid||!sinceFrame.valid)return 0;var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return 0;var rot=this.rotationMatrix(sinceFrame);var cs=(rot[0]+rot[4]+rot[8]-1)*.5;var angle=Math.acos(cs);angle=isNaN(angle)?0:angle;if(axis!==undefined){var rotAxis=this.rotationAxis(sinceFrame);angle*=vec3.dot(rotAxis,vec3.normalize(vec3.create(),axis))}return angle};Hand.prototype.rotationAxis=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return vec3.create();return vec3.normalize(vec3.create(),[this._rotation[7]-sinceHand._rotation[5],this._rotation[2]-sinceHand._rotation[6],this._rotation[3]-sinceHand._rotation[1]])};Hand.prototype.rotationMatrix=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return mat3.create();var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return mat3.create();var transpose=mat3.transpose(mat3.create(),this._rotation);var m=mat3.multiply(mat3.create(),sinceHand._rotation,transpose);return m};Hand.prototype.scaleFactor=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return 1;var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return 1;return Math.exp(this._scaleFactor-sinceHand._scaleFactor)};Hand.prototype.translation=function(sinceFrame){if(!this.valid||!sinceFrame.valid)return vec3.create();var sinceHand=sinceFrame.hand(this.id);if(!sinceHand.valid)return vec3.create();return[this._translation[0]-sinceHand._translation[0],this._translation[1]-sinceHand._translation[1],this._translation[2]-sinceHand._translation[2]]};Hand.prototype.toString=function(){return"Hand [ id: "+this.id+" | palm velocity:"+this.palmVelocity+" | sphere center:"+this.sphereCenter+" ] "};Hand.Invalid={valid:false,fingers:[],tools:[],pointables:[],pointable:function(){return Pointable.Invalid},finger:function(){return Pointable.Invalid},toString:function(){return"invalid frame"},dump:function(){return this.toString()},rotationAngle:function(){return 0},rotationMatrix:function(){return mat3.create()},rotationAxis:function(){return vec3.create()},scaleFactor:function(){return 1},translation:function(){return vec3.create()}}},{"./pointable":11,"gl-matrix":19,underscore:20}],8:[function(require,module,exports){!function(){module.exports={Controller:require("./controller"),Frame:require("./frame"),Gesture:require("./gesture"),Hand:require("./hand"),Pointable:require("./pointable"),InteractionBox:require("./interaction_box"),Connection:require("./connection"),CircularBuffer:require("./circular_buffer"),UI:require("./ui"),glMatrix:require("gl-matrix"),mat3:require("gl-matrix").mat3,vec3:require("gl-matrix").vec3,loopController:undefined,loop:function(opts,callback){if(callback===undefined){callback=opts;opts={}}if(!this.loopController)this.loopController=new this.Controller(opts);this.loopController.loop(callback)}}}()},{"./circular_buffer":2,"./connection":3,"./controller":4,"./frame":5,"./gesture":6,"./hand":7,"./interaction_box":9,"./pointable":11,"./ui":13,"gl-matrix":19}],9:[function(require,module,exports){var glMatrix=require("gl-matrix"),vec3=glMatrix.vec3;var InteractionBox=module.exports=function(data){this.valid=true;this.center=data.center;this.size=data.size;this.width=data.size[0];this.height=data.size[1];this.depth=data.size[2]};InteractionBox.prototype.denormalizePoint=function(normalizedPosition){return vec3.fromValues((normalizedPosition[0]-.5)*this.size[0]+this.center[0],(normalizedPosition[1]-.5)*this.size[1]+this.center[1],(normalizedPosition[2]-.5)*this.size[2]+this.center[2])};InteractionBox.prototype.normalizePoint=function(position,clamp){var vec=vec3.fromValues((position[0]-this.center[0])/this.size[0]+.5,(position[1]-this.center[1])/this.size[1]+.5,(position[2]-this.center[2])/this.size[2]+.5);if(clamp){vec[0]=Math.min(Math.max(vec[0],0),1);vec[1]=Math.min(Math.max(vec[1],0),1);vec[2]=Math.min(Math.max(vec[2],0),1)}return vec};InteractionBox.prototype.toString=function(){return"InteractionBox [ width:"+this.width+" | height:"+this.height+" | depth:"+this.depth+" ]"};InteractionBox.Invalid={valid:false}},{"gl-matrix":19}],10:[function(require,module,exports){var Pipeline=module.exports=function(){this.steps=[]};Pipeline.prototype.addStep=function(step){this.steps.push(step)};Pipeline.prototype.run=function(frame){var stepsLength=this.steps.length;for(var i=0;i!=stepsLength;i++){if(!frame)break;frame=this.steps[i](frame)}return frame}},{}],11:[function(require,module,exports){var glMatrix=require("gl-matrix"),vec3=glMatrix.vec3;var Pointable=module.exports=function(data){this.valid=true;this.id=data.id;this.handId=data.handId;this.length=data.length;this.tool=data.tool;this.width=data.width;this.direction=data.direction;this.stabilizedTipPosition=data.stabilizedTipPosition;this.tipPosition=data.tipPosition;this.tipVelocity=data.tipVelocity;this.touchZone=data.touchZone;this.touchDistance=data.touchDistance;this.timeVisible=data.timeVisible};Pointable.prototype.toString=function(){if(this.tool==true){return"Pointable [ id:"+this.id+" "+this.length+"mmx | with:"+this.width+"mm | direction:"+this.direction+" ]"}else{return"Pointable [ id:"+this.id+" "+this.length+"mmx | direction: "+this.direction+" ]"}};Pointable.Invalid={valid:false}},{"gl-matrix":19}],12:[function(require,module,exports){var Frame=require("./frame");var Event=function(data){this.type=data.type;this.state=data.state};var chooseProtocol=exports.chooseProtocol=function(header){var protocol;switch(header.version){case 1:protocol=JSONProtocol(1,function(data){return new Frame(data)});break;case 2:protocol=JSONProtocol(2,function(data){return new Frame(data)});protocol.sendHeartbeat=function(connection){connection.send(protocol.encode({heartbeat:true}))};break;case 3:protocol=JSONProtocol(3,function(data){return data.event?new Event(data.event):new Frame(data)});protocol.sendHeartbeat=function(connection){connection.send(protocol.encode({heartbeat:true}))};break;default:throw"unrecognized version"}return protocol};var JSONProtocol=function(version,cb){var protocol=cb;protocol.encode=function(message){return JSON.stringify(message)};protocol.version=version;protocol.versionLong="Version "+version;protocol.type="protocol";return protocol}},{"./frame":5}],13:[function(require,module,exports){exports.UI={Region:require("./ui/region"),Cursor:require("./ui/cursor")}},{"./ui/cursor":14,"./ui/region":15}],14:[function(require,module,exports){var Cursor=module.exports=function(){return function(frame){var pointable=frame.pointables.sort(function(a,b){return a.z-b.z})[0];if(pointable&&pointable.valid){frame.cursorPosition=pointable.tipPosition}return frame}}},{}],15:[function(require,module,exports){var EventEmitter=require("events").EventEmitter,_=require("underscore");var Region=module.exports=function(start,end){this.start=new Vector(start);this.end=new Vector(end);this.enteredFrame=null};Region.prototype.hasPointables=function(frame){for(var i=0;i!=frame.pointables.length;i++){var position=frame.pointables[i].tipPosition;if(position.x>=this.start.x&&position.x<=this.end.x&&position.y>=this.start.y&&position.y<=this.end.y&&position.z>=this.start.z&&position.z<=this.end.z){return true}}return false};Region.prototype.listener=function(opts){var region=this;if(opts&&opts.nearThreshold)this.setupNearRegion(opts.nearThreshold);return function(frame){return region.updatePosition(frame)}};Region.prototype.clipper=function(){var region=this;return function(frame){region.updatePosition(frame);return region.enteredFrame?frame:null}};Region.prototype.setupNearRegion=function(distance){var nearRegion=this.nearRegion=new Region([this.start.x-distance,this.start.y-distance,this.start.z-distance],[this.end.x+distance,this.end.y+distance,this.end.z+distance]);var region=this;nearRegion.on("enter",function(frame){region.emit("near",frame)});nearRegion.on("exit",function(frame){region.emit("far",frame)});region.on("exit",function(frame){region.emit("near",frame)})};Region.prototype.updatePosition=function(frame){if(this.nearRegion)this.nearRegion.updatePosition(frame);if(this.hasPointables(frame)&&this.enteredFrame==null){this.enteredFrame=frame;this.emit("enter",this.enteredFrame)}else if(!this.hasPointables(frame)&&this.enteredFrame!=null){this.enteredFrame=null;this.emit("exit",this.enteredFrame)}return frame};Region.prototype.normalize=function(position){return new Vector([(position.x-this.start.x)/(this.end.x-this.start.x),(position.y-this.start.y)/(this.end.y-this.start.y),(position.z-this.start.z)/(this.end.z-this.start.z)])};Region.prototype.mapToXY=function(position,width,height){var normalized=this.normalize(position);var x=normalized.x,y=normalized.y;if(x>1)x=1;else if(x<-1)x=-1;if(y>1)y=1;else if(y<-1)y=-1;return[(x+1)/2*width,(1-y)/2*height,normalized.z]};_.extend(Region.prototype,EventEmitter.prototype)},{events:17,underscore:20}],16:[function(require,module,exports){},{}],17:[function(require,module,exports){!function(process){if(!process.EventEmitter)process.EventEmitter=function(){};var EventEmitter=exports.EventEmitter=process.EventEmitter;var isArray=typeof Array.isArray==="function"?Array.isArray:function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function indexOf(xs,x){if(xs.indexOf)return xs.indexOf(x);for(var i=0;i<xs.length;i++){if(x===xs[i])return i}return-1}var defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!this._events)this._events={};this._events.maxListeners=n};EventEmitter.prototype.emit=function(type){if(type==="error"){if(!this._events||!this._events.error||isArray(this._events.error)&&!this._events.error.length){if(arguments[1]instanceof Error){throw arguments[1]}else{throw new Error("Uncaught, unspecified 'error' event.")}return false}}if(!this._events)return false;var handler=this._events[type];if(!handler)return false;if(typeof handler=="function"){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:var args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}return true}else if(isArray(handler)){var args=Array.prototype.slice.call(arguments,1);var listeners=handler.slice();for(var i=0,l=listeners.length;i<l;i++){listeners[i].apply(this,args)}return true}else{return false}};EventEmitter.prototype.addListener=function(type,listener){if("function"!==typeof listener){throw new Error("addListener only takes instances of Function")}if(!this._events)this._events={};this.emit("newListener",type,listener);if(!this._events[type]){this._events[type]=listener}else if(isArray(this._events[type])){if(!this._events[type].warned){var m;if(this._events.maxListeners!==undefined){m=this._events.maxListeners}else{m=defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);console.trace()}}this._events[type].push(listener)}else{this._events[type]=[this._events[type],listener]}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){var self=this;self.on(type,function g(){self.removeListener(type,g);listener.apply(this,arguments)});return this};EventEmitter.prototype.removeListener=function(type,listener){if("function"!==typeof listener){throw new Error("removeListener only takes instances of Function")}if(!this._events||!this._events[type])return this;var list=this._events[type];if(isArray(list)){var i=indexOf(list,listener);if(i<0)return this;list.splice(i,1);if(list.length==0)delete this._events[type]}else if(this._events[type]===listener){delete this._events[type]}return this};EventEmitter.prototype.removeAllListeners=function(type){if(arguments.length===0){this._events={};return this}if(type&&this._events&&this._events[type])this._events[type]=null;return this};EventEmitter.prototype.listeners=function(type){if(!this._events)this._events={};if(!this._events[type])this._events[type]=[];if(!isArray(this._events[type])){this._events[type]=[this._events[type]]}return this._events[type]}}(require("__browserify_process"))},{__browserify_process:18}],18:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){if(ev.source===window&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],19:[function(require,module,exports){!function(){!function(){"use strict";var shim={};if(typeof exports==="undefined"){if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){shim.exports={};define(function(){return shim.exports})}else{shim.exports=window}}else{shim.exports=exports}!function(exports){var vec2={};if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}vec2.create=function(){return new Float32Array(2)};vec2.clone=function(a){var out=new Float32Array(2);out[0]=a[0];out[1]=a[1];return out};vec2.fromValues=function(x,y){var out=new Float32Array(2);out[0]=x;out[1]=y;return out};vec2.copy=function(out,a){out[0]=a[0];out[1]=a[1];return out};vec2.set=function(out,x,y){out[0]=x;out[1]=y;return out};vec2.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];return out};vec2.sub=vec2.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];return out};vec2.mul=vec2.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];return out};vec2.div=vec2.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];return out};vec2.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);
out[1]=Math.min(a[1],b[1]);return out};vec2.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);return out};vec2.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;return out};vec2.dist=vec2.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)};vec2.sqrDist=vec2.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y};vec2.len=vec2.length=function(a){var x=a[0],y=a[1];return Math.sqrt(x*x+y*y)};vec2.sqrLen=vec2.squaredLength=function(a){var x=a[0],y=a[1];return x*x+y*y};vec2.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];return out};vec2.normalize=function(out,a){var x=a[0],y=a[1];var len=x*x+y*y;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len}return out};vec2.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]};vec2.cross=function(out,a,b){var z=a[0]*b[1]-a[1]*b[0];out[0]=out[1]=0;out[2]=z;return out};vec2.lerp=function(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out};vec2.transformMat2=function(out,a,m){var x=a[0],y=a[1];out[0]=x*m[0]+y*m[1];out[1]=x*m[2]+y*m[3];return out};vec2.forEach=function(){var vec=new Float32Array(2);return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=2}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1]}return a}}();vec2.str=function(a){return"vec2("+a[0]+", "+a[1]+")"};if(typeof exports!=="undefined"){exports.vec2=vec2}var vec3={};if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}vec3.create=function(){return new Float32Array(3)};vec3.clone=function(a){var out=new Float32Array(3);out[0]=a[0];out[1]=a[1];out[2]=a[2];return out};vec3.fromValues=function(x,y,z){var out=new Float32Array(3);out[0]=x;out[1]=y;out[2]=z;return out};vec3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];return out};vec3.set=function(out,x,y,z){out[0]=x;out[1]=y;out[2]=z;return out};vec3.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];return out};vec3.sub=vec3.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];return out};vec3.mul=vec3.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];return out};vec3.div=vec3.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];return out};vec3.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);return out};vec3.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);return out};vec3.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;return out};vec3.dist=vec3.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)};vec3.sqrDist=vec3.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z};vec3.len=vec3.length=function(a){var x=a[0],y=a[1],z=a[2];return Math.sqrt(x*x+y*y+z*z)};vec3.sqrLen=vec3.squaredLength=function(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z};vec3.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];return out};vec3.normalize=function(out,a){var x=a[0],y=a[1],z=a[2];var len=x*x+y*y+z*z;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len}return out};vec3.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};vec3.cross=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out};vec3.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);return out};vec3.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12];out[1]=m[1]*x+m[5]*y+m[9]*z+m[13];out[2]=m[2]*x+m[6]*y+m[10]*z+m[14];return out};vec3.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return out};vec3.forEach=function(){var vec=new Float32Array(3);return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=3}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2]}return a}}();vec3.str=function(a){return"vec3("+a[0]+", "+a[1]+", "+a[2]+")"};if(typeof exports!=="undefined"){exports.vec3=vec3}var vec4={};if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}vec4.create=function(){return new Float32Array(4)};vec4.clone=function(a){var out=new Float32Array(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};vec4.fromValues=function(x,y,z,w){var out=new Float32Array(4);out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out};vec4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};vec4.set=function(out,x,y,z,w){out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out};vec4.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out};vec4.sub=vec4.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];return out};vec4.mul=vec4.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];out[3]=a[3]*b[3];return out};vec4.div=vec4.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];out[3]=a[3]/b[3];return out};vec4.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);out[3]=Math.min(a[3],b[3]);return out};vec4.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);out[3]=Math.max(a[3],b[3]);return out};vec4.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out};vec4.dist=vec4.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return Math.sqrt(x*x+y*y+z*z+w*w)};vec4.sqrDist=vec4.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return x*x+y*y+z*z+w*w};vec4.len=vec4.length=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return Math.sqrt(x*x+y*y+z*z+w*w)};vec4.sqrLen=vec4.squaredLength=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return x*x+y*y+z*z+w*w};vec4.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=-a[3];return out};vec4.normalize=function(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var len=x*x+y*y+z*z+w*w;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;out[3]=a[3]*len}return out};vec4.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]};vec4.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out};vec4.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out};vec4.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return out};vec4.forEach=function(){var vec=new Float32Array(4);return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=4}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];vec[3]=a[i+3];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];a[i+3]=vec[3]}return a}}();vec4.str=function(a){return"vec4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"};if(typeof exports!=="undefined"){exports.vec4=vec4}var mat2={};var mat2Identity=new Float32Array([1,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}mat2.create=function(){return new Float32Array(mat2Identity)};mat2.clone=function(a){var out=new Float32Array(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};mat2.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out};mat2.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out};mat2.transpose=function(out,a){if(out===a){var a1=a[1];out[1]=a[2];out[2]=a1}else{out[0]=a[0];out[1]=a[2];out[2]=a[1];out[3]=a[3]}return out};mat2.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],det=a0*a3-a2*a1;if(!det){return null}det=1/det;out[0]=a3*det;out[1]=-a1*det;out[2]=-a2*det;out[3]=a0*det;return out};mat2.adjoint=function(out,a){var a0=a[0];out[0]=a[3];out[1]=-a[1];out[2]=-a[2];out[3]=a0;return out};mat2.determinant=function(a){return a[0]*a[3]-a[2]*a[1]};mat2.mul=mat2.multiply=function(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=a0*b0+a1*b2;out[1]=a0*b1+a1*b3;out[2]=a2*b0+a3*b2;out[3]=a2*b1+a3*b3;return out};mat2.rotate=function(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],s=Math.sin(rad),c=Math.cos(rad);out[0]=a0*c+a1*s;out[1]=a0*-s+a1*c;out[2]=a2*c+a3*s;out[3]=a2*-s+a3*c;return out};mat2.scale=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v1;out[2]=a2*v0;out[3]=a3*v1;return out};mat2.str=function(a){return"mat2("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"};if(typeof exports!=="undefined"){exports.mat2=mat2}var mat3={};var mat3Identity=new Float32Array([1,0,0,0,1,0,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}mat3.create=function(){return new Float32Array(mat3Identity)};mat3.clone=function(a){var out=new Float32Array(9);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out};mat3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out};mat3.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out};mat3.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a12=a[5];out[1]=a[3];out[2]=a[6];out[3]=a01;out[5]=a[7];out[6]=a02;out[7]=a12}else{out[0]=a[0];out[1]=a[3];out[2]=a[6];out[3]=a[1];out[4]=a[4];out[5]=a[7];out[6]=a[2];out[7]=a[5];out[8]=a[8]}return out};mat3.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b01=a22*a11-a12*a21,b11=-a22*a10+a12*a20,b21=a21*a10-a11*a20,det=a00*b01+a01*b11+a02*b21;if(!det){return null}det=1/det;out[0]=b01*det;out[1]=(-a22*a01+a02*a21)*det;out[2]=(a12*a01-a02*a11)*det;out[3]=b11*det;out[4]=(a22*a00-a02*a20)*det;out[5]=(-a12*a00+a02*a10)*det;out[6]=b21*det;out[7]=(-a21*a00+a01*a20)*det;out[8]=(a11*a00-a01*a10)*det;return out};mat3.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];out[0]=a11*a22-a12*a21;out[1]=a02*a21-a01*a22;out[2]=a01*a12-a02*a11;out[3]=a12*a20-a10*a22;out[4]=a00*a22-a02*a20;out[5]=a02*a10-a00*a12;out[6]=a10*a21-a11*a20;out[7]=a01*a20-a00*a21;out[8]=a00*a11-a01*a10;return out};mat3.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];return a00*(a22*a11-a12*a21)+a01*(-a22*a10+a12*a20)+a02*(a21*a10-a11*a20)};mat3.mul=mat3.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b00=b[0],b01=b[1],b02=b[2],b10=b[3],b11=b[4],b12=b[5],b20=b[6],b21=b[7],b22=b[8];out[0]=b00*a00+b01*a10+b02*a20;out[1]=b00*a01+b01*a11+b02*a21;out[2]=b00*a02+b01*a12+b02*a22;out[3]=b10*a00+b11*a10+b12*a20;out[4]=b10*a01+b11*a11+b12*a21;out[5]=b10*a02+b11*a12+b12*a22;out[6]=b20*a00+b21*a10+b22*a20;out[7]=b20*a01+b21*a11+b22*a21;out[8]=b20*a02+b21*a12+b22*a22;return out};mat3.str=function(a){return"mat3("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+")"};if(typeof exports!=="undefined"){exports.mat3=mat3}var mat4={};var mat4Identity=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}mat4.create=function(){return new Float32Array(mat4Identity)};mat4.clone=function(a){var out=new Float32Array(16);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out};mat4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out};mat4.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out};mat4.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a03=a[3],a12=a[6],a13=a[7],a23=a[11];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a01;out[6]=a[9];out[7]=a[13];out[8]=a02;out[9]=a12;out[11]=a[14];out[12]=a03;out[13]=a13;out[14]=a23}else{out[0]=a[0];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a[1];out[5]=a[5];out[6]=a[9];out[7]=a[13];out[8]=a[2];out[9]=a[6];out[10]=a[10];out[11]=a[14];out[12]=a[3];out[13]=a[7];out[14]=a[11];out[15]=a[15]}return out};mat4.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32,det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null}det=1/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a02*b10-a01*b11-a03*b09)*det;out[2]=(a31*b05-a32*b04+a33*b03)*det;out[3]=(a22*b04-a21*b05-a23*b03)*det;out[4]=(a12*b08-a10*b11-a13*b07)*det;out[5]=(a00*b11-a02*b08+a03*b07)*det;out[6]=(a32*b02-a30*b05-a33*b01)*det;out[7]=(a20*b05-a22*b02+a23*b01)*det;out[8]=(a10*b10-a11*b08+a13*b06)*det;out[9]=(a01*b08-a00*b10-a03*b06)*det;out[10]=(a30*b04-a31*b02+a33*b00)*det;out[11]=(a21*b02-a20*b04-a23*b00)*det;out[12]=(a11*b07-a10*b09-a12*b06)*det;out[13]=(a00*b09-a01*b07+a02*b06)*det;out[14]=(a31*b01-a30*b03-a32*b00)*det;out[15]=(a20*b03-a21*b01+a22*b00)*det;return out};mat4.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];out[0]=a11*(a22*a33-a23*a32)-a21*(a12*a33-a13*a32)+a31*(a12*a23-a13*a22);out[1]=-(a01*(a22*a33-a23*a32)-a21*(a02*a33-a03*a32)+a31*(a02*a23-a03*a22));out[2]=a01*(a12*a33-a13*a32)-a11*(a02*a33-a03*a32)+a31*(a02*a13-a03*a12);out[3]=-(a01*(a12*a23-a13*a22)-a11*(a02*a23-a03*a22)+a21*(a02*a13-a03*a12));out[4]=-(a10*(a22*a33-a23*a32)-a20*(a12*a33-a13*a32)+a30*(a12*a23-a13*a22));out[5]=a00*(a22*a33-a23*a32)-a20*(a02*a33-a03*a32)+a30*(a02*a23-a03*a22);out[6]=-(a00*(a12*a33-a13*a32)-a10*(a02*a33-a03*a32)+a30*(a02*a13-a03*a12));out[7]=a00*(a12*a23-a13*a22)-a10*(a02*a23-a03*a22)+a20*(a02*a13-a03*a12);out[8]=a10*(a21*a33-a23*a31)-a20*(a11*a33-a13*a31)+a30*(a11*a23-a13*a21);out[9]=-(a00*(a21*a33-a23*a31)-a20*(a01*a33-a03*a31)+a30*(a01*a23-a03*a21));out[10]=a00*(a11*a33-a13*a31)-a10*(a01*a33-a03*a31)+a30*(a01*a13-a03*a11);out[11]=-(a00*(a11*a23-a13*a21)-a10*(a01*a23-a03*a21)+a20*(a01*a13-a03*a11));out[12]=-(a10*(a21*a32-a22*a31)-a20*(a11*a32-a12*a31)+a30*(a11*a22-a12*a21));out[13]=a00*(a21*a32-a22*a31)-a20*(a01*a32-a02*a31)+a30*(a01*a22-a02*a21);out[14]=-(a00*(a11*a32-a12*a31)-a10*(a01*a32-a02*a31)+a30*(a01*a12-a02*a11));out[15]=a00*(a11*a22-a12*a21)-a10*(a01*a22-a02*a21)+a20*(a01*a12-a02*a11);return out};mat4.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;return b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06};mat4.mul=mat4.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=b0*a00+b1*a10+b2*a20+b3*a30;out[1]=b0*a01+b1*a11+b2*a21+b3*a31;out[2]=b0*a02+b1*a12+b2*a22+b3*a32;out[3]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[4];b1=b[5];b2=b[6];b3=b[7];out[4]=b0*a00+b1*a10+b2*a20+b3*a30;out[5]=b0*a01+b1*a11+b2*a21+b3*a31;out[6]=b0*a02+b1*a12+b2*a22+b3*a32;out[7]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[8];b1=b[9];b2=b[10];b3=b[11];out[8]=b0*a00+b1*a10+b2*a20+b3*a30;out[9]=b0*a01+b1*a11+b2*a21+b3*a31;out[10]=b0*a02+b1*a12+b2*a22+b3*a32;out[11]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[12];b1=b[13];b2=b[14];b3=b[15];out[12]=b0*a00+b1*a10+b2*a20+b3*a30;out[13]=b0*a01+b1*a11+b2*a21+b3*a31;out[14]=b0*a02+b1*a12+b2*a22+b3*a32;out[15]=b0*a03+b1*a13+b2*a23+b3*a33;return out};mat4.translate=function(out,a,v){var x=v[0],y=v[1],z=v[2],a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;if(a===out){out[12]=a[0]*x+a[4]*y+a[8]*z+a[12];out[13]=a[1]*x+a[5]*y+a[9]*z+a[13];out[14]=a[2]*x+a[6]*y+a[10]*z+a[14];out[15]=a[3]*x+a[7]*y+a[11]*z+a[15]}else{a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a03;out[4]=a10;out[5]=a11;out[6]=a12;out[7]=a13;out[8]=a20;out[9]=a21;out[10]=a22;out[11]=a23;out[12]=a00*x+a10*y+a20*z+a[12];out[13]=a01*x+a11*y+a21*z+a[13];out[14]=a02*x+a12*y+a22*z+a[14];out[15]=a03*x+a13*y+a23*z+a[15]}return out};mat4.scale=function(out,a,v){var x=v[0],y=v[1],z=v[2];out[0]=a[0]*x;out[1]=a[1]*x;out[2]=a[2]*x;out[3]=a[3]*x;out[4]=a[4]*y;out[5]=a[5]*y;out[6]=a[6]*y;out[7]=a[7]*y;out[8]=a[8]*z;out[9]=a[9]*z;out[10]=a[10]*z;out[11]=a[11]*z;out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out};mat4.rotate=function(out,a,rad,axis){var x=axis[0],y=axis[1],z=axis[2],len=Math.sqrt(x*x+y*y+z*z),s,c,t,a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23,b00,b01,b02,b10,b11,b12,b20,b21,b22;if(Math.abs(len)<GLMAT_EPSILON){return null}len=1/len;x*=len;y*=len;z*=len;s=Math.sin(rad);c=Math.cos(rad);t=1-c;a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];b00=x*x*t+c;b01=y*x*t+z*s;b02=z*x*t-y*s;b10=x*y*t-z*s;b11=y*y*t+c;b12=z*y*t+x*s;b20=x*z*t+y*s;b21=y*z*t-x*s;b22=z*z*t+c;out[0]=a00*b00+a10*b01+a20*b02;out[1]=a01*b00+a11*b01+a21*b02;out[2]=a02*b00+a12*b01+a22*b02;out[3]=a03*b00+a13*b01+a23*b02;out[4]=a00*b10+a10*b11+a20*b12;out[5]=a01*b10+a11*b11+a21*b12;out[6]=a02*b10+a12*b11+a22*b12;out[7]=a03*b10+a13*b11+a23*b12;out[8]=a00*b20+a10*b21+a20*b22;out[9]=a01*b20+a11*b21+a21*b22;out[10]=a02*b20+a12*b21+a22*b22;out[11]=a03*b20+a13*b21+a23*b22;if(a!==out){out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}return out};mat4.rotateX=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}out[4]=a10*c+a20*s;out[5]=a11*c+a21*s;out[6]=a12*c+a22*s;out[7]=a13*c+a23*s;out[8]=a20*c-a10*s;out[9]=a21*c-a11*s;out[10]=a22*c-a12*s;out[11]=a23*c-a13*s;return out};mat4.rotateY=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}out[0]=a00*c-a20*s;out[1]=a01*c-a21*s;out[2]=a02*c-a22*s;out[3]=a03*c-a23*s;out[8]=a00*s+a20*c;out[9]=a01*s+a21*c;out[10]=a02*s+a22*c;out[11]=a03*s+a23*c;return out};mat4.rotateZ=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7];if(a!==out){out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15]}out[0]=a00*c+a10*s;out[1]=a01*c+a11*s;out[2]=a02*c+a12*s;out[3]=a03*c+a13*s;out[4]=a10*c-a00*s;out[5]=a11*c-a01*s;out[6]=a12*c-a02*s;out[7]=a13*c-a03*s;return out};mat4.fromRotationTranslation=function(out,q,v){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,xy=x*y2,xz=x*z2,yy=y*y2,yz=y*z2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-(yy+zz);out[1]=xy+wz;out[2]=xz-wy;out[3]=0;out[4]=xy-wz;out[5]=1-(xx+zz);out[6]=yz+wx;out[7]=0;out[8]=xz+wy;out[9]=yz-wx;out[10]=1-(xx+yy);out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out};mat4.frustum=function(out,left,right,bottom,top,near,far){var rl=1/(right-left),tb=1/(top-bottom),nf=1/(near-far);out[0]=near*2*rl;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=near*2*tb;out[6]=0;out[7]=0;out[8]=(right+left)*rl;out[9]=(top+bottom)*tb;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=far*near*2*nf;out[15]=0;return out};mat4.perspective=function(out,fovy,aspect,near,far){var f=1/Math.tan(fovy/2),nf=1/(near-far);out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=2*far*near*nf;out[15]=0;return out};mat4.ortho=function(out,left,right,bottom,top,near,far){var lr=1/(left-right),bt=1/(bottom-top),nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=2*nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=(far+near)*nf;out[15]=1;return out};mat4.lookAt=function(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len,eyex=eye[0],eyey=eye[1],eyez=eye[2],upx=up[0],upy=up[1],upz=up[2],centerx=center[0],centery=center[1],centerz=center[2];if(Math.abs(eyex-centerx)<GLMAT_EPSILON&&Math.abs(eyey-centery)<GLMAT_EPSILON&&Math.abs(eyez-centerz)<GLMAT_EPSILON){return mat4.identity(out)}z0=eyex-centerx;z1=eyey-centery;z2=eyez-centerz;len=1/Math.sqrt(z0*z0+z1*z1+z2*z2);z0*=len;z1*=len;z2*=len;x0=upy*z2-upz*z1;x1=upz*z0-upx*z2;x2=upx*z1-upy*z0;len=Math.sqrt(x0*x0+x1*x1+x2*x2);if(!len){x0=0;x1=0;x2=0}else{len=1/len;x0*=len;x1*=len;x2*=len}y0=z1*x2-z2*x1;y1=z2*x0-z0*x2;y2=z0*x1-z1*x0;len=Math.sqrt(y0*y0+y1*y1+y2*y2);if(!len){y0=0;y1=0;y2=0}else{len=1/len;y0*=len;y1*=len;y2*=len}out[0]=x0;out[1]=y0;out[2]=z0;out[3]=0;out[4]=x1;out[5]=y1;out[6]=z1;out[7]=0;out[8]=x2;out[9]=y2;out[10]=z2;out[11]=0;out[12]=-(x0*eyex+x1*eyey+x2*eyez);out[13]=-(y0*eyex+y1*eyey+y2*eyez);out[14]=-(z0*eyex+z1*eyey+z2*eyez);out[15]=1;return out};mat4.str=function(a){return"mat4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+")"};if(typeof exports!=="undefined"){exports.mat4=mat4}var quat={};var quatIdentity=new Float32Array([0,0,0,1]);if(!GLMAT_EPSILON){var GLMAT_EPSILON=1e-6}quat.create=function(){return new Float32Array(quatIdentity)};quat.clone=vec4.clone;quat.fromValues=vec4.fromValues;quat.copy=vec4.copy;quat.set=vec4.set;quat.identity=function(out){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out};quat.setAxisAngle=function(out,axis,rad){rad=rad*.5;var s=Math.sin(rad);out[0]=s*axis[0];out[1]=s*axis[1];out[2]=s*axis[2];out[3]=Math.cos(rad);return out};quat.add=vec4.add;quat.mul=quat.multiply=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out};quat.scale=vec4.scale;quat.rotateX=function(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out};quat.rotateY=function(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out};quat.rotateZ=function(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out};quat.calculateW=function(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=-Math.sqrt(Math.abs(1-x*x-y*y-z*z));return out};quat.dot=vec4.dot;quat.lerp=vec4.lerp;quat.slerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=a[3];var cosHalfTheta=ax*bx+ay*by+az*bz+aw*bw,halfTheta,sinHalfTheta,ratioA,ratioB;if(Math.abs(cosHalfTheta)>=1){if(out!==a){out[0]=ax;out[1]=ay;out[2]=az;out[3]=aw}return out}halfTheta=Math.acos(cosHalfTheta);sinHalfTheta=Math.sqrt(1-cosHalfTheta*cosHalfTheta);if(Math.abs(sinHalfTheta)<.001){out[0]=ax*.5+bx*.5;out[1]=ay*.5+by*.5;out[2]=az*.5+bz*.5;out[3]=aw*.5+bw*.5;return out}ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta;ratioB=Math.sin(t*halfTheta)/sinHalfTheta;out[0]=ax*ratioA+bx*ratioB;out[1]=ay*ratioA+by*ratioB;out[2]=az*ratioA+bz*ratioB;out[3]=aw*ratioA+bw*ratioB;return out};quat.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],dot=a0*a0+a1*a1+a2*a2+a3*a3,invDot=dot?1/dot:0;out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out};quat.conjugate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out};quat.len=quat.length=vec4.length;quat.sqrLen=quat.squaredLength=vec4.squaredLength;quat.normalize=vec4.normalize;quat.str=function(a){return"quat("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"};if(typeof exports!=="undefined"){exports.quat=quat}}(shim.exports)}()}()},{}],20:[function(require,module,exports){!function(){!function(){var root=this;var previousUnderscore=root._;var breaker={};var ArrayProto=Array.prototype,ObjProto=Object.prototype,FuncProto=Function.prototype;var push=ArrayProto.push,slice=ArrayProto.slice,concat=ArrayProto.concat,toString=ObjProto.toString,hasOwnProperty=ObjProto.hasOwnProperty;var nativeForEach=ArrayProto.forEach,nativeMap=ArrayProto.map,nativeReduce=ArrayProto.reduce,nativeReduceRight=ArrayProto.reduceRight,nativeFilter=ArrayProto.filter,nativeEvery=ArrayProto.every,nativeSome=ArrayProto.some,nativeIndexOf=ArrayProto.indexOf,nativeLastIndexOf=ArrayProto.lastIndexOf,nativeIsArray=Array.isArray,nativeKeys=Object.keys,nativeBind=FuncProto.bind;var _=function(obj){if(obj instanceof _)return obj;if(!(this instanceof _))return new _(obj);this._wrapped=obj};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=_}exports._=_}else{root._=_}_.VERSION="1.4.4";var each=_.each=_.forEach=function(obj,iterator,context){if(obj==null)return;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context)}else if(obj.length===+obj.length){for(var i=0,l=obj.length;i<l;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return}}else{for(var key in obj){if(_.has(obj,key)){if(iterator.call(context,obj[key],key,obj)===breaker)return}}}};_.map=_.collect=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeMap&&obj.map===nativeMap)return obj.map(iterator,context);each(obj,function(value,index,list){results[results.length]=iterator.call(context,value,index,list)});return results};var reduceError="Reduce of empty array with no initial value";_.reduce=_.foldl=_.inject=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduce&&obj.reduce===nativeReduce){if(context)iterator=_.bind(iterator,context);return initial?obj.reduce(iterator,memo):obj.reduce(iterator)}each(obj,function(value,index,list){if(!initial){memo=value;initial=true}else{memo=iterator.call(context,memo,value,index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.reduceRight=_.foldr=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduceRight&&obj.reduceRight===nativeReduceRight){if(context)iterator=_.bind(iterator,context);return initial?obj.reduceRight(iterator,memo):obj.reduceRight(iterator)}var length=obj.length;if(length!==+length){var keys=_.keys(obj);length=keys.length}each(obj,function(value,index,list){index=keys?keys[--length]:--length;if(!initial){memo=obj[index];initial=true}else{memo=iterator.call(context,memo,obj[index],index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.find=_.detect=function(obj,iterator,context){var result;any(obj,function(value,index,list){if(iterator.call(context,value,index,list)){result=value;return true}});return result};_.filter=_.select=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeFilter&&obj.filter===nativeFilter)return obj.filter(iterator,context);each(obj,function(value,index,list){if(iterator.call(context,value,index,list))results[results.length]=value});return results};_.reject=function(obj,iterator,context){return _.filter(obj,function(value,index,list){return!iterator.call(context,value,index,list)},context)};_.every=_.all=function(obj,iterator,context){iterator||(iterator=_.identity);var result=true;if(obj==null)return result;if(nativeEvery&&obj.every===nativeEvery)return obj.every(iterator,context);each(obj,function(value,index,list){if(!(result=result&&iterator.call(context,value,index,list)))return breaker});return!!result};var any=_.some=_.any=function(obj,iterator,context){iterator||(iterator=_.identity);var result=false;if(obj==null)return result;if(nativeSome&&obj.some===nativeSome)return obj.some(iterator,context);each(obj,function(value,index,list){if(result||(result=iterator.call(context,value,index,list)))return breaker});return!!result};_.contains=_.include=function(obj,target){if(obj==null)return false;if(nativeIndexOf&&obj.indexOf===nativeIndexOf)return obj.indexOf(target)!=-1;return any(obj,function(value){return value===target})};_.invoke=function(obj,method){var args=slice.call(arguments,2);var isFunc=_.isFunction(method);return _.map(obj,function(value){return(isFunc?method:value[method]).apply(value,args)})};_.pluck=function(obj,key){return _.map(obj,function(value){return value[key]})};_.where=function(obj,attrs,first){if(_.isEmpty(attrs))return first?null:[];return _[first?"find":"filter"](obj,function(value){for(var key in attrs){if(attrs[key]!==value[key])return false}return true})};_.findWhere=function(obj,attrs){return _.where(obj,attrs,true)};_.max=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.max.apply(Math,obj)}if(!iterator&&_.isEmpty(obj))return-Infinity;var result={computed:-Infinity,value:-Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed>=result.computed&&(result={value:value,computed:computed})});return result.value};_.min=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.min.apply(Math,obj)}if(!iterator&&_.isEmpty(obj))return Infinity;var result={computed:Infinity,value:Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed<result.computed&&(result={value:value,computed:computed})});return result.value};_.shuffle=function(obj){var rand;var index=0;var shuffled=[];each(obj,function(value){rand=_.random(index++);shuffled[index-1]=shuffled[rand];shuffled[rand]=value});return shuffled};var lookupIterator=function(value){return _.isFunction(value)?value:function(obj){return obj[value]}};_.sortBy=function(obj,value,context){var iterator=lookupIterator(value);return _.pluck(_.map(obj,function(value,index,list){return{value:value,index:index,criteria:iterator.call(context,value,index,list)}}).sort(function(left,right){var a=left.criteria;
var b=right.criteria;if(a!==b){if(a>b||a===void 0)return 1;if(a<b||b===void 0)return-1}return left.index<right.index?-1:1}),"value")};var group=function(obj,value,context,behavior){var result={};var iterator=lookupIterator(value||_.identity);each(obj,function(value,index){var key=iterator.call(context,value,index,obj);behavior(result,key,value)});return result};_.groupBy=function(obj,value,context){return group(obj,value,context,function(result,key,value){(_.has(result,key)?result[key]:result[key]=[]).push(value)})};_.countBy=function(obj,value,context){return group(obj,value,context,function(result,key){if(!_.has(result,key))result[key]=0;result[key]++})};_.sortedIndex=function(array,obj,iterator,context){iterator=iterator==null?_.identity:lookupIterator(iterator);var value=iterator.call(context,obj);var low=0,high=array.length;while(low<high){var mid=low+high>>>1;iterator.call(context,array[mid])<value?low=mid+1:high=mid}return low};_.toArray=function(obj){if(!obj)return[];if(_.isArray(obj))return slice.call(obj);if(obj.length===+obj.length)return _.map(obj,_.identity);return _.values(obj)};_.size=function(obj){if(obj==null)return 0;return obj.length===+obj.length?obj.length:_.keys(obj).length};_.first=_.head=_.take=function(array,n,guard){if(array==null)return void 0;return n!=null&&!guard?slice.call(array,0,n):array[0]};_.initial=function(array,n,guard){return slice.call(array,0,array.length-(n==null||guard?1:n))};_.last=function(array,n,guard){if(array==null)return void 0;if(n!=null&&!guard){return slice.call(array,Math.max(array.length-n,0))}else{return array[array.length-1]}};_.rest=_.tail=_.drop=function(array,n,guard){return slice.call(array,n==null||guard?1:n)};_.compact=function(array){return _.filter(array,_.identity)};var flatten=function(input,shallow,output){each(input,function(value){if(_.isArray(value)){shallow?push.apply(output,value):flatten(value,shallow,output)}else{output.push(value)}});return output};_.flatten=function(array,shallow){return flatten(array,shallow,[])};_.without=function(array){return _.difference(array,slice.call(arguments,1))};_.uniq=_.unique=function(array,isSorted,iterator,context){if(_.isFunction(isSorted)){context=iterator;iterator=isSorted;isSorted=false}var initial=iterator?_.map(array,iterator,context):array;var results=[];var seen=[];each(initial,function(value,index){if(isSorted?!index||seen[seen.length-1]!==value:!_.contains(seen,value)){seen.push(value);results.push(array[index])}});return results};_.union=function(){return _.uniq(concat.apply(ArrayProto,arguments))};_.intersection=function(array){var rest=slice.call(arguments,1);return _.filter(_.uniq(array),function(item){return _.every(rest,function(other){return _.indexOf(other,item)>=0})})};_.difference=function(array){var rest=concat.apply(ArrayProto,slice.call(arguments,1));return _.filter(array,function(value){return!_.contains(rest,value)})};_.zip=function(){var args=slice.call(arguments);var length=_.max(_.pluck(args,"length"));var results=new Array(length);for(var i=0;i<length;i++){results[i]=_.pluck(args,""+i)}return results};_.object=function(list,values){if(list==null)return{};var result={};for(var i=0,l=list.length;i<l;i++){if(values){result[list[i]]=values[i]}else{result[list[i][0]]=list[i][1]}}return result};_.indexOf=function(array,item,isSorted){if(array==null)return-1;var i=0,l=array.length;if(isSorted){if(typeof isSorted=="number"){i=isSorted<0?Math.max(0,l+isSorted):isSorted}else{i=_.sortedIndex(array,item);return array[i]===item?i:-1}}if(nativeIndexOf&&array.indexOf===nativeIndexOf)return array.indexOf(item,isSorted);for(;i<l;i++)if(array[i]===item)return i;return-1};_.lastIndexOf=function(array,item,from){if(array==null)return-1;var hasIndex=from!=null;if(nativeLastIndexOf&&array.lastIndexOf===nativeLastIndexOf){return hasIndex?array.lastIndexOf(item,from):array.lastIndexOf(item)}var i=hasIndex?from:array.length;while(i--)if(array[i]===item)return i;return-1};_.range=function(start,stop,step){if(arguments.length<=1){stop=start||0;start=0}step=arguments[2]||1;var len=Math.max(Math.ceil((stop-start)/step),0);var idx=0;var range=new Array(len);while(idx<len){range[idx++]=start;start+=step}return range};_.bind=function(func,context){if(func.bind===nativeBind&&nativeBind)return nativeBind.apply(func,slice.call(arguments,1));var args=slice.call(arguments,2);return function(){return func.apply(context,args.concat(slice.call(arguments)))}};_.partial=function(func){var args=slice.call(arguments,1);return function(){return func.apply(this,args.concat(slice.call(arguments)))}};_.bindAll=function(obj){var funcs=slice.call(arguments,1);if(funcs.length===0)funcs=_.functions(obj);each(funcs,function(f){obj[f]=_.bind(obj[f],obj)});return obj};_.memoize=function(func,hasher){var memo={};hasher||(hasher=_.identity);return function(){var key=hasher.apply(this,arguments);return _.has(memo,key)?memo[key]:memo[key]=func.apply(this,arguments)}};_.delay=function(func,wait){var args=slice.call(arguments,2);return setTimeout(function(){return func.apply(null,args)},wait)};_.defer=function(func){return _.delay.apply(_,[func,1].concat(slice.call(arguments,1)))};_.throttle=function(func,wait){var context,args,timeout,result;var previous=0;var later=function(){previous=new Date;timeout=null;result=func.apply(context,args)};return function(){var now=new Date;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args)}else if(!timeout){timeout=setTimeout(later,remaining)}return result}};_.debounce=function(func,wait,immediate){var timeout,result;return function(){var context=this,args=arguments;var later=function(){timeout=null;if(!immediate)result=func.apply(context,args)};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow)result=func.apply(context,args);return result}};_.once=function(func){var ran=false,memo;return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo}};_.wrap=function(func,wrapper){return function(){var args=[func];push.apply(args,arguments);return wrapper.apply(this,args)}};_.compose=function(){var funcs=arguments;return function(){var args=arguments;for(var i=funcs.length-1;i>=0;i--){args=[funcs[i].apply(this,args)]}return args[0]}};_.after=function(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}};_.keys=nativeKeys||function(obj){if(obj!==Object(obj))throw new TypeError("Invalid object");var keys=[];for(var key in obj)if(_.has(obj,key))keys[keys.length]=key;return keys};_.values=function(obj){var values=[];for(var key in obj)if(_.has(obj,key))values.push(obj[key]);return values};_.pairs=function(obj){var pairs=[];for(var key in obj)if(_.has(obj,key))pairs.push([key,obj[key]]);return pairs};_.invert=function(obj){var result={};for(var key in obj)if(_.has(obj,key))result[obj[key]]=key;return result};_.functions=_.methods=function(obj){var names=[];for(var key in obj){if(_.isFunction(obj[key]))names.push(key)}return names.sort()};_.extend=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){obj[prop]=source[prop]}}});return obj};_.pick=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));each(keys,function(key){if(key in obj)copy[key]=obj[key]});return copy};_.omit=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));for(var key in obj){if(!_.contains(keys,key))copy[key]=obj[key]}return copy};_.defaults=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){if(obj[prop]==null)obj[prop]=source[prop]}}});return obj};_.clone=function(obj){if(!_.isObject(obj))return obj;return _.isArray(obj)?obj.slice():_.extend({},obj)};_.tap=function(obj,interceptor){interceptor(obj);return obj};var eq=function(a,b,aStack,bStack){if(a===b)return a!==0||1/a==1/b;if(a==null||b==null)return a===b;if(a instanceof _)a=a._wrapped;if(b instanceof _)b=b._wrapped;var className=toString.call(a);if(className!=toString.call(b))return false;switch(className){case"[object String]":return a==String(b);case"[object Number]":return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case"[object Date]":case"[object Boolean]":return+a==+b;case"[object RegExp]":return a.source==b.source&&a.global==b.global&&a.multiline==b.multiline&&a.ignoreCase==b.ignoreCase}if(typeof a!="object"||typeof b!="object")return false;var length=aStack.length;while(length--){if(aStack[length]==a)return bStack[length]==b}aStack.push(a);bStack.push(b);var size=0,result=true;if(className=="[object Array]"){size=a.length;result=size==b.length;if(result){while(size--){if(!(result=eq(a[size],b[size],aStack,bStack)))break}}}else{var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&aCtor instanceof aCtor&&_.isFunction(bCtor)&&bCtor instanceof bCtor)){return false}for(var key in a){if(_.has(a,key)){size++;if(!(result=_.has(b,key)&&eq(a[key],b[key],aStack,bStack)))break}}if(result){for(key in b){if(_.has(b,key)&&!size--)break}result=!size}}aStack.pop();bStack.pop();return result};_.isEqual=function(a,b){return eq(a,b,[],[])};_.isEmpty=function(obj){if(obj==null)return true;if(_.isArray(obj)||_.isString(obj))return obj.length===0;for(var key in obj)if(_.has(obj,key))return false;return true};_.isElement=function(obj){return!!(obj&&obj.nodeType===1)};_.isArray=nativeIsArray||function(obj){return toString.call(obj)=="[object Array]"};_.isObject=function(obj){return obj===Object(obj)};each(["Arguments","Function","String","Number","Date","RegExp"],function(name){_["is"+name]=function(obj){return toString.call(obj)=="[object "+name+"]"}});if(!_.isArguments(arguments)){_.isArguments=function(obj){return!!(obj&&_.has(obj,"callee"))}}if(typeof/./!=="function"){_.isFunction=function(obj){return typeof obj==="function"}}_.isFinite=function(obj){return isFinite(obj)&&!isNaN(parseFloat(obj))};_.isNaN=function(obj){return _.isNumber(obj)&&obj!=+obj};_.isBoolean=function(obj){return obj===true||obj===false||toString.call(obj)=="[object Boolean]"};_.isNull=function(obj){return obj===null};_.isUndefined=function(obj){return obj===void 0};_.has=function(obj,key){return hasOwnProperty.call(obj,key)};_.noConflict=function(){root._=previousUnderscore;return this};_.identity=function(value){return value};_.times=function(n,iterator,context){var accum=Array(n);for(var i=0;i<n;i++)accum[i]=iterator.call(context,i);return accum};_.random=function(min,max){if(max==null){max=min;min=0}return min+Math.floor(Math.random()*(max-min+1))};var entityMap={escape:{"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"}};entityMap.unescape=_.invert(entityMap.escape);var entityRegexes={escape:new RegExp("["+_.keys(entityMap.escape).join("")+"]","g"),unescape:new RegExp("("+_.keys(entityMap.unescape).join("|")+")","g")};_.each(["escape","unescape"],function(method){_[method]=function(string){if(string==null)return"";return(""+string).replace(entityRegexes[method],function(match){return entityMap[method][match]})}});_.result=function(object,property){if(object==null)return null;var value=object[property];return _.isFunction(value)?value.call(object):value};_.mixin=function(obj){each(_.functions(obj),function(name){var func=_[name]=obj[name];_.prototype[name]=function(){var args=[this._wrapped];push.apply(args,arguments);return result.call(this,func.apply(_,args))}})};var idCounter=0;_.uniqueId=function(prefix){var id=++idCounter+"";return prefix?prefix+id:id};_.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var noMatch=/(.)^/;var escapes={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"};var escaper=/\\|'|\r|\n|\t|\u2028|\u2029/g;_.template=function(text,data,settings){var render;settings=_.defaults({},settings,_.templateSettings);var matcher=new RegExp([(settings.escape||noMatch).source,(settings.interpolate||noMatch).source,(settings.evaluate||noMatch).source].join("|")+"|$","g");var index=0;var source="__p+='";text.replace(matcher,function(match,escape,interpolate,evaluate,offset){source+=text.slice(index,offset).replace(escaper,function(match){return"\\"+escapes[match]});if(escape){source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'"}if(interpolate){source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'"}if(evaluate){source+="';\n"+evaluate+"\n__p+='"}index=offset+match.length;return match});source+="';\n";if(!settings.variable)source="with(obj||{}){\n"+source+"}\n";source="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+source+"return __p;\n";try{render=new Function(settings.variable||"obj","_",source)}catch(e){e.source=source;throw e}if(data)return render(data,_);var template=function(data){return render.call(this,data,_)};template.source="function("+(settings.variable||"obj")+"){\n"+source+"}";return template};_.chain=function(obj){return _(obj).chain()};var result=function(obj){return this._chain?_(obj).chain():obj};_.mixin(_);each(["pop","push","reverse","shift","sort","splice","unshift"],function(name){var method=ArrayProto[name];_.prototype[name]=function(){var obj=this._wrapped;method.apply(obj,arguments);if((name=="shift"||name=="splice")&&obj.length===0)delete obj[0];return result.call(this,obj)}});each(["concat","join","slice"],function(name){var method=ArrayProto[name];_.prototype[name]=function(){return result.call(this,method.apply(this._wrapped,arguments))}});_.extend(_.prototype,{chain:function(){this._chain=true;return this},value:function(){return this._wrapped}})}.call(this)}()},{}],21:[function(require,module,exports){window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1e3/60)}}();Leap=require("../lib/index")},{"../lib/index":8}]},{},[21]);
/*
* Leap Motion integration for Reveal.js.
* James Sun [sun16]
* Rory Hardy [gneatgeek]
*/
(function () {
var body = document.body,
controller = new Leap.Controller({ enableGestures: true }),
lastGesture = 0,
leapConfig = Reveal.getConfig().leap,
pointer = document.createElement( 'div' ),
config = {
autoCenter : true, // Center pointer around detected position.
gestureDelay : 500, // How long to delay between gestures.
naturalSwipe : true, // Swipe as if it were a touch screen.
pointerColor : '#00aaff', // Default color of the pointer.
pointerOpacity : 0.7, // Default opacity of the pointer.
pointerSize : 15, // Default minimum height/width of the pointer.
pointerTolerance : 120 // Bigger = slower pointer.
},
entered, enteredPosition, now, size, tipPosition; // Other vars we need later, but don't need to redeclare.
// Merge user defined settings with defaults
if( leapConfig ) {
for( key in leapConfig ) {
config[key] = leapConfig[key];
}
}
pointer.id = 'leap';
pointer.style.position = 'absolute';
pointer.style.visibility = 'hidden';
pointer.style.zIndex = 50;
pointer.style.opacity = config.pointerOpacity;
pointer.style.backgroundColor = config.pointerColor;
body.appendChild( pointer );
// Leap's loop
controller.on( 'frame', function ( frame ) {
// Timing code to rate limit gesture execution
now = new Date().getTime();
// Pointer: 1 to 2 fingers. Strictly one finger works but may cause innaccuracies.
// The innaccuracies were observed on a development model and may not be an issue with consumer models.
if( frame.fingers.length > 0 && frame.fingers.length < 3 ) {
// Invert direction and multiply by 3 for greater effect.
size = -3 * frame.fingers[0].tipPosition[2];
if( size < config.pointerSize ) {
size = config.pointerSize;
}
pointer.style.width = size + 'px';
pointer.style.height = size + 'px';
pointer.style.borderRadius = size - 5 + 'px';
pointer.style.visibility = 'visible';
if( config.autoCenter ) {
tipPosition = frame.fingers[0].tipPosition;
// Check whether the finger has entered the z range of the Leap Motion. Used for the autoCenter option.
if( !entered ) {
entered = true;
enteredPosition = frame.fingers[0].tipPosition;
}
pointer.style.top =
(-1 * (( tipPosition[1] - enteredPosition[1] ) * body.offsetHeight / config.pointerTolerance )) +
( body.offsetHeight / 2 ) + 'px';
pointer.style.left =
(( tipPosition[0] - enteredPosition[0] ) * body.offsetWidth / config.pointerTolerance ) +
( body.offsetWidth / 2 ) + 'px';
}
else {
pointer.style.top = ( 1 - (( tipPosition[1] - 50) / config.pointerTolerance )) *
body.offsetHeight + 'px';
pointer.style.left = ( tipPosition[0] * body.offsetWidth / config.pointerTolerance ) +
( body.offsetWidth / 2 ) + 'px';
}
}
else {
// Hide pointer on exit
entered = false;
pointer.style.visibility = 'hidden';
}
// Gestures
if( frame.gestures.length > 0 && (now - lastGesture) > config.gestureDelay ) {
var gesture = frame.gestures[0];
// One hand gestures
if( frame.hands.length === 1 ) {
// Swipe gestures. 3+ fingers.
if( frame.fingers.length > 2 && gesture.type === 'swipe' ) {
// Define here since some gestures will throw undefined for these.
var x = gesture.direction[0],
y = gesture.direction[1];
// Left/right swipe gestures
if( Math.abs( x ) > Math.abs( y )) {
if( x > 0 ) {
config.naturalSwipe ? Reveal.left() : Reveal.right();
}
else {
config.naturalSwipe ? Reveal.right() : Reveal.left();
}
}
// Up/down swipe gestures
else {
if( y > 0 ) {
config.naturalSwipe ? Reveal.down() : Reveal.up();
}
else {
config.naturalSwipe ? Reveal.up() : Reveal.down();
}
}
lastGesture = now;
}
}
// Two hand gestures
else if( frame.hands.length === 2 ) {
// Upward two hand swipe gesture
if( gesture.direction[1] > 0 && gesture.type === 'swipe' ) {
Reveal.toggleOverview();
}
lastGesture = now;
}
}
});
controller.connect();
})();
| bsquochoaidownloadfolders/cdnjs | ajax/libs/reveal.js/2.6.0/plugin/leap/leap.js | JavaScript | mit | 84,420 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"a.m.",
"p.m."
],
"DAY": [
"domingo",
"lunes",
"martes",
"mi\u00e9rcoles",
"jueves",
"viernes",
"s\u00e1bado"
],
"MONTH": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"SHORTDAY": [
"dom",
"lun",
"mar",
"mi\u00e9",
"jue",
"vie",
"s\u00e1b"
],
"SHORTMONTH": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"fullDate": "EEEE, d 'de' MMMM 'de' y",
"longDate": "d 'de' MMMM 'de' y",
"medium": "MM/dd/yyyy HH:mm:ss",
"mediumDate": "MM/dd/yyyy",
"mediumTime": "HH:mm:ss",
"short": "MM/dd/yy HH:mm",
"shortDate": "MM/dd/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "es-pr",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | ram-nadella/cdnjs | ajax/libs/angular.js/1.3.0-beta.2/i18n/angular-locale_es-pr.js | JavaScript | mit | 1,976 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u1321\u12cb\u1275",
"\u12a8\u1233\u12d3\u1275"
],
"DAY": [
"\u12a5\u1211\u12f5",
"\u1230\u129e",
"\u121b\u12ad\u1230\u129e",
"\u1228\u1261\u12d5",
"\u1210\u1219\u1235",
"\u12d3\u122d\u1265",
"\u1245\u12f3\u121c"
],
"MONTH": [
"\u1303\u1295\u12e9\u12c8\u122a",
"\u134c\u1265\u1229\u12c8\u122a",
"\u121b\u122d\u127d",
"\u12a4\u1355\u1228\u120d",
"\u121c\u12ed",
"\u1301\u1295",
"\u1301\u120b\u12ed",
"\u12a6\u1308\u1235\u1275",
"\u1234\u1355\u1274\u121d\u1260\u122d",
"\u12a6\u12ad\u1270\u12cd\u1260\u122d",
"\u1296\u126c\u121d\u1260\u122d",
"\u12f2\u1234\u121d\u1260\u122d"
],
"SHORTDAY": [
"\u12a5\u1211\u12f5",
"\u1230\u129e",
"\u121b\u12ad\u1230",
"\u1228\u1261\u12d5",
"\u1210\u1219\u1235",
"\u12d3\u122d\u1265",
"\u1245\u12f3\u121c"
],
"SHORTMONTH": [
"\u1303\u1295\u12e9",
"\u134c\u1265\u1229",
"\u121b\u122d\u127d",
"\u12a4\u1355\u1228",
"\u121c\u12ed",
"\u1301\u1295",
"\u1301\u120b\u12ed",
"\u12a6\u1308\u1235",
"\u1234\u1355\u1274",
"\u12a6\u12ad\u1270",
"\u1296\u126c\u121d",
"\u12f2\u1234\u121d"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yyyy h:mm a",
"shortDate": "dd/MM/yyyy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Birr",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "am-et",
"pluralCat": function (n) { if (n == 0 || n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | blairvanderhoof/cdnjs | ajax/libs/angular.js/1.3.0-beta.4/i18n/angular-locale_am-et.js | JavaScript | mit | 2,539 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"am",
"pm"
],
"DAY": [
"\u0cb0\u0cb5\u0cbf\u0cb5\u0cbe\u0cb0",
"\u0cb8\u0ccb\u0cae\u0cb5\u0cbe\u0cb0",
"\u0cae\u0c82\u0c97\u0cb3\u0cb5\u0cbe\u0cb0",
"\u0cac\u0cc1\u0ca7\u0cb5\u0cbe\u0cb0",
"\u0c97\u0cc1\u0cb0\u0cc1\u0cb5\u0cbe\u0cb0",
"\u0cb6\u0cc1\u0c95\u0ccd\u0cb0\u0cb5\u0cbe\u0cb0",
"\u0cb6\u0ca8\u0cbf\u0cb5\u0cbe\u0cb0"
],
"MONTH": [
"\u0c9c\u0ca8\u0cb5\u0cb0\u0cc0",
"\u0cab\u0cc6\u0cac\u0ccd\u0cb0\u0cb5\u0cb0\u0cc0",
"\u0cae\u0cbe\u0cb0\u0ccd\u0c9a\u0ccd",
"\u0c8e\u0caa\u0ccd\u0cb0\u0cbf\u0cb2\u0ccd",
"\u0cae\u0cc6",
"\u0c9c\u0cc2\u0ca8\u0ccd",
"\u0c9c\u0cc1\u0cb2\u0cc8",
"\u0c86\u0c97\u0cb8\u0ccd\u0c9f\u0ccd",
"\u0cb8\u0caa\u0ccd\u0c9f\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0c85\u0c95\u0ccd\u0c9f\u0ccb\u0cac\u0cb0\u0ccd",
"\u0ca8\u0cb5\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0ca1\u0cbf\u0cb8\u0cc6\u0c82\u0cac\u0cb0\u0ccd"
],
"SHORTDAY": [
"\u0cb0.",
"\u0cb8\u0ccb.",
"\u0cae\u0c82.",
"\u0cac\u0cc1.",
"\u0c97\u0cc1.",
"\u0cb6\u0cc1.",
"\u0cb6\u0ca8\u0cbf."
],
"SHORTMONTH": [
"\u0c9c\u0ca8\u0cb5\u0cb0\u0cc0",
"\u0cab\u0cc6\u0cac\u0ccd\u0cb0\u0cb5\u0cb0\u0cc0",
"\u0cae\u0cbe\u0cb0\u0ccd\u0c9a\u0ccd",
"\u0c8e\u0caa\u0ccd\u0cb0\u0cbf\u0cb2\u0ccd",
"\u0cae\u0cc6",
"\u0c9c\u0cc2\u0ca8\u0ccd",
"\u0c9c\u0cc1\u0cb2\u0cc8",
"\u0c86\u0c97\u0cb8\u0ccd\u0c9f\u0ccd",
"\u0cb8\u0caa\u0ccd\u0c9f\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0c85\u0c95\u0ccd\u0c9f\u0ccb\u0cac\u0cb0\u0ccd",
"\u0ca8\u0cb5\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0ca1\u0cbf\u0cb8\u0cc6\u0c82\u0cac\u0cb0\u0ccd"
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y hh:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "hh:mm:ss a",
"short": "d-M-yy hh:mm a",
"shortDate": "d-M-yy",
"shortTime": "hh:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "kn-in",
"pluralCat": function (n) { return PLURAL_CATEGORY.OTHER;}
});
}]); | Ryuno-Ki/cdnjs | ajax/libs/angular-i18n/1.2.3/angular-locale_kn-in.js | JavaScript | mit | 2,945 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u03c0.\u03bc.",
"\u03bc.\u03bc."
],
"DAY": [
"\u039a\u03c5\u03c1\u03b9\u03b1\u03ba\u03ae",
"\u0394\u03b5\u03c5\u03c4\u03ad\u03c1\u03b1",
"\u03a4\u03c1\u03af\u03c4\u03b7",
"\u03a4\u03b5\u03c4\u03ac\u03c1\u03c4\u03b7",
"\u03a0\u03ad\u03bc\u03c0\u03c4\u03b7",
"\u03a0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae",
"\u03a3\u03ac\u03b2\u03b2\u03b1\u03c4\u03bf"
],
"MONTH": [
"\u0399\u03b1\u03bd\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u03a6\u03b5\u03b2\u03c1\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u039c\u03b1\u03c1\u03c4\u03af\u03bf\u03c5",
"\u0391\u03c0\u03c1\u03b9\u03bb\u03af\u03bf\u03c5",
"\u039c\u03b1\u0390\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bd\u03af\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bb\u03af\u03bf\u03c5",
"\u0391\u03c5\u03b3\u03bf\u03cd\u03c3\u03c4\u03bf\u03c5",
"\u03a3\u03b5\u03c0\u03c4\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039f\u03ba\u03c4\u03c9\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039d\u03bf\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u0394\u03b5\u03ba\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5"
],
"SHORTDAY": [
"\u039a\u03c5\u03c1",
"\u0394\u03b5\u03c5",
"\u03a4\u03c1\u03b9",
"\u03a4\u03b5\u03c4",
"\u03a0\u03b5\u03bc",
"\u03a0\u03b1\u03c1",
"\u03a3\u03b1\u03b2"
],
"SHORTMONTH": [
"\u0399\u03b1\u03bd",
"\u03a6\u03b5\u03b2",
"\u039c\u03b1\u03c1",
"\u0391\u03c0\u03c1",
"\u039c\u03b1\u03ca",
"\u0399\u03bf\u03c5\u03bd",
"\u0399\u03bf\u03c5\u03bb",
"\u0391\u03c5\u03b3",
"\u03a3\u03b5\u03c0",
"\u039f\u03ba\u03c4",
"\u039d\u03bf\u03b5",
"\u0394\u03b5\u03ba"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "el-gr",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | kiwi89/cdnjs | ajax/libs/angular.js/1.2.4/i18n/angular-locale_el-gr.js | JavaScript | mit | 3,030 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-fm",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | perdona/cdnjs | ajax/libs/angular-i18n/1.2.7/angular-locale_en-fm.js | JavaScript | mit | 1,915 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-cd",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | SaravananRajaraman/cdnjs | ajax/libs/angular.js/1.3.0-beta.8/i18n/angular-locale_fr-cd.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"a.m.",
"p.m."
],
"DAY": [
"domingo",
"lunes",
"martes",
"mi\u00e9rcoles",
"jueves",
"viernes",
"s\u00e1bado"
],
"MONTH": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"SHORTDAY": [
"dom",
"lun",
"mar",
"mi\u00e9",
"jue",
"vie",
"s\u00e1b"
],
"SHORTMONTH": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"fullDate": "EEEE, d 'de' MMMM 'de' y",
"longDate": "d 'de' MMMM 'de' y",
"medium": "dd/MM/yyyy HH:mm:ss",
"mediumDate": "dd/MM/yyyy",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "es-ic",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | tresni/cdnjs | ajax/libs/angular.js/1.2.12/i18n/angular-locale_es-ic.js | JavaScript | mit | 1,976 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"a.m.",
"p.m."
],
"DAY": [
"domingo",
"lunes",
"martes",
"mi\u00e9rcoles",
"jueves",
"viernes",
"s\u00e1bado"
],
"MONTH": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"SHORTDAY": [
"dom",
"lun",
"mar",
"mi\u00e9",
"jue",
"vie",
"s\u00e1b"
],
"SHORTMONTH": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"fullDate": "EEEE, d 'de' MMMM 'de' y",
"longDate": "d 'de' MMMM 'de' y",
"medium": "dd/MM/yyyy HH:mm:ss",
"mediumDate": "dd/MM/yyyy",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "es-ar",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | HealthIndicators/cdnjs | ajax/libs/angular.js/1.2.8/i18n/angular-locale_es-ar.js | JavaScript | mit | 1,976 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, d MMMM, y",
"longDate": "d MMMM, y",
"medium": "d MMM, y h:mm:ss a",
"mediumDate": "d MMM, y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-sg",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | quba/cdnjs | ajax/libs/angular.js/1.3.0-beta.2/i18n/angular-locale_en-sg.js | JavaScript | mit | 1,915 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"am",
"pm"
],
"DAY": [
"\u0cb0\u0cb5\u0cbf\u0cb5\u0cbe\u0cb0",
"\u0cb8\u0ccb\u0cae\u0cb5\u0cbe\u0cb0",
"\u0cae\u0c82\u0c97\u0cb3\u0cb5\u0cbe\u0cb0",
"\u0cac\u0cc1\u0ca7\u0cb5\u0cbe\u0cb0",
"\u0c97\u0cc1\u0cb0\u0cc1\u0cb5\u0cbe\u0cb0",
"\u0cb6\u0cc1\u0c95\u0ccd\u0cb0\u0cb5\u0cbe\u0cb0",
"\u0cb6\u0ca8\u0cbf\u0cb5\u0cbe\u0cb0"
],
"MONTH": [
"\u0c9c\u0ca8\u0cb5\u0cb0\u0cc0",
"\u0cab\u0cc6\u0cac\u0ccd\u0cb0\u0cb5\u0cb0\u0cc0",
"\u0cae\u0cbe\u0cb0\u0ccd\u0c9a\u0ccd",
"\u0c8e\u0caa\u0ccd\u0cb0\u0cbf\u0cb2\u0ccd",
"\u0cae\u0cc6",
"\u0c9c\u0cc2\u0ca8\u0ccd",
"\u0c9c\u0cc1\u0cb2\u0cc8",
"\u0c86\u0c97\u0cb8\u0ccd\u0c9f\u0ccd",
"\u0cb8\u0caa\u0ccd\u0c9f\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0c85\u0c95\u0ccd\u0c9f\u0ccb\u0cac\u0cb0\u0ccd",
"\u0ca8\u0cb5\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0ca1\u0cbf\u0cb8\u0cc6\u0c82\u0cac\u0cb0\u0ccd"
],
"SHORTDAY": [
"\u0cb0.",
"\u0cb8\u0ccb.",
"\u0cae\u0c82.",
"\u0cac\u0cc1.",
"\u0c97\u0cc1.",
"\u0cb6\u0cc1.",
"\u0cb6\u0ca8\u0cbf."
],
"SHORTMONTH": [
"\u0c9c\u0ca8\u0cb5\u0cb0\u0cc0",
"\u0cab\u0cc6\u0cac\u0ccd\u0cb0\u0cb5\u0cb0\u0cc0",
"\u0cae\u0cbe\u0cb0\u0ccd\u0c9a\u0ccd",
"\u0c8e\u0caa\u0ccd\u0cb0\u0cbf\u0cb2\u0ccd",
"\u0cae\u0cc6",
"\u0c9c\u0cc2\u0ca8\u0ccd",
"\u0c9c\u0cc1\u0cb2\u0cc8",
"\u0c86\u0c97\u0cb8\u0ccd\u0c9f\u0ccd",
"\u0cb8\u0caa\u0ccd\u0c9f\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0c85\u0c95\u0ccd\u0c9f\u0ccb\u0cac\u0cb0\u0ccd",
"\u0ca8\u0cb5\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0ca1\u0cbf\u0cb8\u0cc6\u0c82\u0cac\u0cb0\u0ccd"
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y hh:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "hh:mm:ss a",
"short": "d-M-yy hh:mm a",
"shortDate": "d-M-yy",
"shortTime": "hh:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "kn-in",
"pluralCat": function (n) { return PLURAL_CATEGORY.OTHER;}
});
}]); | tambien/cdnjs | ajax/libs/angular.js/1.2.24/i18n/angular-locale_kn-in.js | JavaScript | mit | 2,945 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"a.m.",
"p.m."
],
"DAY": [
"domingo",
"lunes",
"martes",
"mi\u00e9rcoles",
"jueves",
"viernes",
"s\u00e1bado"
],
"MONTH": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"SHORTDAY": [
"dom",
"lun",
"mar",
"mi\u00e9",
"jue",
"vie",
"s\u00e1b"
],
"SHORTMONTH": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"fullDate": "EEEE, d 'de' MMMM 'de' y",
"longDate": "d 'de' MMMM 'de' y",
"medium": "dd/MM/yyyy HH:mm:ss",
"mediumDate": "dd/MM/yyyy",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "es-ea",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | kiwi89/cdnjs | ajax/libs/angular.js/1.3.0-beta.4/i18n/angular-locale_es-ea.js | JavaScript | mit | 1,976 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"vm.",
"nm."
],
"DAY": [
"Sondag",
"Maandag",
"Dinsdag",
"Woensdag",
"Donderdag",
"Vrydag",
"Saterdag"
],
"MONTH": [
"Januarie",
"Februarie",
"Maart",
"April",
"Mei",
"Junie",
"Julie",
"Augustus",
"September",
"Oktober",
"November",
"Desember"
],
"SHORTDAY": [
"So",
"Ma",
"Di",
"Wo",
"Do",
"Vr",
"Sa"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"Mei",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Des"
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "yyyy-MM-dd HH:mm",
"shortDate": "yyyy-MM-dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "R",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "af-na",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | redmunds/cdnjs | ajax/libs/angular-i18n/1.2.8/angular-locale_af-na.js | JavaScript | mit | 1,921 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"nedjelja",
"ponedjeljak",
"utorak",
"srijeda",
"\u010detvrtak",
"petak",
"subota"
],
"MONTH": [
"sije\u010dnja",
"velja\u010de",
"o\u017eujka",
"travnja",
"svibnja",
"lipnja",
"srpnja",
"kolovoza",
"rujna",
"listopada",
"studenoga",
"prosinca"
],
"SHORTDAY": [
"ned",
"pon",
"uto",
"sri",
"\u010det",
"pet",
"sub"
],
"SHORTMONTH": [
"sij",
"velj",
"o\u017eu",
"tra",
"svi",
"lip",
"srp",
"kol",
"ruj",
"lis",
"stu",
"pro"
],
"fullDate": "EEEE, d. MMMM y.",
"longDate": "d. MMMM y.",
"medium": "d. M. y. HH:mm:ss",
"mediumDate": "d. M. y.",
"mediumTime": "HH:mm:ss",
"short": "d.M.y. HH:mm",
"shortDate": "d.M.y.",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "kn",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "hr-hr",
"pluralCat": function (n) { if (n % 10 == 1 && n % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (n == (n | 0) && n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)) { return PLURAL_CATEGORY.FEW; } if (n % 10 == 0 || n == (n | 0) && n % 10 >= 5 && n % 10 <= 9 || n == (n | 0) && n % 100 >= 11 && n % 100 <= 14) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;}
});
}]); | HealthIndicators/cdnjs | ajax/libs/angular.js/1.2.6/i18n/angular-locale_hr-hr.js | JavaScript | mit | 2,259 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"am",
"pm"
],
"DAY": [
"\u0930\u0935\u093f\u0935\u093e\u0930",
"\u0938\u094b\u092e\u0935\u093e\u0930",
"\u092e\u0902\u0917\u0932\u0935\u093e\u0930",
"\u092c\u0941\u0927\u0935\u093e\u0930",
"\u092c\u0943\u0939\u0938\u094d\u092a\u0924\u093f\u0935\u093e\u0930",
"\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930",
"\u0936\u0928\u093f\u0935\u093e\u0930"
],
"MONTH": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0930\u0935\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u0948\u0932",
"\u092e\u0908",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u0924",
"\u0938\u093f\u0924\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u0924\u0942\u092c\u0930",
"\u0928\u0935\u092e\u094d\u092c\u0930",
"\u0926\u093f\u0938\u092e\u094d\u092c\u0930"
],
"SHORTDAY": [
"\u0930\u0935\u093f.",
"\u0938\u094b\u092e.",
"\u092e\u0902\u0917\u0932.",
"\u092c\u0941\u0927.",
"\u092c\u0943\u0939.",
"\u0936\u0941\u0915\u094d\u0930.",
"\u0936\u0928\u093f."
],
"SHORTMONTH": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0930\u0935\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u0948\u0932",
"\u092e\u0908",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u0924",
"\u0938\u093f\u0924\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u0924\u0942\u092c\u0930",
"\u0928\u0935\u092e\u094d\u092c\u0930",
"\u0926\u093f\u0938\u092e\u094d\u092c\u0930"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "dd-MM-yyyy h:mm:ss a",
"mediumDate": "dd-MM-yyyy",
"mediumTime": "h:mm:ss a",
"short": "d-M-yy h:mm a",
"shortDate": "d-M-yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "hi-in",
"pluralCat": function (n) { if (n == 0 || n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | jackdoyle/cdnjs | ajax/libs/angular.js/1.2.7/i18n/angular-locale_hi-in.js | JavaScript | mit | 2,969 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u03c0.\u03bc.",
"\u03bc.\u03bc."
],
"DAY": [
"\u039a\u03c5\u03c1\u03b9\u03b1\u03ba\u03ae",
"\u0394\u03b5\u03c5\u03c4\u03ad\u03c1\u03b1",
"\u03a4\u03c1\u03af\u03c4\u03b7",
"\u03a4\u03b5\u03c4\u03ac\u03c1\u03c4\u03b7",
"\u03a0\u03ad\u03bc\u03c0\u03c4\u03b7",
"\u03a0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae",
"\u03a3\u03ac\u03b2\u03b2\u03b1\u03c4\u03bf"
],
"MONTH": [
"\u0399\u03b1\u03bd\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u03a6\u03b5\u03b2\u03c1\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u039c\u03b1\u03c1\u03c4\u03af\u03bf\u03c5",
"\u0391\u03c0\u03c1\u03b9\u03bb\u03af\u03bf\u03c5",
"\u039c\u03b1\u0390\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bd\u03af\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bb\u03af\u03bf\u03c5",
"\u0391\u03c5\u03b3\u03bf\u03cd\u03c3\u03c4\u03bf\u03c5",
"\u03a3\u03b5\u03c0\u03c4\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039f\u03ba\u03c4\u03c9\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039d\u03bf\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u0394\u03b5\u03ba\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5"
],
"SHORTDAY": [
"\u039a\u03c5\u03c1",
"\u0394\u03b5\u03c5",
"\u03a4\u03c1\u03b9",
"\u03a4\u03b5\u03c4",
"\u03a0\u03b5\u03bc",
"\u03a0\u03b1\u03c1",
"\u03a3\u03b1\u03b2"
],
"SHORTMONTH": [
"\u0399\u03b1\u03bd",
"\u03a6\u03b5\u03b2",
"\u039c\u03b1\u03c1",
"\u0391\u03c0\u03c1",
"\u039c\u03b1\u03ca",
"\u0399\u03bf\u03c5\u03bd",
"\u0399\u03bf\u03c5\u03bb",
"\u0391\u03c5\u03b3",
"\u03a3\u03b5\u03c0",
"\u039f\u03ba\u03c4",
"\u039d\u03bf\u03b5",
"\u0394\u03b5\u03ba"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "el-gr",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | dhenson02/cdnjs | ajax/libs/angular-i18n/1.3.0-beta.7/angular-locale_el-gr.js | JavaScript | mit | 3,030 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-mp",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | eduardo-costa/cdnjs | ajax/libs/angular.js/1.3.0-beta.6/i18n/angular-locale_en-mp.js | JavaScript | mit | 1,915 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-bl",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | callumacrae/cdnjs | ajax/libs/angular.js/1.2.4/i18n/angular-locale_fr-bl.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"am",
"pm"
],
"DAY": [
"\u0930\u0935\u093f\u0935\u093e\u0930",
"\u0938\u094b\u092e\u0935\u093e\u0930",
"\u092e\u0902\u0917\u0932\u0935\u093e\u0930",
"\u092c\u0941\u0927\u0935\u093e\u0930",
"\u092c\u0943\u0939\u0938\u094d\u092a\u0924\u093f\u0935\u093e\u0930",
"\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930",
"\u0936\u0928\u093f\u0935\u093e\u0930"
],
"MONTH": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0930\u0935\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u0948\u0932",
"\u092e\u0908",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u0924",
"\u0938\u093f\u0924\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u0924\u0942\u092c\u0930",
"\u0928\u0935\u092e\u094d\u092c\u0930",
"\u0926\u093f\u0938\u092e\u094d\u092c\u0930"
],
"SHORTDAY": [
"\u0930\u0935\u093f.",
"\u0938\u094b\u092e.",
"\u092e\u0902\u0917\u0932.",
"\u092c\u0941\u0927.",
"\u092c\u0943\u0939.",
"\u0936\u0941\u0915\u094d\u0930.",
"\u0936\u0928\u093f."
],
"SHORTMONTH": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0930\u0935\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u0948\u0932",
"\u092e\u0908",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u0924",
"\u0938\u093f\u0924\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u0924\u0942\u092c\u0930",
"\u0928\u0935\u092e\u094d\u092c\u0930",
"\u0926\u093f\u0938\u092e\u094d\u092c\u0930"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "dd-MM-yyyy h:mm:ss a",
"mediumDate": "dd-MM-yyyy",
"mediumTime": "h:mm:ss a",
"short": "d-M-yy h:mm a",
"shortDate": "d-M-yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "hi-in",
"pluralCat": function (n) { if (n == 0 || n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | johan-gorter/cdnjs | ajax/libs/angular.js/1.3.0-beta.9/i18n/angular-locale_hi-in.js | JavaScript | mit | 2,969 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-dj",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | barcadictni/cdnjs | ajax/libs/angular.js/1.3.0-beta.9/i18n/angular-locale_fr-dj.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-cg",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | sujonvidia/cdnjs | ajax/libs/angular.js/1.2.7/i18n/angular-locale_fr-cg.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-gy",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | EragonJ/cdnjs | ajax/libs/angular-i18n/1.2.5/angular-locale_en-gy.js | JavaScript | mit | 1,915 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u03c0.\u03bc.",
"\u03bc.\u03bc."
],
"DAY": [
"\u039a\u03c5\u03c1\u03b9\u03b1\u03ba\u03ae",
"\u0394\u03b5\u03c5\u03c4\u03ad\u03c1\u03b1",
"\u03a4\u03c1\u03af\u03c4\u03b7",
"\u03a4\u03b5\u03c4\u03ac\u03c1\u03c4\u03b7",
"\u03a0\u03ad\u03bc\u03c0\u03c4\u03b7",
"\u03a0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae",
"\u03a3\u03ac\u03b2\u03b2\u03b1\u03c4\u03bf"
],
"MONTH": [
"\u0399\u03b1\u03bd\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u03a6\u03b5\u03b2\u03c1\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u039c\u03b1\u03c1\u03c4\u03af\u03bf\u03c5",
"\u0391\u03c0\u03c1\u03b9\u03bb\u03af\u03bf\u03c5",
"\u039c\u03b1\u0390\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bd\u03af\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bb\u03af\u03bf\u03c5",
"\u0391\u03c5\u03b3\u03bf\u03cd\u03c3\u03c4\u03bf\u03c5",
"\u03a3\u03b5\u03c0\u03c4\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039f\u03ba\u03c4\u03c9\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039d\u03bf\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u0394\u03b5\u03ba\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5"
],
"SHORTDAY": [
"\u039a\u03c5\u03c1",
"\u0394\u03b5\u03c5",
"\u03a4\u03c1\u03b9",
"\u03a4\u03b5\u03c4",
"\u03a0\u03b5\u03bc",
"\u03a0\u03b1\u03c1",
"\u03a3\u03b1\u03b2"
],
"SHORTMONTH": [
"\u0399\u03b1\u03bd",
"\u03a6\u03b5\u03b2",
"\u039c\u03b1\u03c1",
"\u0391\u03c0\u03c1",
"\u039c\u03b1\u03ca",
"\u0399\u03bf\u03c5\u03bd",
"\u0399\u03bf\u03c5\u03bb",
"\u0391\u03c5\u03b3",
"\u03a3\u03b5\u03c0",
"\u039f\u03ba\u03c4",
"\u039d\u03bf\u03b5",
"\u0394\u03b5\u03ba"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "el-gr",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | tmorin/cdnjs | ajax/libs/angular-i18n/1.2.16/angular-locale_el-gr.js | JavaScript | mit | 3,030 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-mh",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | jasonpang/cdnjs | ajax/libs/angular-i18n/1.3.0-beta.9/angular-locale_en-mh.js | JavaScript | mit | 1,915 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": "\u00a0\u00a4)",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-bl",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | chrillep/cdnjs | ajax/libs/angular.js/1.3.0-beta.6/i18n/angular-locale_fr-bl.js | JavaScript | mit | 1,998 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-um",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | sajochiu/cdnjs | ajax/libs/angular-i18n/1.2.9/angular-locale_en-um.js | JavaScript | mit | 1,915 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0635",
"\u0645"
],
"DAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"MONTH": [
"\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u062b\u0627\u0646\u064a",
"\u0634\u0628\u0627\u0637",
"\u0622\u0630\u0627\u0631",
"\u0646\u064a\u0633\u0627\u0646",
"\u0623\u064a\u0627\u0631",
"\u062d\u0632\u064a\u0631\u0627\u0646",
"\u062a\u0645\u0648\u0632",
"\u0622\u0628",
"\u0623\u064a\u0644\u0648\u0644",
"\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u0623\u0648\u0644",
"\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u062b\u0627\u0646\u064a",
"\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u0623\u0648\u0644"
],
"SHORTDAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"SHORTMONTH": [
"\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u062b\u0627\u0646\u064a",
"\u0634\u0628\u0627\u0637",
"\u0622\u0630\u0627\u0631",
"\u0646\u064a\u0633\u0627\u0646",
"\u0623\u064a\u0627\u0631",
"\u062d\u0632\u064a\u0631\u0627\u0646",
"\u062a\u0645\u0648\u0632",
"\u0622\u0628",
"\u0623\u064a\u0644\u0648\u0644",
"\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u0623\u0648\u0644",
"\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u062b\u0627\u0646\u064a",
"\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u0623\u0648\u0644"
],
"fullDate": "EEEE\u060c d MMMM\u060c y",
"longDate": "d MMMM\u060c y",
"medium": "dd\u200f/MM\u200f/yyyy h:mm:ss a",
"mediumDate": "dd\u200f/MM\u200f/yyyy",
"mediumTime": "h:mm:ss a",
"short": "d\u200f/M\u200f/yyyy h:mm a",
"shortDate": "d\u200f/M\u200f/yyyy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u00a3",
"DECIMAL_SEP": "\u066b",
"GROUP_SEP": "\u066c",
"PATTERNS": [
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "",
"negSuf": "-",
"posPre": "",
"posSuf": ""
},
{
"gSize": 0,
"lgSize": 0,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0",
"negSuf": "-",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "ar-sy",
"pluralCat": function (n) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n == (n | 0) && n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n == (n | 0) && n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;}
});
}]); | Sneezry/cdnjs | ajax/libs/angular.js/1.3.0-beta.7/i18n/angular-locale_ar-sy.js | JavaScript | mit | 3,572 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"f.m.",
"e.m."
],
"DAY": [
"s\u00f8ndag",
"mandag",
"tirsdag",
"onsdag",
"torsdag",
"fredag",
"l\u00f8rdag"
],
"MONTH": [
"januar",
"februar",
"marts",
"april",
"maj",
"juni",
"juli",
"august",
"september",
"oktober",
"november",
"december"
],
"SHORTDAY": [
"s\u00f8n",
"man",
"tir",
"ons",
"tor",
"fre",
"l\u00f8r"
],
"SHORTMONTH": [
"jan.",
"feb.",
"mar.",
"apr.",
"maj",
"jun.",
"jul.",
"aug.",
"sep.",
"okt.",
"nov.",
"dec."
],
"fullDate": "EEEE 'den' d. MMMM y",
"longDate": "d. MMM y",
"medium": "dd/MM/yyyy HH.mm.ss",
"mediumDate": "dd/MM/yyyy",
"mediumTime": "HH.mm.ss",
"short": "dd/MM/yy HH.mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH.mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "kr",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "da-dk",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | xeodou/cdnjs | ajax/libs/angular.js/1.3.0-beta.5/i18n/angular-locale_da-dk.js | JavaScript | mit | 1,962 |
/*
* Copyright © 2008 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file hash_table.c
* \brief Implementation of a generic, opaque hash table data type.
*
* \author Ian Romanick <ian.d.romanick@intel.com>
*/
#include "main/errors.h"
#include "main/simple_list.h"
#include "hash_table.h"
struct node {
struct node *next;
struct node *prev;
};
struct hash_table {
hash_func_t hash;
hash_compare_func_t compare;
unsigned num_buckets;
struct node buckets[1];
};
struct hash_node {
struct node link;
const void *key;
void *data;
};
struct hash_table *
hash_table_ctor(unsigned num_buckets, hash_func_t hash,
hash_compare_func_t compare)
{
struct hash_table *ht;
unsigned i;
if (num_buckets < 16) {
num_buckets = 16;
}
ht = malloc(sizeof(*ht) + ((num_buckets - 1)
* sizeof(ht->buckets[0])));
if (ht != NULL) {
ht->hash = hash;
ht->compare = compare;
ht->num_buckets = num_buckets;
for (i = 0; i < num_buckets; i++) {
make_empty_list(& ht->buckets[i]);
}
}
return ht;
}
void
hash_table_dtor(struct hash_table *ht)
{
if (!ht)
return;
hash_table_clear(ht);
free(ht);
}
void
hash_table_clear(struct hash_table *ht)
{
struct node *node;
struct node *temp;
unsigned i;
for (i = 0; i < ht->num_buckets; i++) {
foreach_s(node, temp, & ht->buckets[i]) {
remove_from_list(node);
free(node);
}
assert(is_empty_list(& ht->buckets[i]));
}
}
static struct hash_node *
get_node(struct hash_table *ht, const void *key)
{
const unsigned hash_value = (*ht->hash)(key);
const unsigned bucket = hash_value % ht->num_buckets;
struct node *node;
foreach(node, & ht->buckets[bucket]) {
struct hash_node *hn = (struct hash_node *) node;
if ((*ht->compare)(hn->key, key) == 0) {
return hn;
}
}
return NULL;
}
void *
hash_table_find(struct hash_table *ht, const void *key)
{
struct hash_node *hn = get_node(ht, key);
return (hn == NULL) ? NULL : hn->data;
}
void
hash_table_insert(struct hash_table *ht, void *data, const void *key)
{
const unsigned hash_value = (*ht->hash)(key);
const unsigned bucket = hash_value % ht->num_buckets;
struct hash_node *node;
node = calloc(1, sizeof(*node));
if (node == NULL) {
_mesa_error_no_memory(__func__);
return;
}
node->data = data;
node->key = key;
insert_at_head(& ht->buckets[bucket], & node->link);
}
bool
hash_table_replace(struct hash_table *ht, void *data, const void *key)
{
const unsigned hash_value = (*ht->hash)(key);
const unsigned bucket = hash_value % ht->num_buckets;
struct node *node;
struct hash_node *hn;
foreach(node, & ht->buckets[bucket]) {
hn = (struct hash_node *) node;
if ((*ht->compare)(hn->key, key) == 0) {
hn->data = data;
return true;
}
}
hn = calloc(1, sizeof(*hn));
if (hn == NULL) {
_mesa_error_no_memory(__func__);
return false;
}
hn->data = data;
hn->key = key;
insert_at_head(& ht->buckets[bucket], & hn->link);
return false;
}
void
hash_table_remove(struct hash_table *ht, const void *key)
{
struct node *node = (struct node *) get_node(ht, key);
if (node != NULL) {
remove_from_list(node);
free(node);
return;
}
}
void
hash_table_call_foreach(struct hash_table *ht,
void (*callback)(const void *key,
void *data,
void *closure),
void *closure)
{
unsigned bucket;
for (bucket = 0; bucket < (int)ht->num_buckets; bucket++) {
struct node *node, *temp;
foreach_s(node, temp, &ht->buckets[bucket]) {
struct hash_node *hn = (struct hash_node *) node;
callback(hn->key, hn->data, closure);
}
}
}
unsigned
hash_table_string_hash(const void *key)
{
const char *str = (const char *) key;
unsigned hash = 5381;
while (*str != '\0') {
hash = (hash * 33) + *str;
str++;
}
return hash;
}
unsigned
hash_table_pointer_hash(const void *key)
{
return (unsigned)((uintptr_t) key / sizeof(void *));
}
int
hash_table_pointer_compare(const void *key1, const void *key2)
{
return key1 == key2 ? 0 : 1;
}
| andr3wmac/Torque6 | lib/bgfx/3rdparty/glsl-optimizer/src/mesa/program/prog_hash_table.c | C | mit | 5,401 |
// locale_info.cpp ---------------------------------------------------------//
// Copyright Beman Dawes 2011
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#include <locale>
#include <iostream>
#include <exception>
#include <cstdlib>
using namespace std;
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4996) // ... Function call with parameters that may be unsafe
#endif
namespace
{
void facet_info(const locale& loc, const char* msg)
{
cout << "has_facet<std::codecvt<wchar_t, char, std::mbstate_t> >("
<< msg << ") is "
<< (has_facet<std::codecvt<wchar_t, char, std::mbstate_t> >(loc)
? "true\n"
: "false\n");
}
void default_info()
{
try
{
locale loc;
cout << "\nlocale default construction OK" << endl;
facet_info(loc, "locale()");
}
catch (const exception& ex)
{
cout << "\nlocale default construction threw: " << ex.what() << endl;
}
}
void null_string_info()
{
try
{
locale loc("");
cout << "\nlocale(\"\") construction OK" << endl;
facet_info(loc, "locale(\"\")");
}
catch (const exception& ex)
{
cout << "\nlocale(\"\") construction threw: " << ex.what() << endl;
}
}
void classic_info()
{
try
{
locale loc(locale::classic());
cout << "\nlocale(locale::classic()) copy construction OK" << endl;
facet_info(loc, "locale::classic()");
}
catch (const exception& ex)
{
cout << "\nlocale(locale::clasic()) copy construction threw: " << ex.what() << endl;
}
}
}
int main()
{
const char* lang = getenv("LANG");
cout << "\nLANG environmental variable is "
<< (lang ? lang : "not present") << endl;
default_info();
null_string_info();
classic_info();
return 0;
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
| hand-iemura/lightpng | boost_1_53_0/libs/filesystem/test/locale_info.cpp | C++ | mit | 1,925 |
/*
Highstock JS v1.3.10 (2014-03-10)
Standalone Highcharts Framework
License: MIT License
*/
var HighchartsAdapter=function(){function o(c){function b(b,a,d){b.removeEventListener(a,d,!1)}function d(b,a,d){d=b.HCProxiedMethods[d.toString()];b.detachEvent("on"+a,d)}function a(a,c){var f=a.HCEvents,i,g,k,j;if(a.removeEventListener)i=b;else if(a.attachEvent)i=d;else return;c?(g={},g[c]=!0):g=f;for(j in g)if(f[j])for(k=f[j].length;k--;)i(a,j,f[j][k])}c.HCExtended||Highcharts.extend(c,{HCExtended:!0,HCEvents:{},bind:function(b,a){var d=this,c=this.HCEvents,g;if(d.addEventListener)d.addEventListener(b,
a,!1);else if(d.attachEvent){g=function(b){a.call(d,b)};if(!d.HCProxiedMethods)d.HCProxiedMethods={};d.HCProxiedMethods[a.toString()]=g;d.attachEvent("on"+b,g)}c[b]===r&&(c[b]=[]);c[b].push(a)},unbind:function(c,h){var f,i;c?(f=this.HCEvents[c]||[],h?(i=HighchartsAdapter.inArray(h,f),i>-1&&(f.splice(i,1),this.HCEvents[c]=f),this.removeEventListener?b(this,c,h):this.attachEvent&&d(this,c,h)):(a(this,c),this.HCEvents[c]=[])):(a(this),this.HCEvents={})},trigger:function(b,a){var d=this.HCEvents[b]||
[],c=d.length,g,k,j;k=function(){a.defaultPrevented=!0};for(g=0;g<c;g++){j=d[g];if(a.stopped)break;a.preventDefault=k;a.target=this;if(!a.type)a.type=b;j.call(this,a)===!1&&a.preventDefault()}}});return c}var r,l=document,p=[],m=[],q,n;Math.easeInOutSine=function(c,b,d,a){return-d/2*(Math.cos(Math.PI*c/a)-1)+b};return{init:function(c){if(!l.defaultView)this._getStyle=function(b,d){var a;return b.style[d]?b.style[d]:(d==="opacity"&&(d="filter"),a=b.currentStyle[d.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()})],
d==="filter"&&(a=a.replace(/alpha\(opacity=([0-9]+)\)/,function(a,b){return b/100})),a===""?1:a)},this.adapterRun=function(b,d){var a={width:"clientWidth",height:"clientHeight"}[d];if(a)return b.style.zoom=1,b[a]-2*parseInt(HighchartsAdapter._getStyle(b,"padding"),10)};if(!Array.prototype.forEach)this.each=function(b,d){for(var a=0,c=b.length;a<c;a++)if(d.call(b[a],b[a],a,b)===!1)return a};if(!Array.prototype.indexOf)this.inArray=function(b,d){var a,c=0;if(d)for(a=d.length;c<a;c++)if(d[c]===b)return c;
return-1};if(!Array.prototype.filter)this.grep=function(b,d){for(var a=[],c=0,h=b.length;c<h;c++)d(b[c],c)&&a.push(b[c]);return a};n=function(b,c,a){this.options=c;this.elem=b;this.prop=a};n.prototype={update:function(){var b;b=this.paths;var d=this.elem,a=d.element;b&&a?d.attr("d",c.step(b[0],b[1],this.now,this.toD)):d.attr?a&&d.attr(this.prop,this.now):(b={},b[this.prop]=this.now+this.unit,Highcharts.css(d,b));this.options.step&&this.options.step.call(this.elem,this.now,this)},custom:function(b,
c,a){var e=this,h=function(a){return e.step(a)},f;this.startTime=+new Date;this.start=b;this.end=c;this.unit=a;this.now=this.start;this.pos=this.state=0;h.elem=this.elem;h()&&m.push(h)===1&&(q=setInterval(function(){for(f=0;f<m.length;f++)m[f]()||m.splice(f--,1);m.length||clearInterval(q)},13))},step:function(b){var c=+new Date,a;a=this.options;var e=this.elem,h;if(e.stopAnimation||e.attr&&!e.element)a=!1;else if(b||c>=a.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();
b=this.options.curAnim[this.prop]=!0;for(h in a.curAnim)a.curAnim[h]!==!0&&(b=!1);b&&a.complete&&a.complete.call(e);a=!1}else e=c-this.startTime,this.state=e/a.duration,this.pos=a.easing(e,0,1,a.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update(),a=!0;return a}};this.animate=function(b,d,a){var e,h="",f,i,g;b.stopAnimation=!1;if(typeof a!=="object"||a===null)e=arguments,a={duration:e[2],easing:e[3],complete:e[4]};if(typeof a.duration!=="number")a.duration=400;a.easing=Math[a.easing]||
Math.easeInOutSine;a.curAnim=Highcharts.extend({},d);for(g in d)i=new n(b,a,g),f=null,g==="d"?(i.paths=c.init(b,b.d,d.d),i.toD=d.d,e=0,f=1):b.attr?e=b.attr(g):(e=parseFloat(HighchartsAdapter._getStyle(b,g))||0,g!=="opacity"&&(h="px")),f||(f=parseFloat(d[g])),i.custom(e,f,h)}},_getStyle:function(c,b){return window.getComputedStyle(c).getPropertyValue(b)},getScript:function(c,b){var d=l.getElementsByTagName("head")[0],a=l.createElement("script");a.type="text/javascript";a.src=c;a.onload=b;d.appendChild(a)},
inArray:function(c,b){return b.indexOf?b.indexOf(c):p.indexOf.call(b,c)},adapterRun:function(c,b){return parseInt(HighchartsAdapter._getStyle(c,b),10)},grep:function(c,b){return p.filter.call(c,b)},map:function(c,b){for(var d=[],a=0,e=c.length;a<e;a++)d[a]=b.call(c[a],c[a],a,c);return d},offset:function(c){var b=document.documentElement,c=c.getBoundingClientRect();return{top:c.top+(window.pageYOffset||b.scrollTop)-(b.clientTop||0),left:c.left+(window.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}},
addEvent:function(c,b,d){o(c).bind(b,d)},removeEvent:function(c,b,d){o(c).unbind(b,d)},fireEvent:function(c,b,d,a){var e;l.createEvent&&(c.dispatchEvent||c.fireEvent)?(e=l.createEvent("Events"),e.initEvent(b,!0,!0),e.target=c,Highcharts.extend(e,d),c.dispatchEvent?c.dispatchEvent(e):c.fireEvent(b,e)):c.HCExtended===!0&&(d=d||{},c.trigger(b,d));d&&d.defaultPrevented&&(a=null);a&&a(d)},washMouseEvent:function(c){return c},stop:function(c){c.stopAnimation=!0},each:function(c,b){return Array.prototype.forEach.call(c,
b)}}}();
| dc-js/cdnjs | ajax/libs/highstock/1.3.10/adapters/standalone-framework.js | JavaScript | mit | 5,208 |
;(function(__root) {
/*
Matreshka Magic v1.4.0 (2015-11-06), the part of Matreshka project
JavaScript Framework by Andrey Gubanov
Released under the MIT license
More info: http://matreshka.io/#magic
*/
var matreshka_dir_core_var_core, matreshka_dir_core_util_common, matreshka_dir_core_var_sym, matreshka_dir_core_bindings_binders, matreshka_dir_polyfills_addeventlistener, matreshka_dir_core_dom_lib_balalaika, matreshka_dir_polyfills_classlist, matreshka_dir_core_dom_lib_balalaika_extended, matreshka_dir_core_dom_lib_dollar_lib, matreshka_dir_core_dom_lib_used_lib, matreshka_dir_core_var_isxdr, matreshka_dir_core_initmk, matreshka_dir_core_definespecial, matreshka_dir_core_util_define, matreshka_dir_core_util_linkprops, matreshka_dir_core_util_mediate, matreshka_dir_core_get_set_remove, matreshka_dir_core_bindings_bindnode, matreshka_dir_core_bindings_unbindnode, matreshka_dir_core_bindings_parsebindings, matreshka_dir_core_bindings_getnodes, matreshka_dir_core_var_domevtreg, matreshka_dir_core_events_trigger, matreshka_dir_core_events_on, matreshka_dir_core_events_off, matreshka_dir_core_var_specialevtreg, matreshka_dir_core_events_addlistener, matreshka_dir_core_events_removelistener, matreshka_dir_core_events_delegatelistener, matreshka_dir_core_events_undelegatelistener, matreshka_dir_core_events_domevents, matreshka_dir_core_events_adddomlistener, matreshka_dir_core_events_removedomlistener, matreshka_dir_core_events_once, matreshka_dir_core_events_ondebounce, matreshka_magic;
matreshka_dir_core_var_core = {};
matreshka_dir_core_util_common = function (core) {
var extend = function (o1, o2) {
var i, j;
if (o1)
for (i = 1; i < arguments.length; i++) {
o2 = arguments[i];
if (o2)
for (j in o2)
if (o2.hasOwnProperty(j)) {
o1[j] = o2[j];
}
}
return o1;
}, util = {
extend: extend,
trim: function (s) {
return s.trim ? s.trim() : s.replace(/^\s+|\s+$/g, '');
},
randomString: function () {
return (new Date().getTime() - new Date(2013, 4, 3).getTime()).toString(36) + Math.floor(Math.random() * 1679616).toString(36);
},
toArray: function (object, start) {
var array = [], l = object.length, i;
start = start || 0;
for (i = start; i < l; i++) {
array[i - start] = object[i];
}
return array;
},
debounce: function (f, d, thisArg) {
var timeout;
if (typeof d !== 'number') {
thisArg = d;
d = 0;
}
return function () {
var args = arguments, ctx = this;
clearTimeout(timeout);
timeout = setTimeout(function () {
f.apply(thisArg || ctx, args);
}, d || 0);
};
},
each: function (o, f, thisArg) {
if (!o)
return;
if (o.isMK && typeof o.each == 'function')
o.each(f, thisArg);
else if ('length' in o)
[].forEach.call(o, f, thisArg);
else
for (var i in o)
if (o.hasOwnProperty(i)) {
f.call(thisArg, o[i], i, o);
}
return o;
},
delay: function (object, f, delay, thisArg) {
if (typeof delay == 'object') {
thisArg = delay;
delay = 0;
}
setTimeout(function () {
f.call(thisArg || object);
}, delay || 0);
return object;
},
deepFind: function (obj, path) {
var paths = path.split('.'), current = obj, i;
for (i = 0; i < paths.length; ++i) {
if (typeof current[paths[i]] == 'undefined') {
return undefined;
} else {
current = current[paths[i]];
}
}
return current;
},
noop: function () {
}
};
extend(core, util);
return util;
}(matreshka_dir_core_var_core);
matreshka_dir_core_var_sym = function (util) {
return typeof Symbol == 'undefined' ? 'mk-' + util.randomString() : Symbol('matreshka');
}(matreshka_dir_core_util_common);
matreshka_dir_core_bindings_binders = function (core) {
var readFiles = function (files, readAs, callback) {
var length = files.length, j = 0, i = 0, filesArray = [], reader, file;
for (; i < length; i++) {
file = files[i];
if (readAs) {
reader = new FileReader();
reader.onloadend = function (evt) {
file.readerResult = reader.result;
filesArray[j++] = file;
if (j == length) {
callback(filesArray);
}
};
reader['readAs' + readAs[0].toUpperCase() + readAs.slice(1)](file);
} else {
filesArray[j++] = file;
if (j == length) {
callback(filesArray);
}
}
}
}, binders,
// cross-browser input event
cbInputEvent = document.documentMode == 8 ? 'keyup paste' : 'input';
// TODO tests
core.binders = binders = {
innerHTML: function () {
// @IE8
return {
on: cbInputEvent,
getValue: function () {
return this.innerHTML;
},
setValue: function (v) {
this.innerHTML = v === null ? '' : v + '';
}
};
},
innerText: function () {
// @IE8
return {
on: cbInputEvent,
getValue: function () {
return this.textContent || this.innerText;
},
setValue: function (v) {
this['textContent' in this ? 'textContent' : 'innerText'] = v === null ? '' : v + '';
}
};
},
className: function (className) {
var not = className.indexOf('!') === 0, contains;
if (not) {
className = className.replace('!', '');
}
return {
on: null,
getValue: function () {
contains = this.classList.contains(className);
return not ? !contains : !!contains;
},
setValue: function (v) {
this.classList.toggle(className, not ? !v : !!v);
}
};
},
property: function (propertyName) {
return {
on: null,
getValue: function () {
return this[propertyName];
},
setValue: function (v) {
// in case when you're trying to set read-only property
try {
this[propertyName] = v;
} catch (e) {
}
}
};
},
attribute: function (attributeName) {
return {
on: null,
getValue: function () {
return this.getAttribute(attributeName);
},
setValue: function (v) {
this.setAttribute(attributeName, v);
}
};
},
dataset: function (prop) {
// replace namesLikeThis with names-like-this
function toDashed(name) {
return 'data-' + name.replace(/([A-Z])/g, function (u) {
return '-' + u.toLowerCase();
});
}
return {
on: null,
getValue: function () {
var _this = this;
return _this.dataset ? _this.dataset[prop] : _this.getAttribute(toDashed(prop));
},
setValue: function (v) {
var _this = this;
if (_this.dataset) {
_this.dataset[prop] = v;
} else {
_this.setAttribute(toDashed(prop), v);
}
}
};
},
textarea: function () {
return binders.input('text');
},
progress: function () {
return binders.input();
},
input: function (type, options) {
var on;
switch (type) {
case 'checkbox':
return {
on: 'click keyup',
getValue: function () {
return this.checked;
},
setValue: function (v) {
this.checked = v;
}
};
case 'radio':
return {
on: 'click keyup',
getValue: function () {
return this.value;
},
setValue: function (v) {
this.checked = this.value == v;
}
};
case 'submit':
case 'button':
case 'image':
case 'reset':
return {};
case 'hidden':
on = null;
break;
case 'file':
on = 'change';
break;
case 'text':
case 'password':
// IE8 requires to use 'keyup paste' instead of 'input'
on = cbInputEvent;
break;
/* case 'date':
case 'datetime':
case 'datetime-local':
case 'month':
case 'time':
case 'week':
case 'range':
case 'color':
case 'search':
case 'email':
case 'tel':
case 'url':
case 'file':
case 'number': */
default:
// other future (HTML6+) inputs
on = 'input';
}
return {
on: on,
getValue: function () {
return this.value;
},
setValue: function (v) {
this.value = v;
}
};
},
output: function () {
// @IE8
return {
getValue: function () {
var _this = this;
return _this.value || _this.textContent || _this.innerText;
},
setValue: function (v) {
var _this = this;
_this['form' in _this ? 'value' : 'textContent' in _this ? 'textContent' : 'innerText'] = v === null ? '' : v + '';
}
};
},
select: function (multiple) {
var i;
if (multiple) {
return {
on: 'change',
getValue: function () {
return [].slice.call(this.options).filter(function (o) {
return o.selected;
}).map(function (o) {
return o.value;
});
},
setValue: function (v) {
v = typeof v == 'string' ? [v] : v;
for (i = this.options.length - 1; i >= 0; i--) {
this.options[i].selected = ~v.indexOf(this.options[i].value);
}
}
};
} else {
return {
on: 'change',
getValue: function () {
return this.value;
},
setValue: function (v) {
var _this = this, options;
_this.value = v;
if (!v) {
options = _this.options;
for (i = options.length - 1; i >= 0; i--) {
if (!options[i].value) {
options[i].selected = true;
}
}
}
}
};
}
},
display: function (value) {
value = typeof value == 'undefined' ? true : value;
return {
on: null,
getValue: function () {
var _this = this, v = _this.style.display || (window.getComputedStyle ? getComputedStyle(_this, null).getPropertyValue('display') : _this.currentStyle.display), none = v == 'none';
return value ? !none : !!none;
},
setValue: function (v) {
this.style.display = value ? v ? '' : 'none' : v ? 'none' : '';
}
};
},
file: function (readAs) {
if (typeof FileList != 'undefined') {
return {
on: function (callback) {
var handler = function () {
var files = this.files;
if (files.length) {
readFiles(files, readAs, function (files) {
callback(files);
});
} else {
callback([]);
}
};
this.addEventListener('change', handler);
},
getValue: function (evt) {
var files = evt.domEvent || [];
return this.multiple ? files : files[0] || null;
}
};
} else {
throw Error('file binder is not supported at this browser');
}
},
style: function (property) {
return {
getValue: function () {
// @IE8
var _this = this;
return _this.style[property] || (window.getComputedStyle ? getComputedStyle(_this, null).getPropertyValue(property) : _this.currentStyle[property]);
},
setValue: function (v) {
this.style[property] = v;
}
};
}
};
binders.visibility = binders.display;
binders.html = binders.innerHTML;
binders.text = binders.innerText;
binders.prop = binders.property;
binders.attr = binders.attribute;
return binders;
}(matreshka_dir_core_var_core);
matreshka_dir_polyfills_addeventlistener = function () {
(function (win, doc, s_add, s_rem) {
if (doc[s_add])
return;
Element.prototype[s_add] = win[s_add] = doc[s_add] = function (on, fn, self) {
return (self = this).attachEvent('on' + on, function (e) {
e = e || win.event;
e.target = e.target || e.srcElement;
e.preventDefault = e.preventDefault || function () {
e.returnValue = false;
};
e.stopPropagation = e.stopPropagation || function () {
e.cancelBubble = true;
};
e.which = e.button ? e.button === 2 ? 3 : e.button === 4 ? 2 : e.button : e.keyCode;
fn.call(self, e);
});
};
Element.prototype[s_rem] = win[s_rem] = doc[s_rem] = function (on, fn) {
return this.detachEvent('on' + on, fn);
};
}(window, document, 'addEventListener', 'removeEventListener'));
}();
matreshka_dir_core_dom_lib_balalaika = function (window, document, fn, nsRegAndEvents, id, s_EventListener, s_MatchesSelector, i, j, k, l, $) {
$ = function (s, context) {
return new $.i(s, context);
};
$.i = function (s, context) {
fn.push.apply(this, !s ? fn : s.nodeType || s == window ? [s] : '' + s === s ? /</.test(s) ? ((i = document.createElement(context || 'div')).innerHTML = s, i.children) : (context && $(context)[0] || document).querySelectorAll(s) : /f/.test(typeof s) ? /c/.test(document.readyState) ? s() : $(document).on('DOMContentLoaded', s) : 'length' in s ? s : [s]);
};
$.i[l = 'prototype'] = ($.extend = function (obj) {
k = arguments;
for (i = 1; i < k.length; i++) {
if (l = k[i]) {
for (j in l) {
obj[j] = l[j];
}
}
}
return obj;
})($.fn = $[l] = fn, {
// $.fn = $.prototype = fn
on: function (n, f) {
// n = [ eventName, nameSpace ]
n = n.split(nsRegAndEvents);
this.map(function (item) {
// item.b$ is balalaika_id for an element
// i is eventName + id ("click75")
// nsRegAndEvents[ i ] is array of events (eg all click events for element#75) ([[namespace, handler], [namespace, handler]])
(nsRegAndEvents[i = n[0] + (item.b$ = item.b$ || ++id)] = nsRegAndEvents[i] || []).push([
f,
n[1]
]);
// item.addEventListener( eventName, f )
item['add' + s_EventListener](n[0], f);
});
return this;
},
off: function (n, f) {
// n = [ eventName, nameSpace ]
n = n.split(nsRegAndEvents);
// l = 'removeEventListener'
l = 'remove' + s_EventListener;
this.map(function (item) {
// k - array of events
// item.b$ - balalaika_id for an element
// n[ 0 ] + item.b$ - eventName + id ("click75")
k = nsRegAndEvents[n[0] + item.b$];
// if array of events exist then i = length of array of events
if (i = k && k.length) {
// while j = one of array of events
while (j = k[--i]) {
// if( no f and no namespace || f but no namespace || no f but namespace || f and namespace )
if ((!f || f == j[0] || f == j[0]._callback) && (!n[1] || n[1] == j[1])) {
// item.removeEventListener( eventName, handler );
item[l](n[0], j[0]);
// remove event from array of events
k.splice(i, 1);
}
}
} else {
// if event added before using addEventListener, just remove it using item.removeEventListener( eventName, f )
!n[1] && item[l](n[0], f);
}
});
return this;
},
is: function (s) {
i = this[0];
j = !!i && (i.matches || i['webkit' + s_MatchesSelector] || i['moz' + s_MatchesSelector] || i['ms' + s_MatchesSelector] || i['o' + s_MatchesSelector]);
return !!j && j.call(i, s);
}
});
return $;
}(window, document, [], /\.(.+)/, 0, 'EventListener', 'MatchesSelector');
matreshka_dir_polyfills_classlist = function () {
var toggle = function (token, force) {
if (typeof force === 'boolean') {
this[force ? 'add' : 'remove'](token);
} else {
this[!this.contains(token) ? 'add' : 'remove'](token);
}
return this.contains(token);
};
if (window.DOMTokenList) {
var a = document.createElement('a');
a.classList.toggle('x', false);
if (a.className) {
window.DOMTokenList.prototype.toggle = toggle;
}
}
if (typeof window.Element === 'undefined' || 'classList' in document.documentElement)
return;
var prototype = Array.prototype, push = prototype.push, splice = prototype.splice, join = prototype.join;
function DOMTokenList(el) {
this.el = el;
// The className needs to be trimmed and split on whitespace
// to retrieve a list of classes.
var classes = el.className.replace(/^\s+|\s+$/g, '').split(/\s+/);
for (var i = 0; i < classes.length; i++) {
push.call(this, classes[i]);
}
}
DOMTokenList.prototype = {
add: function (token) {
if (this.contains(token))
return;
push.call(this, token);
this.el.className = this.toString();
},
contains: function (token) {
return this.el.className.indexOf(token) != -1;
},
item: function (index) {
return this[index] || null;
},
remove: function (token) {
if (!this.contains(token))
return;
for (var i = 0; i < this.length; i++) {
if (this[i] == token)
break;
}
splice.call(this, i, 1);
this.el.className = this.toString();
},
toString: function () {
return join.call(this, ' ');
},
toggle: toggle
};
window.DOMTokenList = DOMTokenList;
function defineElementGetter(obj, prop, getter) {
if (Object.defineProperty) {
Object.defineProperty(obj, prop, { get: getter });
} else {
obj.__defineGetter__(prop, getter);
}
}
defineElementGetter(Element.prototype, 'classList', function () {
return new DOMTokenList(this);
});
}();
matreshka_dir_core_dom_lib_balalaika_extended = function ($b) {
var s_classList = 'classList', _on, _off;
if (!$b) {
throw new Error('Balalaika is missing');
}
_on = $b.fn.on;
_off = $b.fn.off;
$b.extend($b.fn, {
on: function (n, f) {
n.split(/\s/).forEach(function (n) {
_on.call(this, n, f);
}, this);
return this;
},
off: function (n, f) {
n.split(/\s/).forEach(function (n) {
_off.call(this, n, f);
}, this);
return this;
},
hasClass: function (className) {
return !!this[0] && this[0][s_classList].contains(className);
},
addClass: function (className) {
this.forEach(function (item) {
var classList = item[s_classList];
classList.add.apply(classList, className.split(/\s/));
});
return this;
},
removeClass: function (className) {
this.forEach(function (item) {
var classList = item[s_classList];
classList.remove.apply(classList, className.split(/\s/));
});
return this;
},
toggleClass: function (className, b) {
this.forEach(function (item) {
var classList = item[s_classList];
if (typeof b !== 'boolean') {
b = !classList.contains(className);
}
classList[b ? 'add' : 'remove'].apply(classList, className.split(/\s/));
});
return this;
},
add: function (s) {
var result = $b(this), ieIndexOf = function (a, e) {
for (j = 0; j < a.length; j++)
if (a[j] === e)
return j;
}, i, j;
s = $b(s).slice();
[].push.apply(result, s);
for (i = result.length - s.length; i < result.length; i++) {
if (([].indexOf ? result.indexOf(result[i]) : ieIndexOf(result, result[i])) !== i) {
// @IE8
result.splice(i--, 1);
}
}
return result;
},
not: function (s) {
var result = $b(this), index, i;
s = $b(s);
for (i = 0; i < s.length; i++) {
if (~(index = result.indexOf(s[i]))) {
result.splice(index, 1);
}
}
return result;
},
find: function (s) {
var result = $b();
this.forEach(function (item) {
result = result.add($b(s, item));
});
return result;
}
});
// simple html parser
$b.parseHTML = function (html) {
var node = document.createElement('div'),
// wrapMap is taken from jQuery
wrapMap = {
option: [
1,
'<select multiple=\'multiple\'>',
'</select>'
],
legend: [
1,
'<fieldset>',
'</fieldset>'
],
thead: [
1,
'<table>',
'</table>'
],
tr: [
2,
'<table><tbody>',
'</tbody></table>'
],
td: [
3,
'<table><tbody><tr>',
'</tr></tbody></table>'
],
col: [
2,
'<table><tbody></tbody><colgroup>',
'</colgroup></table>'
],
area: [
1,
'<map>',
'</map>'
],
_: [
0,
'',
''
]
}, wrapper, i, ex;
html = html.replace(/^\s+|\s+$/g, '');
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
ex = /<([\w:]+)/.exec(html);
wrapper = ex && wrapMap[ex[1]] || wrapMap._;
node.innerHTML = wrapper[1] + html + wrapper[2];
i = wrapper[0];
while (i--) {
node = node.children[0];
}
return $b(node.childNodes);
};
$b.create = function create(tagName, props) {
var el, i, j, prop;
if (typeof tagName == 'object') {
props = tagName;
tagName = props.tagName;
}
el = document.createElement(tagName);
if (props)
for (i in props) {
prop = props[i];
if (i == 'attributes' && typeof prop == 'object') {
for (j in prop)
if (prop.hasOwnProperty(j)) {
el.setAttribute(j, prop[j]);
}
} else if (i == 'tagName') {
continue;
} else if (i == 'children' && prop) {
for (j = 0; j < prop.length; j++) {
el.appendChild(create(prop[j]));
}
} else if (typeof el[i] == 'object' && el[i] !== null && typeof props == 'object') {
for (j in prop)
if (prop.hasOwnProperty(j)) {
el[i][j] = prop[j];
}
} else {
el[i] = prop;
}
}
return el;
};
// @IE8 Balalaika fix. This browser doesn't support HTMLCollection and NodeList as second argument for .apply
// This part of code will be removed in Matreshka 1.0
(function (document, $, i, j, k, fn) {
var bugs, children = document.createElement('div').children;
try {
[].push.apply([], children);
} catch (e) {
bugs = true;
}
bugs = bugs || typeof children === 'function' || document.documentMode < 9;
if (bugs) {
fn = $.i[j = 'prototype'];
$.i = function (s, context) {
k = !s ? fn : s && s.nodeType || s == window ? [s] : typeof s == 'string' ? /</.test(s) ? ((i = document.createElement('div')).innerHTML = s, i.children) : (context && $(context)[0] || document).querySelectorAll(s) : /f/.test(typeof s) && (!s[0] && !s[0].nodeType) ? /c/.test(document.readyState) ? s() : !function r(f) {
/in/(document.readyState) ? setTimeout(r, 9, f) : f();
}(s) : s;
j = [];
for (i = k ? k.length : 0; i--; j[i] = k[i]) {
}
fn.push.apply(this, j);
};
$.i[j] = fn;
fn.is = function (selector) {
var elem = this[0], elems = elem.parentNode.querySelectorAll(selector), i;
for (i = 0; i < elems.length; i++) {
if (elems[i] === elem)
return true;
}
return false;
};
}
return $;
}(document, $b));
return $b;
}(matreshka_dir_core_dom_lib_balalaika);
matreshka_dir_core_dom_lib_dollar_lib = function ($b) {
var neededMethods = 'on off is hasClass addClass removeClass toggleClass add not find'.split(/\s+/), dollar = typeof window.$ == 'function' ? window.$ : null, useDollar = true, i;
if (dollar) {
for (i = 0; i < neededMethods.length; i++) {
if (!dollar.prototype[neededMethods[i]]) {
useDollar = false;
break;
}
}
if (!dollar.parseHTML) {
useDollar = false;
}
} else {
useDollar = false;
}
return useDollar ? dollar : $b;
}(matreshka_dir_core_dom_lib_balalaika_extended);
matreshka_dir_core_dom_lib_used_lib = function (core, $b, $) {
core.$ = $;
core.$b = core.balalaika = $b;
core.useAs$ = function (_$) {
return core.$ = this.$ = $ = _$;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_dom_lib_balalaika_extended, matreshka_dir_core_dom_lib_dollar_lib);
matreshka_dir_core_var_isxdr = document.documentMode == 8;
matreshka_dir_core_initmk = function (core, sym, isXDR) {
var initMK = core.initMK = function (object) {
if (!object[sym]) {
Object.defineProperty(object, sym, {
value: {
events: {},
special: {},
id: 'mk' + Math.random()
},
enumerable: isXDR,
configurable: isXDR,
writable: isXDR
});
}
return object;
};
return function (object) {
object._initMK ? object._initMK() : initMK(object);
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_var_isxdr);
matreshka_dir_core_definespecial = function (core, sym, isXDR) {
core._defineSpecial = function (object, key, noAccessors) {
if (!object || typeof object != 'object' || !object[sym])
return object;
var specialProps = object[sym].special[key];
if (!specialProps) {
specialProps = object[sym].special[key] = {
$nodes: core.$(),
value: object[key],
getter: null,
setter: null,
mediator: null
};
if (!noAccessors && key != 'sandbox') {
Object.defineProperty(object, key, {
configurable: true,
enumerable: !isXDR,
get: function () {
return specialProps.getter ? specialProps.getter.call(object) : specialProps.value;
},
set: function (v) {
specialProps.setter ? specialProps.setter.call(object, v) : core.set(object, key, v, { fromSetter: true });
}
});
}
}
return specialProps;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_var_isxdr);
matreshka_dir_core_util_define = function (core, initMK) {
var _define, defineGetter, defineSetter;
_define = core.define = function (object, key, descriptor) {
if (!object || typeof object != 'object')
return object;
var i;
if (typeof key == 'object') {
for (i in key) {
_define(object, i, key[i]);
}
return object;
}
Object.defineProperty(object, key, descriptor);
return object;
};
defineGetter = core.defineGetter = function (object, key, getter) {
if (!object || typeof object != 'object')
return object;
initMK(object);
var i, special;
if (typeof key == 'object') {
for (i in key)
if (key.hasOwnProperty(i)) {
defineGetter(object, i, key[i]);
}
return object;
}
special = core._defineSpecial(object, key);
special.getter = function () {
return getter.call(object, {
value: special.value,
key: key,
self: object
});
};
return object;
};
defineSetter = core.defineSetter = function (object, key, setter) {
if (!object || typeof object != 'object')
return object;
initMK(object);
var i;
if (typeof key == 'object') {
for (i in key)
if (key.hasOwnProperty(i)) {
defineSetter(object, i, key[i]);
}
return object;
}
core._defineSpecial(object, key).setter = function (v) {
return setter.call(object, v, {
value: v,
key: key,
self: object
});
};
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk);
matreshka_dir_core_util_linkprops = function (core, sym, initMK, util) {
var linkProps = core.linkProps = function (object, key, keys, getter, setOnInit, options) {
if (!object || typeof object != 'object')
return object;
initMK(object);
keys = typeof keys == 'string' ? keys.split(/\s/) : keys;
options = options || {};
var on_Change = function (evt) {
var values = [], _protect = evt._protect = evt._protect || {};
evt.fromDependency = true;
if (!(key + object[sym].id in _protect)) {
if (typeof keys[0] == 'object') {
for (i = 0; i < keys.length; i += 2) {
_this = keys[i];
_keys = typeof keys[i + 1] == 'string' ? keys[i + 1].split(/\s/) : keys[i + 1];
for (j = 0; j < _keys.length; j++) {
values.push(util.deepFind(_this, _keys[j]));
}
}
} else {
for (i = 0; i < keys.length; i++) {
_key = keys[i];
_this = object;
values.push(util.deepFind(_this, _key));
}
}
_protect[key + object[sym].id] = 1;
core._defineSpecial(object, key, options.hideProperty);
core.set(object, key, getter.apply(object, values), evt);
}
}, _this, _key, _keys, i, j, path;
getter = getter || function (value) {
return value;
};
function getEvtName(path) {
var evtName, sliceIndex;
if (path.length > 1) {
sliceIndex = path.length - 1;
evtName = path.slice(0, sliceIndex).join('.') + '@' + '_rundependencies:' + path[sliceIndex];
} else {
evtName = '_rundependencies:' + path;
}
return evtName;
}
if (typeof keys[0] == 'object') {
for (i = 0; i < keys.length; i += 2) {
_this = initMK(keys[i]);
_keys = typeof keys[i + 1] == 'string' ? keys[i + 1].split(/\s/) : keys[i + 1];
for (j = 0; j < _keys.length; j++) {
path = _keys[j].split('.');
core[path.length > 1 ? 'on' : '_fastAddListener'](_this, getEvtName(path), on_Change);
}
}
} else {
for (i = 0; i < keys.length; i++) {
_key = keys[i];
_this = object;
path = _key.split('.');
core[path.length > 1 ? 'on' : '_fastAddListener'](_this, getEvtName(path), on_Change);
}
}
setOnInit !== false && on_Change.call(typeof keys[0] == 'object' ? keys[0] : object, { key: typeof keys[0] == 'object' ? keys[1] : keys[0] });
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_initmk, matreshka_dir_core_util_common);
matreshka_dir_core_util_mediate = function (core, initMK) {
var mediate = core.mediate = function (object, keys, mediator) {
if (!object || typeof object != 'object')
return object;
initMK(object);
var type = typeof keys, i, special;
if (type == 'object' && !(keys instanceof Array)) {
for (i in keys) {
if (keys.hasOwnProperty(i)) {
core.mediate(object, i, keys[i]);
}
}
return object;
}
keys = type == 'string' ? keys.split(/\s/) : keys;
for (i = 0; i < keys.length; i++)
(function (key) {
special = core._defineSpecial(object, key);
special.mediator = function (v) {
return mediator.call(object, v, special.value, key, object);
};
core.set(object, key, special.mediator(special.value), { fromMediator: true });
}(keys[i]));
return object;
};
var setClassFor = core.setClassFor = function (object, keys, Class, updateFunction) {
if (!object || typeof object != 'object')
return object;
initMK(object);
var type = typeof keys, i;
if (type == 'object' && !(keys instanceof Array)) {
for (i in keys)
if (keys.hasOwnProperty(i)) {
core.setClassFor(object, i, keys[i], Class);
}
return object;
}
keys = type == 'string' ? keys.split(/\s/) : keys;
updateFunction = updateFunction || function (instance, data) {
var i;
if (instance.isMKArray) {
instance.recreate(data);
} else if (instance.isMKObject) {
instance.jset(data);
} else {
for (i in data) {
if (data.hasOwnProperty(i)) {
instance[i] = data[i];
}
}
}
};
for (i = 0; i < keys.length; i++) {
core.mediate(object, keys[i], function (v, prevVal) {
var result;
if (prevVal && (prevVal.instanceOf ? prevVal.instanceOf(Class) : prevVal instanceof Class)) {
updateFunction.call(object, prevVal, v);
result = prevVal;
} else {
result = new Class(v, object);
}
return result;
});
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk);
matreshka_dir_core_get_set_remove = function (core, sym) {
var set;
core.get = function (object, key) {
return object && object[key];
};
// set method is the most often used method
// we need to optimize it as good as possible
set = core.set = function (object, key, v, evt) {
if (!object || typeof object != 'object')
return object;
var type = typeof key, _isNaN = Number.isNaN || function (value) {
return typeof value == 'number' && isNaN(value);
}, special, events, prevVal, newV, i, _evt, triggerChange;
if (type == 'undefined')
return object;
if (type == 'object') {
for (i in key)
if (key.hasOwnProperty(i)) {
set(object, i, key[i], v);
}
return object;
}
if (!object[sym] || !object[sym].special || !object[sym].special[key]) {
object[key] = v;
return object;
}
special = object[sym].special[key];
events = object[sym].events;
prevVal = special.value;
if (special.mediator && v !== prevVal && (!evt || !evt.skipMediator && !evt.fromMediator)) {
newV = special.mediator(v, prevVal, key, object);
} else {
newV = v;
}
_evt = {
value: newV,
previousValue: prevVal,
key: key,
node: special.$nodes[0] || null,
$nodes: special.$nodes,
self: object
};
if (evt && typeof evt == 'object') {
for (i in evt) {
_evt[i] = evt[i];
}
}
triggerChange = (newV !== prevVal || _evt.force) && !_evt.silent;
if (triggerChange) {
events['beforechange:' + key] && core._fastTrigger(object, 'beforechange:' + key, _evt);
events.beforechange && core._fastTrigger(object, 'beforechange', _evt);
}
special.value = newV;
if (newV !== prevVal || _evt.force || _evt.forceHTML || newV !== v && !_isNaN(newV)) {
if (!_evt.silentHTML) {
events['_runbindings:' + key] && core._fastTrigger(object, '_runbindings:' + key, _evt);
}
}
if (triggerChange) {
events['change:' + key] && core._fastTrigger(object, 'change:' + key, _evt);
events.change && core._fastTrigger(object, 'change', _evt);
}
if ((newV !== prevVal || _evt.force || _evt.forceHTML) && !_evt.skipLinks) {
events['_rundependencies:' + key] && core._fastTrigger(object, '_rundependencies:' + key, _evt);
}
return object;
};
core.remove = function (object, key, evt) {
if (!object || typeof object != 'object')
return null;
var exists, keys = String(key).split(/\s/), i, _evt = { keys: keys };
if (evt && typeof evt == 'object') {
for (i in evt) {
_evt[i] = evt[i];
}
}
for (i = 0; i < keys.length; i++) {
key = keys[i];
exists = key in object;
if (exists) {
_evt.key = key;
_evt.value = object[key];
try {
// @IE8 spike
delete object[key];
} catch (e) {
}
if (object[sym]) {
core.unbindNode(object, key);
core.off(object, 'change:' + key + ' beforechange:' + key + ' _runbindings:' + key + ' _rundependencies:' + key);
delete object[sym].special[key];
if (!_evt.silent) {
core._fastTrigger(object, 'delete', _evt);
core._fastTrigger(object, 'delete:' + key, _evt);
}
}
}
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym);
matreshka_dir_core_bindings_bindnode = function (core, sym, initMK, util) {
var defaultBinders, lookForBinder;
defaultBinders = core.defaultBinders = [function (node) {
var tagName = node.tagName, binders = core.binders, b;
if (tagName == 'INPUT') {
b = binders.input(node.type);
} else if (tagName == 'TEXTAREA') {
b = binders.textarea();
} else if (tagName == 'SELECT') {
b = binders.select(node.multiple);
} else if (tagName == 'PROGRESS') {
b = binders.progress();
} else if (tagName == 'OUTPUT') {
b = binders.output();
}
return b;
}];
lookForBinder = core.lookForBinder = function (node) {
var result, ep = defaultBinders, i;
for (i = 0; i < ep.length; i++) {
if (result = ep[i].call(node, node)) {
return result;
}
}
};
core.bindOptionalNode = function (object, key, node, binder, evt) {
if (typeof key == 'object') {
/*
* this.bindNode({ key: $() }, { on: 'evt' }, { silent: true });
*/
bindNode(object, key, node, binder, true);
} else {
bindNode(object, key, node, binder, evt, true);
}
return object;
};
var bindNode = core.bindNode = function (object, key, node, binder, evt, optional) {
if (!object || typeof object != 'object')
return object;
initMK(object);
var win = typeof window != 'undefined' ? window : null, isUndefined, $nodes, keys, i, j, special, path, listenKey, changeHandler, domEvt, _binder, options, _options, mkHandler, foundBinder, _evt;
/*
* this.bindNode([['key', $(), {on:'evt'}], [{key: $(), {on: 'evt'}}]], { silent: true });
*/
if (key instanceof Array) {
for (i = 0; i < key.length; i++) {
bindNode(object, key[i][0], key[i][1], key[i][2] || evt, node);
}
return object;
}
/*
* this.bindNode('key1 key2', node, binder, { silent: true });
*/
if (typeof key == 'string') {
keys = key.split(/\s+/);
if (keys.length > 1) {
for (i = 0; i < keys.length; i++) {
bindNode(object, keys[i], node, binder, evt, optional);
}
return object;
}
}
/*
* this.bindNode({ key: $() }, { on: 'evt' }, { silent: true });
*/
if (typeof key == 'object') {
for (i in key) {
if (key.hasOwnProperty(i)) {
bindNode(object, i, key[i], node, binder, evt);
}
}
return object;
}
/*
* this.bindNode('key', [ node, binder ], { silent: true });
*/
// node !== win is the most uncommon bugfix ever. Don't ask what does it mean.
// This is about iframes, CORS and deprecated DOM API.
if (node && node.length == 2 && node !== win && !node[1].nodeName && (node[1].setValue || node[1].getValue)) {
return bindNode(object, key, node[0], node[1], binder, optional);
}
$nodes = core._getNodes(object, node);
if (!$nodes.length) {
if (optional) {
return object;
} else {
throw Error('Binding error: node is missing for "' + key + '".' + (typeof node == 'string' ? ' The selector is "' + node + '"' : ''));
}
}
if (~key.indexOf('.')) {
path = key.split('.');
changeHandler = function (evt) {
var target = evt && evt.value;
if (!target) {
target = object;
for (var i = 0; i < path.length - 1; i++) {
target = target[path[i]];
}
}
bindNode(target, path[path.length - 1], $nodes, binder, evt, optional);
if (evt && evt.previousValue) {
core.unbindNode(evt.previousValue, path[path.length - 1], $nodes);
}
};
core._delegateListener(object, path.slice(0, path.length - 2).join('.'), 'change:' + path[path.length - 2], changeHandler);
changeHandler();
return object;
}
evt = evt || {};
special = core._defineSpecial(object, key);
isUndefined = typeof special.value == 'undefined';
special.$nodes = special.$nodes.length ? special.$nodes.add($nodes) : $nodes;
if (object.isMK) {
if (key == 'sandbox') {
object.$sandbox = $nodes;
object.sandbox = $nodes[0];
}
object.$nodes[key] = special.$nodes;
object.nodes[key] = special.$nodes[0];
}
if (key != 'sandbox') {
for (i = 0; i < $nodes.length; i++) {
initBinding($nodes[i]);
}
}
if (!evt.silent) {
_evt = {
key: key,
$nodes: $nodes,
node: $nodes[0] || null
};
for (i in evt) {
_evt[i] = evt[i];
}
core._fastTrigger(object, 'bind:' + key, _evt);
core._fastTrigger(object, 'bind', _evt);
}
function initBinding(node) {
var _binder, options = {
self: object,
key: key,
$nodes: $nodes,
node: node
};
if (binder === null) {
_binder = {};
} else {
foundBinder = lookForBinder(node);
if (foundBinder) {
if (binder) {
for (j in binder) {
foundBinder[j] = binder[j];
}
}
_binder = foundBinder;
} else {
_binder = binder || {};
}
}
if (_binder.initialize) {
_options = { value: special.value };
for (j in options) {
_options[j] = options[j];
}
_binder.initialize.call(node, _options);
}
if (_binder.setValue) {
mkHandler = function (evt) {
var v = object[sym].special[key].value,
// dirty hack for this one https://github.com/matreshkajs/matreshka/issues/19
_v = evt && typeof evt.onChangeValue == 'string' && typeof v == 'number' ? String(v) : v;
if (evt && evt.changedNode == node && evt.onChangeValue == _v)
return;
_options = { value: v };
for (j in options) {
_options[j] = options[j];
}
_binder.setValue.call(node, v, _options);
};
core._fastAddListener(object, '_runbindings:' + key, mkHandler, null, { node: node });
!isUndefined && mkHandler();
}
if (_binder.getValue && (isUndefined && evt.assignDefaultValue !== false || evt.assignDefaultValue === true)) {
_evt = { fromNode: true };
for (j in evt) {
_evt[j] = evt[j];
}
core.set(object, key, _binder.getValue.call(node, options), _evt);
}
if (_binder.getValue && _binder.on) {
domEvt = {
node: node,
on: _binder.on,
instance: object,
key: key,
mkHandler: mkHandler,
handler: function (evt) {
if (domEvt.removed)
return;
var oldvalue = object[key], value, j, _options = {
value: oldvalue,
domEvent: evt,
originalEvent: evt.originalEvent || evt,
preventDefault: function () {
evt.preventDefault();
},
stopPropagation: function () {
evt.stopPropagation();
},
which: evt.which,
target: evt.target
};
// hasOwnProperty is not required there
for (j in options) {
_options[j] = options[j];
}
value = _binder.getValue.call(node, _options);
if (value !== oldvalue) {
core.set(object, key, value, {
fromNode: true,
changedNode: node,
onChangeValue: value
});
}
}
};
core.domEvents.add(domEvt);
}
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_initmk, matreshka_dir_core_util_common);
matreshka_dir_core_bindings_unbindnode = function (core, sym, initMK) {
var unbindNode = core.unbindNode = function (object, key, node, evt) {
if (!object || typeof object != 'object')
return object;
initMK(object);
var type = typeof key, $nodes, keys, special = object[sym].special[key], i, indexOfDot, path, listenKey, _evt;
if (key instanceof Array) {
for (i = 0; i < key.length; i++) {
evt = node;
unbindNode(object, key[i][0], key[i][1] || evt, evt);
}
return object;
}
if (type == 'string') {
keys = key.split(/\s/);
if (keys.length > 1) {
for (i = 0; i < keys.length; i++) {
unbindNode(object, keys[i], node, evt);
}
return object;
}
}
indexOfDot = key.indexOf('.');
if (~indexOfDot) {
path = key.split('.');
var target = object;
for (i = 0; i < path.length - 1; i++) {
target = target[path[i]];
}
core._undelegateListener(object, path.slice(0, path.length - 2), 'change:' + path[path.length - 2]);
unbindNode(target, path[path.length - 1], node, evt);
return object;
}
if (key === null) {
for (key in object[sym].special)
if (object[sym].special.hasOwnProperty(key)) {
unbindNode(object, key, node, evt);
}
return object;
} else if (type == 'object') {
for (i in key)
if (key.hasOwnProperty(i)) {
unbindNode(object, i, key[i], node);
}
return object;
} else if (!node) {
if (special && special.$nodes) {
return unbindNode(object, key, special.$nodes, evt);
} else {
return object;
}
} else if (node.length == 2 && !node[1].nodeName && (node[1].setValue || node[1].getValue || node[1].on)) {
// It actually ignores binder. With such a syntax you can assign definite binders to some variable and then easily delete all at once using
return unbindNode(object, key, node[0], evt);
} else if (!special) {
return object;
}
$nodes = core._getNodes(object, node);
for (i = 0; i < $nodes.length; i++) {
core.domEvents.remove({
key: key,
node: $nodes[i],
instance: object
});
special.$nodes = special.$nodes.not($nodes[i]);
(function (node) {
core._removeListener(object, '_runbindings:' + key, null, null, {
node: node,
howToRemove: function (onData, offData) {
return onData.node == offData.node;
}
});
}($nodes[i]));
}
if (object.isMK) {
object.$nodes[key] = special.$nodes;
object.nodes[key] = special.$nodes[0] || null;
if (key == 'sandbox') {
object.sandbox = special.$nodes[0] || null;
object.$sandbox = special.$nodes;
}
}
if (!evt || !evt.silent) {
_evt = {
key: key,
$nodes: $nodes,
node: $nodes[0] || null
};
for (i in evt) {
_evt[i] = evt[i];
}
core._fastTrigger(object, 'unbind:' + key, _evt);
core._fastTrigger(object, 'unbind', _evt);
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_initmk);
matreshka_dir_core_bindings_parsebindings = function (core, sym, initMK, util) {
var parseBindings = core.parseBindings = function (object, nodes) {
var $ = core.$;
if (!object || typeof object != 'object')
return $();
if (typeof nodes == 'string') {
if (~nodes.indexOf('{{')) {
nodes = $.parseHTML(nodes.replace(/^\s+|\s+$/g, ''));
} else {
return $.parseHTML(nodes.replace(/^\s+|\s+$/g, ''));
}
} else if (!nodes) {
nodes = object[sym] && object[sym].special && object[sym].special.sandbox && object[sym].special.sandbox.$nodes;
if (!nodes || !nodes.length) {
return object;
}
} else {
nodes = $(nodes);
}
initMK(object);
var all = [], k = 0, childNodes, i, j, node, bindHTMLKey, atts, attr, attrValue, attrName, keys, key, binder, previous, textContent, childNode, body;
function initLink(key, keys, attrValue) {
core.linkProps(object, key, keys, function () {
var v = attrValue, i;
for (i = 0; i < keys.length; i++) {
v = v.replace(new RegExp('{{' + keys[i] + '}}', 'g'), util.deepFind(object, keys[i]));
}
return v;
}, true, { hideProperty: true });
}
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
// we need 2 ifs for old firefoxes
if (node.outerHTML) {
// '%7B%7B' is for firefox too
if (!~node.outerHTML.indexOf('{{') && !~node.outerHTML.indexOf('%7B%7B'))
continue;
}
childNodes = node.getElementsByTagName('*');
for (j = 0; j < childNodes.length; j++) {
all[k++] = childNodes[j];
}
all[k++] = node;
}
if (!all.length) {
return $();
}
for (j = 0; j < all.length; j++) {
node = all[j];
if (node.tagName != 'TEXTAREA') {
for (i = 0; i < node.childNodes.length; i++) {
childNode = node.childNodes[i];
previous = childNode.previousSibling;
if (childNode.nodeType == 3 && ~childNode.nodeValue.indexOf('{{')) {
textContent = childNode.nodeValue.replace(/{{([^}]*)}}/g, '<span mk-html="$1"></span>');
try {
if (previous) {
previous.insertAdjacentHTML('afterend', textContent);
} else {
node.insertAdjacentHTML('afterbegin', textContent);
}
} catch (e) {
// in case user uses very old webkit-based browser
body = document.body;
if (previous) {
body.appendChild(previous);
previous.insertAdjacentHTML('afterend', textContent);
body.removeChild(previous);
} else {
body.appendChild(node);
node.insertAdjacentHTML('afterbegin', textContent);
body.removeChild(node);
}
}
node.removeChild(childNode);
}
}
}
}
for (i = 0; i < nodes.length; i++) {
childNodes = nodes[i].querySelectorAll('[mk-html]');
for (j = 0; j < childNodes.length; j++) {
all[k++] = childNodes[j];
}
}
for (i = 0; i < all.length; i++) {
node = all[i];
bindHTMLKey = node.getAttribute('mk-html');
if (bindHTMLKey) {
node.removeAttribute('mk-html');
core.bindNode(object, bindHTMLKey, node, {
setValue: function (v) {
this.innerHTML = v;
}
});
}
atts = node.attributes;
for (j = 0; j < atts.length; j++) {
attr = atts[j];
attrValue = attr.value;
attrName = attr.name;
if (~attrValue.indexOf('{{')) {
keys = attrValue.match(/{{[^}]*}}/g).map(function (key) {
return key.replace(/{{(.*)}}/, '$1');
});
if (keys.length == 1 && /^{{[^}]*}}$/g.test(attrValue)) {
key = keys[0];
} else {
key = core.randomString();
initLink(key, keys, attrValue);
}
if ((attrName == 'value' && node.type != 'checkbox' || attrName == 'checked' && node.type == 'checkbox') && core.lookForBinder(node)) {
node.setAttribute(attrName, '');
core.bindNode(object, key, node);
} else {
core.bindNode(object, key, node, core.binders.attr(attrName));
}
}
}
}
return nodes;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_initmk, matreshka_dir_core_util_common);
matreshka_dir_core_bindings_getnodes = function (core, sym, initMK, util) {
var selectAll, boundAll;
/**
* @private
* @summary selectNodes selects nodes match to custom selectors such as :sandbox and :bound(KEY)
*/
function selectNodes(object, selectors) {
var result = core.$(), execResult, $bound, node, selector, i, j, random;
if (!object || !object[sym])
return result;
// replacing :sandbox to :bound(sandbox)
selectors = selectors.split(',');
for (i = 0; i < selectors.length; i++) {
selector = selectors[i];
if (execResult = /\s*:bound\(([^(]*)\)\s*([\S\s]*)\s*|\s*:sandbox\s*([\S\s]*)\s*/.exec(selector)) {
var key = execResult[3] !== undefined ? 'sandbox' : execResult[1], subSelector = execResult[3] !== undefined ? execResult[3] : execResult[2];
// getting KEY from :bound(KEY)
$bound = object[sym].special[key] && object[sym].special[key].$nodes;
if (!$bound || !$bound.length) {
continue;
}
// if native selector passed after :bound(KEY) is not empty string
// for example ":bound(KEY) .my-selector"
if (subSelector) {
// if native selector contains children selector
// for example ":bound(KEY) > .my-selector"
if (subSelector.indexOf('>') === 0) {
// selecting children
for (j = 0; j < $bound.length; j++) {
node = $bound[j];
random = core.randomString();
node.setAttribute(random, random);
result = result.add($('[' + random + '="' + random + '"]' + subSelector, node));
node.removeAttribute(random);
}
} else {
// if native selector doesn't contain children selector
result = result.add($bound.find(subSelector));
}
} else {
// if native selector is empty string
result = result.add($bound);
} // if it's native selector
} else {
result = result.add(selector);
}
}
return result;
}
selectAll = core.selectAll = function (object, s) {
var $sandbox;
if (!object || !object[sym] || typeof s != 'string')
return core.$();
if (/:sandbox|:bound\(([^(]*)\)/.test(s)) {
return selectNodes(object, s);
} else {
$sandbox = object && object[sym] && object[sym].special;
$sandbox = $sandbox && $sandbox.sandbox && $sandbox.sandbox.$nodes;
return $sandbox && $sandbox.find(s);
}
}, core.select = function (object, s) {
var sandbox;
if (!object || !object[sym] || typeof s != 'string')
return core.$();
if (/:sandbox|:bound\(([^(]*)\)/.test(s)) {
return selectNodes(object, s)[0] || null;
} else {
sandbox = object && object[sym] && object[sym].special;
sandbox = sandbox && sandbox.sandbox && sandbox.sandbox.$nodes && sandbox.sandbox.$nodes[0];
return sandbox && sandbox.querySelector(s);
}
};
boundAll = core.boundAll = function (object, key) {
var $ = core.$, special, keys, $nodes, i;
if (!object || typeof object != 'object')
return $();
initMK(object);
special = object[sym].special, key = !key ? 'sandbox' : key;
keys = typeof key == 'string' ? key.split(/\s+/) : key;
if (keys.length <= 1) {
return keys[0] in special ? special[keys[0]].$nodes : $();
} else {
$nodes = $();
for (i = 0; i < keys.length; i++) {
$nodes = $nodes.add(special[keys[i]].$nodes);
}
return $nodes;
}
};
core.$bound = function (object, key) {
return boundAll(object, key);
};
core.bound = function (object, key) {
if (!object || typeof object != 'object')
return null;
initMK(object);
var special = object[sym].special, keys, i;
key = !key ? 'sandbox' : key;
keys = typeof key == 'string' ? key.split(/\s+/) : key;
if (keys.length <= 1) {
return keys[0] in special ? special[keys[0]].$nodes[0] || null : null;
} else {
for (i = 0; i < keys.length; i++) {
if (keys[i] in special && special[keys[i]].$nodes.length) {
return special[keys[i]].$nodes[0];
}
}
}
return null;
};
core._getNodes = function (object, s) {
return typeof s == 'string' && !/</.test(s) && /:sandbox|:bound\(([^(]*)\)/.test(s) ? selectNodes(object, s) : core.$(s);
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_initmk, matreshka_dir_core_util_common);
matreshka_dir_core_var_domevtreg = /([^\:\:]+)(::([^\(\)]+)?(\((.*)\))?)?/;
matreshka_dir_core_events_trigger = function (core, sym, utils, domEvtReg) {
var triggerDOMEvent = function (el, name, args) {
var doc = document, event;
if (doc.createEvent) {
event = doc.createEvent('Event');
event.initEvent(name, true, true);
event.mkArgs = args;
el.dispatchEvent(event);
} else if (typeof Event != 'undefined' && !el.fireEvent) {
event = new Event(name, {
bubbles: true,
cancelable: true
});
event.mkArgs = args;
el.dispatchEvent(event);
} else if (el.fireEvent) {
event = doc.createEventObject();
event.mkArgs = args;
el.fireEvent('on' + name, event);
} else {
throw Error('Cannot trigger DOM event');
}
return event;
};
core.trigger = function (object, names) {
var allEvents = object && typeof object == 'object' && object[sym] && object[sym].events, args, i, j, l, events, ev, name, executed, nodes, _nodes, selector;
if (names && allEvents) {
args = utils.toArray(arguments, 2);
names = names.split(/\s/);
for (i = 0; i < names.length; i++) {
name = names[i];
if (~name.indexOf('::')) {
executed = domEvtReg.exec(name);
nodes = object[sym].special[executed[3] || 'sandbox'];
nodes = nodes && nodes.$nodes;
_nodes = core.$();
selector = executed[5];
if (selector) {
for (j = 0; j < nodes.length; j++) {
_nodes = _nodes.add(nodes.find(selector));
}
} else {
_nodes = nodes;
}
for (j = 0; j < _nodes.length; j++) {
triggerDOMEvent(_nodes[i], executed[1], args);
}
} else {
events = allEvents[name];
if (events) {
j = -1, l = events.length;
while (++j < l)
(ev = events[j]).callback.apply(ev.ctx, args);
}
}
}
}
return object;
};
core._fastTrigger = function (object, name, evt) {
var events = object[sym].events[name], i, l, ev;
if (events) {
i = -1, l = events.length;
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, evt);
}
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym, matreshka_dir_core_util_common, matreshka_dir_core_var_domevtreg);
matreshka_dir_core_events_on = function (core, initMK, util) {
var on = core.on = function (object, names, callback, triggerOnInit, context, evtData) {
if (!object)
return object;
initMK(object);
var t, i, name, path, lastIndexOfET;
// if event-callback object is passed to the function
if (typeof names == 'object' && !(names instanceof Array)) {
for (i in names) {
if (names.hasOwnProperty(i)) {
on(object, i, names[i], callback, triggerOnInit);
}
}
return object;
}
// callback is required
if (!callback)
throw Error('callback is not function for event(s) "' + names + '"');
names = names instanceof Array ? names : util.trim(names).replace(/\s+/g, ' ') // single spaces only
.split(/\s(?![^(]*\))/g) // split by spaces
;
// allow to flip triggerOnInit and context
if (typeof triggerOnInit != 'boolean' && typeof triggerOnInit != 'undefined') {
t = context;
context = triggerOnInit;
triggerOnInit = t;
}
for (i = 0; i < names.length; i++) {
name = names[i];
// index of @
lastIndexOfET = name.lastIndexOf('@');
if (~lastIndexOfET) {
path = name.slice(0, lastIndexOfET);
// fallback for older apps
if (!path) {
path = '*';
} else if (~path.indexOf('@')) {
path = path.replace(/([^@]*)@/g, function ($0, key) {
return (key || '*') + '.';
}).replace(/\.$/, '.*') || '*';
}
name = name.slice(lastIndexOfET + 1);
core._delegateListener(object, path, name, callback, context || object, evtData);
} else {
core._addListener(object, name, callback, context, evtData);
}
}
// trigger after event is initialized
if (triggerOnInit === true) {
callback.call(context || object, { triggeredOnInit: true });
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk, matreshka_dir_core_util_common);
matreshka_dir_core_events_off = function (core, initMK, util, sym) {
var off = core.off = function (object, names, callback, context) {
if (!object || typeof object != 'object' || !object[sym])
return object;
var i, path, lastIndexOfET, name;
// if event-callback object is passed to the function
if (typeof names == 'object' && !(names instanceof Array)) {
for (i in names)
if (names.hasOwnProperty(i)) {
off(object, i, names[i], callback);
}
return object;
}
if (!names && !callback && !context && object[sym]) {
object[sym].events = {};
return object;
}
names = util.trim(names).replace(/\s+/g, ' ') // single spaces only
.split(/\s(?![^(]*\))/g);
if (typeof object != 'object') {
return object;
}
for (i = 0; i < names.length; i++) {
name = names[i];
// index of @
lastIndexOfET = name.lastIndexOf('@');
if (~lastIndexOfET) {
path = name.slice(0, lastIndexOfET);
name = name.slice(lastIndexOfET + 1).replace(/@/g, '.');
core._undelegateListener(object, path, name, callback, context);
} else {
core._removeListener(object, name, callback, context);
}
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk, matreshka_dir_core_util_common, matreshka_dir_core_var_sym);
matreshka_dir_core_var_specialevtreg = /_rundependencies:|_runbindings:|change:/;
matreshka_dir_core_events_addlistener = function (core, initMK, sym, specialEvtReg, domEvtReg) {
var _addListener;
core._fastAddListener = function (object, name, callback, context, evtData) {
var allEvents = object[sym].events, events = allEvents[name] || (allEvents[name] = []);
events.push({
callback: callback,
context: context,
ctx: context || object,
name: name,
node: evtData && evtData.node
});
if (specialEvtReg.test(name)) {
// define needed accessors for KEY
core._defineSpecial(object, name.replace(specialEvtReg, ''));
}
return object;
};
_addListener = core._addListener = function (object, name, callback, context, evtData) {
if (!object || typeof object != 'object')
return false;
initMK(object);
var ctx = context || object, allEvents = object[sym].events, events = allEvents[name] || (allEvents[name] = []), l = events.length, defaultEvtData = {
callback: callback,
//_callback: callback._callback || callback,
context: context,
ctx: ctx,
//howToRemove: null,
name: name
}, i, ev, _evtData, executed;
for (i = 0; i < l; i++) {
ev = events[i];
if ((ev.callback == callback || ev.callback == callback._callback) && ev.context == context) {
return false;
}
}
if (evtData) {
_evtData = {};
for (i in evtData) {
_evtData[i] = evtData[i];
}
for (i in defaultEvtData) {
_evtData[i] = defaultEvtData[i];
}
} else {
_evtData = defaultEvtData;
}
events.push(_evtData);
executed = domEvtReg.exec(name);
if (executed && executed[2]) {
core._addDOMListener(object, executed[3] || 'sandbox', executed[1], executed[5], callback, ctx, _evtData);
} else if (specialEvtReg.test(name)) {
// define needed accessors for KEY
core._defineSpecial(object, name.replace(specialEvtReg, ''));
}
core._fastTrigger(object, 'addevent:' + name, _evtData);
core._fastTrigger(object, 'addevent', _evtData);
return true;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk, matreshka_dir_core_var_sym, matreshka_dir_core_var_specialevtreg, matreshka_dir_core_var_domevtreg);
matreshka_dir_core_events_removelistener = function (core, sym) {
core._removeListener = function (object, name, callback, context, evtData) {
if (!object || typeof object != 'object' || !object[sym] || !object[sym].events)
return object;
var events = object[sym].events[name] || [], retain = object[sym].events[name] = [], domEvtNameRegExp = /([^\:\:]+)(::([^\(\)]+)(\((.*)\))?)?/, j = 0, l = events.length, evt, i, executed, howToRemove, removeEvtData;
evtData = evtData || {};
executed = domEvtNameRegExp.exec(name);
if (executed && executed[2]) {
core._removeDOMListener(object, executed[3], executed[1], executed[5], callback, context);
} else {
for (i = 0; i < l; i++) {
evt = events[i];
howToRemove = evt.howToRemove || evtData.howToRemove;
if (howToRemove ? !howToRemove(evt, evtData) : callback && (callback !== evt.callback && callback._callback !== evt.callback) || context && context !== evt.context) {
retain[j++] = evt;
} else {
removeEvtData = {
name: name,
callback: evt.callback,
context: evt.context
};
core._fastTrigger(object, 'removeevent:' + name, removeEvtData);
core._fastTrigger(object, 'removeevent', removeEvtData);
}
}
if (!retain.length) {
delete object[sym].events[name];
}
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym);
matreshka_dir_core_events_delegatelistener = function (core, initMK, sym, specialEvtReg) {
/**
* @private
* @summary this experimental function adds event listener to any object from deep tree of objects
*/
var _delegateTreeListener = core._delegateTreeListener = function (object, path, name, callback, context, evtData) {
if (!object || typeof object != 'object')
return object;
var f;
f = function (evt) {
var target = object[evt.key];
if (target) {
_delegateListener(target, path, name, callback, context, evtData);
_delegateTreeListener(target, path, name, callback, context, evtData);
}
};
each(object, function (item) {
_delegateListener(item, path, name, callback, context, evtData);
_delegateTreeListener(item, path, name, callback, context, evtData);
});
f._callback = callback;
core._addListener(object, 'change', f, context, evtData);
return object;
};
var _delegateListener = core._delegateListener = function (object, path, name, callback, context, evtData) {
if (!object || typeof object != 'object')
return object;
initMK(object);
var executed = /([^\.]+)\.(.*)/.exec(path), f, firstKey = executed ? executed[1] : path, changeKey, obj;
path = executed ? executed[2] : '';
evtData = evtData || {};
if (firstKey) {
if (firstKey == '*') {
if (object.isMKArray) {
f = function (evt) {
(evt && evt.added ? evt.added : object).forEach(function (item) {
item && _delegateListener(item, path, name, callback, context, evtData);
});
};
f._callback = callback;
core._addListener(object, 'add', f, context, evtData);
f();
} else if (object.isMKObject) {
f = function (evt) {
var target = object[evt.key];
if (target && evt && evt.key in object[sym].keys) {
_delegateListener(target, path, name, callback, context, evtData);
}
};
object.each(function (item) {
_delegateListener(item, path, name, callback, context, evtData);
});
f._callback = callback;
core._addListener(object, 'change', f, context, evtData);
} /* else {
throw Error('"*" events are only allowed for MK.Array and MK.Object');
}*/
} else {
f = function (evt) {
if (evt && evt._silent)
return;
var target = object[firstKey], changeKey, triggerChange = true, i, changeEvents;
evtData.path = path;
evtData.previousValue = evt && evt.previousValue || evtData.previousValue && evtData.previousValue[firstKey];
if (evt && evt.previousValue && evt.previousValue[sym]) {
core._undelegateListener(evt.previousValue, path, name, callback, context, evtData);
}
if (typeof target == 'object' && target) {
_delegateListener(target, path, name, callback, context, evtData);
}
if (specialEvtReg.test(name)) {
changeKey = name.replace(specialEvtReg, '');
if (!path && evtData.previousValue && evtData.previousValue[changeKey] !== target[changeKey]) {
changeEvents = evtData.previousValue[sym].events[name];
if (changeEvents) {
for (i = 0; i < changeEvents.length; i++) {
if (changeEvents[i].path === path) {
triggerChange = false;
}
}
}
if (triggerChange) {
core.set(target, changeKey, target[changeKey], {
force: true,
previousValue: evtData.previousValue[changeKey],
previousObject: evtData.previousValue,
_silent: true
});
}
}
}
};
f._callback = callback;
core._addListener(object, 'change:' + firstKey, f, context, evtData);
f();
}
} else {
core._addListener(object, name, callback, context, evtData);
}
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk, matreshka_dir_core_var_sym, matreshka_dir_core_var_specialevtreg);
matreshka_dir_core_events_undelegatelistener = function (core, sym) {
var _undelegateListener = core._undelegateListener = function (object, path, name, callback, context, evtData) {
if (!object || typeof object != 'object')
return object;
var executed = /([^\.]+)\.(.*)/.exec(path), firstKey = executed ? executed[1] : path, events, i, p = path;
path = executed ? executed[2] : '';
if (firstKey) {
if (firstKey == '*') {
if (object.isMKArray) {
if (callback) {
_undelegateListener(object, path, 'add', callback, context, evtData);
} else {
events = object[sym].events.add || [];
for (i = 0; i < events.length; i++) {
if (events[i].path == p) {
_undelegateListener(object, path, 'add', events[i].callback);
}
}
}
object.forEach(function (item) {
item && _undelegateListener(item, path, name, callback, context);
});
} else if (object.isMKObject) {
if (callback) {
_undelegateListener(object, path, 'change', callback, context);
} else {
events = object[sym].events.change || [];
for (i = 0; i < events.length; i++) {
if (events[i].path == p) {
_undelegateListener(object, path, 'change', events[i].callback);
}
}
}
object.each(function (item) {
item && _undelegateListener(item, path, name, callback, context);
});
}
} else {
if (callback) {
core._removeListener(object, 'change:' + firstKey, callback, context, evtData);
} else {
events = object[sym].events['change:' + firstKey] || [];
for (i = 0; i < events.length; i++) {
if (events[i].path == p) {
core._removeListener(object, 'change:' + firstKey, events[i].callback);
}
}
}
if (typeof object[firstKey] == 'object') {
_undelegateListener(object[firstKey], path, name, callback, context, evtData);
}
}
} else {
core._removeListener(object, name, callback, context, evtData);
}
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym);
matreshka_dir_core_events_domevents = function (core, sym) {
var list = {};
/**
* @private
* @since 0.0.4
* @todo optimize
* @summary This object is used to map DOM nodes and their DOM events
*/
core.domEvents = {
// adds events to the map
add: function (o) {
var $ = core.$;
if (o.node) {
if (typeof o.on == 'function') {
o.on.call(o.node, o.handler);
} else {
$(o.node).on(o.on.split(/\s/).join('.mk ') + '.mk', o.handler);
}
}
(list[o.instance[sym].id] = list[o.instance[sym].id] || []).push(o);
},
// removes events from the map
remove: function (o) {
var evts = list[o.instance[sym].id], $ = core.$, evt, i;
if (!evts)
return;
for (i = 0; i < evts.length; i++) {
evt = evts[i];
if (evt.node !== o.node)
continue;
// remove Matreshka event
evt.mkHandler && core._removeListener(o.instance, '_runbindings:' + o.key, evt.mkHandler);
// remove DOM event
if (typeof evt.on == 'string') {
$(o.node).off(evt.on + '.mk', evt.handler);
}
evt.removed = true;
list[o.instance[sym].id].splice(i--, 1);
}
}
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym);
matreshka_dir_core_events_adddomlistener = function (core, initMK, sym) {
core._addDOMListener = function (object, key, domEvtName, selector, callback, context, evtData) {
if (!object || typeof object != 'object')
return object;
initMK(object);
selector = selector || null;
evtData = evtData || {};
var domEvtHandler = function (domEvt) {
var node = this, $ = core.$, $nodes = $(node), mkArgs = domEvt.originalEvent ? domEvt.originalEvent.mkArgs : domEvt.mkArgs, evt = {
self: object,
node: node,
$nodes: $nodes,
key: key,
domEvent: domEvt,
originalEvent: domEvt.originalEvent || domEvt,
preventDefault: function () {
domEvt.preventDefault();
},
stopPropagation: function () {
domEvt.stopPropagation();
},
which: domEvt.which,
target: domEvt.target
}, randomID, is;
// DOM event is delegated
if (selector) {
randomID = 'x' + String(Math.random()).split('.')[1];
node.setAttribute(randomID, randomID);
is = '[' + randomID + '="' + randomID + '"] ' + selector;
if ($(domEvt.target).is(is + ',' + is + ' *')) {
callback.apply(context, mkArgs ? mkArgs : [evt]);
}
node.removeAttribute(randomID);
} else {
callback.apply(context, mkArgs ? mkArgs : [evt]);
}
}, fullEvtName = domEvtName + '.' + object[sym].id + key, bindHandler = function (evt) {
evt && evt.$nodes && evt.$nodes.on(fullEvtName, domEvtHandler);
}, unbindHandler = function (evt) {
evt && evt.$nodes && evt.$nodes.off(fullEvtName, domEvtHandler);
};
domEvtHandler._callback = callback;
core._defineSpecial(object, key);
bindHandler._callback = unbindHandler._callback = callback;
if (core._addListener(object, 'bind:' + key, bindHandler, context, evtData) && core._addListener(object, 'unbind:' + key, unbindHandler, context, evtData)) {
bindHandler({ $nodes: object[sym].special[key] && object[sym].special[key].$nodes });
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk, matreshka_dir_core_var_sym);
matreshka_dir_core_events_removedomlistener = function (core, sym) {
core._removeDOMListener = function (object, key, domEvtName, selector, callback, context, evtData) {
if (!object || typeof object != 'object' || !object[sym] || !object[sym].events)
return object;
selector = selector || null;
evtData = evtData || {};
if (key && object[sym].special[key]) {
object[sym].special[key].$nodes.off(domEvtName + '.' + object[sym].id + key, callback);
core._removeListener(object, 'bind:' + key, callback, context, evtData);
core._removeListener(object, 'unbind:' + key, callback, context, evtData);
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym);
matreshka_dir_core_events_once = function (core, initMK) {
var once = core.once = function (object, names, callback, context, evtData) {
var i;
if (!object || typeof object != 'object')
return object;
if (typeof names == 'object') {
for (i in names)
if (names.hasOwnProperty(i)) {
once(object, i, names[i], callback, context);
}
return object;
}
if (!callback)
throw Error('callback is not function for event "' + names + '"');
initMK(object);
names = names.split(/\s/);
for (i = 0; i < names.length; i++) {
(function (name) {
var once = function (func) {
var ran = false, memo;
return function () {
if (ran)
return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
}(callback);
once._callback = callback;
core.on(object, name, once, context);
}(names[i]));
}
return object;
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk);
matreshka_dir_core_events_ondebounce = function (core, initMK, util) {
var onDebounce = core.onDebounce = function (object, names, callback, debounceDelay, triggerOnInit, context, evtData) {
if (!object || typeof object != 'object')
return object;
var cbc, i;
if (typeof names == 'object') {
for (i in names)
if (names.hasOwnProperty(i)) {
onDebounce(object, i, names[i], callback, debounceDelay, triggerOnInit, context);
}
return object;
}
// flip args
if (typeof debounceDelay != 'number') {
evtData = context;
context = triggerOnInit;
triggerOnInit = debounceDelay;
debounceDelay = 0;
}
cbc = util.debounce(callback, debounceDelay);
// set reference to real callback for .off method
cbc._callback = callback;
return core.on(object, names, cbc, triggerOnInit, context, evtData);
};
}(matreshka_dir_core_var_core, matreshka_dir_core_initmk, matreshka_dir_core_util_common);
matreshka_magic = function (core, sym) {
core.sym = sym;
return core;
}(matreshka_dir_core_var_core, matreshka_dir_core_var_sym);
matreshka_magic.version="1.4.0"; (function () {
// hack for systemjs builder
var d = "define";
// I don't know how to define modules with no dependencies (since we use AMDClean)
// so I have to hack it, unfortunatelly
if (typeof __root != 'undefined') {
/* global matreshka, balalaika, matreshka_magic, xclass, __root */
if (typeof define == 'function' && define.amd) {
if(__root[d]) {
__root[d]('matreshka-magic', function() {
return matreshka_magic;
});
}
define(function() {
return matreshka_magic;
});
} else if (typeof exports == "object") {
module.exports = matreshka_magic;
} else {
__root.magic = __root.MatreshkaMagic = matreshka_magic;
}
}
})() })(typeof window != "undefined" ? window : Function("return this")()); | him2him2/cdnjs | ajax/libs/matreshka/1.4.0/magic/matreshka-magic.js | JavaScript | mit | 80,960 |
CKEDITOR.plugins.setLang("colorbutton","eo",{auto:"Aŭtomata",bgColorTitle:"Fona Koloro",colors:{"000":"Nigra",8E5:"Kaŝtankolora","8B4513":"Mezbruna","2F4F4F":"Ardezgriza","008080":"Marĉanaskolora","000080":"Maristblua","4B0082":"Indigokolora",696969:"Malhelgriza",B22222:"Brikruĝa",A52A2A:"Bruna",DAA520:"Senbrilorkolora","006400":"Malhelverda","40E0D0":"Turkisblua","0000CD":"Reĝblua",800080:"Purpura",808080:"Griza",F00:"Ruĝa",FF8C00:"Malheloranĝkolora",FFD700:"Orkolora","008000":"Verda","0FF":"Verdblua",
"00F":"Blua",EE82EE:"Viola",A9A9A9:"Mezgriza",FFA07A:"Salmokolora",FFA500:"Oranĝkolora",FFFF00:"Flava","00FF00":"Limetkolora",AFEEEE:"Helturkiskolora",ADD8E6:"Helblua",DDA0DD:"Prunkolora",D3D3D3:"Helgriza",FFF0F5:"Lavendkolora vangoŝminko",FAEBD7:"Antikvablanka",FFFFE0:"Helflava",F0FFF0:"Vintromelonkolora",F0FFFF:"Lazura",F0F8FF:"Aliceblua",E6E6FA:"Lavendkolora",FFF:"Blanka","1ABC9C":"Fortverdblua","2ECC71":"Smeraldkolora","3498DB":"Brilblua","9B59B6":"Ametistkolora","4E5F70":"Grizblua",F1C40F:"Brilflava",
"16A085":"Malhelverdblua","27AE60":"Malhelsmeraldkolora","2980B9":"Fortblua","8E44AD":"Malhelviola","2C3E50":"Malsaturita Bluo",F39C12:"Oranĝkolora",E67E22:"Karotkolora",E74C3C:"Pale Ruĝa",ECF0F1:"Brile Arĝenta","95A5A6":"Helgrizverdblua",DDD:"Helgriza",D35400:"Kukurbokolora",C0392B:"Forte ruĝa",BDC3C7:"Arĝenta","7F8C8D":"Grizverdblua",999:"Malhelgriza"},more:"Pli da Koloroj...",panelTitle:"Koloroj",textColorTitle:"Teksta Koloro"}); | him2him2/cdnjs | ajax/libs/ckeditor/4.7.2/plugins/colorbutton/lang/eo.js | JavaScript | mit | 1,474 |
Ext.onReady(function(){if(Ext.Date){Ext.Date.monthNames=["Januar","Februar","Mart","April","Мај","Jun","Јul","Avgust","Septembar","Oktobar","Novembar","Decembar"];Ext.Date.dayNames=["Nedelja","Ponedeljak","Utorak","Sreda","Četvrtak","Petak","Subota"]}if(Ext.util&&Ext.util.Format){Ext.apply(Ext.util.Format,{thousandSeparator:".",decimalSeparator:",",currencySign:"\u0414\u0438\u043d\u002e",dateFormat:"d.m.Y"})}});Ext.define("Ext.locale.sr.view.View",{override:"Ext.view.View",emptyText:"Ne postoji ni jedan slog"});Ext.define("Ext.locale.sr.grid.plugin.DragDrop",{override:"Ext.grid.plugin.DragDrop",dragText:"{0} izabranih redova"});Ext.define("Ext.locale.sr.tab.Tab",{override:"Ext.tab.Tab",closeText:"Zatvori оvu »karticu«"});Ext.define("Ext.locale.sr.form.field.Base",{override:"Ext.form.field.Base",invalidText:"Unešena vrednost nije pravilna"});Ext.define("Ext.locale.sr.view.AbstractView",{override:"Ext.view.AbstractView",loadingText:"Učitavam..."});Ext.define("Ext.locale.sr.picker.Date",{override:"Ext.picker.Date",todayText:"Danas",minText:"Datum је ispred najmanjeg dozvoljenog datuma",maxText:"Datum је nakon najvećeg dozvoljenog datuma",disabledDaysText:"",disabledDatesText:"",nextText:"Sledeći mesec (Control+Desno)",prevText:"Prethodni mesec (Control+Levo)",monthYearText:"Izaberite mesec (Control+Gore/Dole za izbor godine)",todayTip:"{0} (Razmaknica)",format:"d.m.y",startDay:1});Ext.define("Ext.locale.sr.toolbar.Paging",{override:"Ext.PagingToolbar",beforePageText:"Strana",afterPageText:"od {0}",firstText:"Prva strana",prevText:"Prethodna strana",nextText:"Sledeća strana",lastText:"Poslednja strana",refreshText:"Osveži",displayMsg:"Prikazana {0} - {1} od {2}",emptyMsg:"Nemam šta prikazati"});Ext.define("Ext.locale.sr.form.field.Text",{override:"Ext.form.field.Text",minLengthText:"Minimalna dužina ovog polja је {0}",maxLengthText:"Maksimalna dužina ovog polja је {0}",blankText:"Polje је obavezno",regexText:"",emptyText:null});Ext.define("Ext.locale.sr.form.field.Number",{override:"Ext.form.field.Number",minText:"Minimalna vrednost u polju је {0}",maxText:"Maksimalna vrednost u polju је {0}",nanText:"{0} nije pravilan broj"});Ext.define("Ext.locale.sr.form.field.Date",{override:"Ext.form.field.Date",disabledDaysText:"Pasivno",disabledDatesText:"Pasivno",minText:"Datum u ovom polju mora biti nakon {0}",maxText:"Datum u ovom polju mora biti pre {0}",invalidText:"{0} nije pravilan datum - zahtevani oblik je {1}",format:"d.m.y",altFormats:"d.m.y|d/m/Y|d-m-y|d-m-Y|d/m|d-m|dm|dmy|dmY|d|Y-m-d"});Ext.define("Ext.locale.sr.form.field.ComboBox",{override:"Ext.form.field.ComboBox",valueNotFoundText:undefined},function(){Ext.apply(Ext.form.field.ComboBox.prototype.defaultListConfig,{loadingText:"Učitavam..."})});Ext.define("Ext.locale.sr.form.field.VTypes",{override:"Ext.form.field.VTypes",emailText:'Ovo polje prihavata e-mail adresu isključivo u obliku "korisnik@domen.com"',urlText:'Ovo polje prihavata URL adresu isključivo u obliku "http://www.domen.com"',alphaText:"Ovo polje može sadržati isključivo slova i znak _",alphanumText:"Ovo polje može sadržati само slova, brojeve i znak _"});Ext.define("Ext.locale.sr.grid.header.Container",{override:"Ext.grid.header.Container",sortAscText:"Rastući redosled",sortDescText:"Opadajući redosled",lockText:"Zaključaj kolonu",unlockText:"Otključaj kolonu",columnsText:"Kolone"});Ext.define("Ext.locale.sr.grid.PropertyColumnModel",{override:"Ext.grid.PropertyColumnModel",nameText:"Naziv",valueText:"Vrednost",dateFormat:"d.m.Y"});Ext.define("Ext.locale.sr.window.MessageBox",{override:"Ext.window.MessageBox",buttonText:{ok:"U redu",cancel:"Odustani",yes:"Da",no:"Ne"}});Ext.define("Ext.locale.sr.Component",{override:"Ext.Component"}); | tmorin/cdnjs | ajax/libs/extjs/4.2.1/locale/ext-lang-sr.min.js | JavaScript | mit | 3,767 |
/*! =========================================================
* bootstrap-slider.js
*
* Maintainers:
* Kyle Kemp
* - Twitter: @seiyria
* - Github: seiyria
* Rohit Kalkur
* - Twitter: @Rovolutionary
* - Github: rovolution
*
* =========================================================
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
/**
* Bridget makes jQuery widgets
* v1.0.1
* MIT license
*/
( function( $ ) {
( function( $ ) {
'use strict';
// -------------------------- utils -------------------------- //
var slice = Array.prototype.slice;
function noop() {}
// -------------------------- definition -------------------------- //
function defineBridget( $ ) {
// bail if no jQuery
if ( !$ ) {
return;
}
// -------------------------- addOptionMethod -------------------------- //
/**
* adds option method -> $().plugin('option', {...})
* @param {Function} PluginClass - constructor class
*/
function addOptionMethod( PluginClass ) {
// don't overwrite original option method
if ( PluginClass.prototype.option ) {
return;
}
// option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
// -------------------------- plugin bridge -------------------------- //
// helper function for logging errors
// $.error breaks jQuery chaining
var logError = typeof console === 'undefined' ? noop :
function( message ) {
console.error( message );
};
/**
* jQuery plugin bridge, access methods like $elem.plugin('method')
* @param {String} namespace - plugin name
* @param {Function} PluginClass - constructor class
*/
function bridge( namespace, PluginClass ) {
// add to jQuery fn namespace
$.fn[ namespace ] = function( options ) {
if ( typeof options === 'string' ) {
// call plugin method when first argument is a string
// get arguments for method
var args = slice.call( arguments, 1 );
for ( var i=0, len = this.length; i < len; i++ ) {
var elem = this[i];
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( "cannot call methods on " + namespace + " prior to initialization; " +
"attempted to call '" + options + "'" );
continue;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
logError( "no such method '" + options + "' for " + namespace + " instance" );
continue;
}
// trigger method with arguments
var returnValue = instance[ options ].apply( instance, args);
// break look and return first value if provided
if ( returnValue !== undefined && returnValue !== instance) {
return returnValue;
}
}
// return this if no return value
return this;
} else {
var objects = this.map( function() {
var instance = $.data( this, namespace );
if ( instance ) {
// apply options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( this, options );
$.data( this, namespace, instance );
}
return $(this);
});
if(!objects || objects.length > 1) {
return objects;
} else {
return objects[0];
}
}
};
}
// -------------------------- bridget -------------------------- //
/**
* converts a Prototypical class into a proper jQuery plugin
* the class must have a ._init method
* @param {String} namespace - plugin name, used in $().pluginName
* @param {Function} PluginClass - constructor class
*/
$.bridget = function( namespace, PluginClass ) {
addOptionMethod( PluginClass );
bridge( namespace, PluginClass );
};
return $.bridget;
}
// get jquery from browser global
defineBridget( $ );
})( $ );
/*************************************************
BOOTSTRAP-SLIDER SOURCE CODE
**************************************************/
(function( $ ) {
var ErrorMsgs = {
formatInvalidInputErrorMsg : function(input) {
return "Invalid input value '" + input + "' passed in";
},
callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
};
/*************************************************
CONSTRUCTOR
**************************************************/
var Slider = function(element, options) {
createNewSlider.call(this, element, options);
return this;
};
function createNewSlider(element, options) {
/*************************************************
Create Markup
**************************************************/
if(typeof element === "string") {
this.element = document.querySelector(element);
} else if(element instanceof HTMLElement) {
this.element = element;
}
var origWidth = this.element.style.width;
var updateSlider = false;
var parent = this.element.parentNode;
var sliderTrackSelection;
var sliderMinHandle;
var sliderMaxHandle;
if (this.sliderElem) {
updateSlider = true;
} else {
/* Create elements needed for slider */
this.sliderElem = document.createElement("div");
this.sliderElem.className = "slider";
/* Create slider track elements */
var sliderTrack = document.createElement("div");
sliderTrack.className = "slider-track";
sliderTrackSelection = document.createElement("div");
sliderTrackSelection.className = "slider-selection";
sliderMinHandle = document.createElement("div");
sliderMinHandle.className = "slider-handle min-slider-handle";
sliderMaxHandle = document.createElement("div");
sliderMaxHandle.className = "slider-handle max-slider-handle";
sliderTrack.appendChild(sliderTrackSelection);
sliderTrack.appendChild(sliderMinHandle);
sliderTrack.appendChild(sliderMaxHandle);
var createAndAppendTooltipSubElements = function(tooltipElem) {
var arrow = document.createElement("div");
arrow.className = "tooltip-arrow";
var inner = document.createElement("div");
inner.className = "tooltip-inner";
tooltipElem.appendChild(arrow);
tooltipElem.appendChild(inner);
};
/* Create tooltip elements */
var sliderTooltip = document.createElement("div");
sliderTooltip.className = "tooltip tooltip-main";
createAndAppendTooltipSubElements(sliderTooltip);
var sliderTooltipMin = document.createElement("div");
sliderTooltipMin.className = "tooltip tooltip-min";
createAndAppendTooltipSubElements(sliderTooltipMin);
var sliderTooltipMax = document.createElement("div");
sliderTooltipMax.className = "tooltip tooltip-max";
createAndAppendTooltipSubElements(sliderTooltipMax);
/* Append components to sliderElem */
this.sliderElem.appendChild(sliderTrack);
this.sliderElem.appendChild(sliderTooltip);
this.sliderElem.appendChild(sliderTooltipMin);
this.sliderElem.appendChild(sliderTooltipMax);
/* Append slider element to parent container, right before the original <input> element */
parent.insertBefore(this.sliderElem, this.element);
/* Hide original <input> element */
this.element.style.display = "none";
}
/* If JQuery exists, cache JQ references */
if($) {
this.$element = $(this.element);
this.$sliderElem = $(this.sliderElem);
}
/*************************************************
Process Options
**************************************************/
options = options ? options : {};
var optionTypes = Object.keys(this.defaultOptions);
for(var i = 0; i < optionTypes.length; i++) {
var optName = optionTypes[i];
// First check if an option was passed in via the constructor
var val = options[optName];
// If no data attrib, then check data atrributes
val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName);
// Finally, if nothing was specified, use the defaults
val = (val !== null) ? val : this.defaultOptions[optName];
// Set all options on the instance of the Slider
if(!this.options) {
this.options = {};
}
this.options[optName] = val;
}
function getDataAttrib(element, optName) {
var dataName = "data-slider-" + optName;
var dataValString = element.getAttribute(dataName);
try {
return JSON.parse(dataValString);
}
catch(err) {
return dataValString;
}
}
/*************************************************
Setup
**************************************************/
this.eventToCallbackMap = {};
this.sliderElem.id = this.options.id;
this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
this.tooltip = this.sliderElem.querySelector('.tooltip-main');
this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner');
if (updateSlider === true) {
// Reset classes
this._removeClass(this.sliderElem, 'slider-horizontal');
this._removeClass(this.sliderElem, 'slider-vertical');
this._removeClass(this.tooltip, 'hide');
this._removeClass(this.tooltip_min, 'hide');
this._removeClass(this.tooltip_max, 'hide');
// Undo existing inline styles for track
["left", "top", "width", "height"].forEach(function(prop) {
this._removeProperty(this.trackSelection, prop);
}, this);
// Undo inline styles on handles
[this.handle1, this.handle2].forEach(function(handle) {
this._removeProperty(handle, 'left');
this._removeProperty(handle, 'top');
}, this);
// Undo inline styles and classes on tooltips
[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) {
this._removeProperty(tooltip, 'left');
this._removeProperty(tooltip, 'top');
this._removeProperty(tooltip, 'margin-left');
this._removeProperty(tooltip, 'margin-top');
this._removeClass(tooltip, 'right');
this._removeClass(tooltip, 'top');
}, this);
}
if(this.options.orientation === 'vertical') {
this._addClass(this.sliderElem,'slider-vertical');
this.stylePos = 'top';
this.mousePos = 'pageY';
this.sizePos = 'offsetHeight';
this._addClass(this.tooltip, 'right');
this.tooltip.style.left = '100%';
this._addClass(this.tooltip_min, 'right');
this.tooltip_min.style.left = '100%';
this._addClass(this.tooltip_max, 'right');
this.tooltip_max.style.left = '100%';
} else {
this._addClass(this.sliderElem, 'slider-horizontal');
this.sliderElem.style.width = origWidth;
this.options.orientation = 'horizontal';
this.stylePos = 'left';
this.mousePos = 'pageX';
this.sizePos = 'offsetWidth';
this._addClass(this.tooltip, 'top');
this.tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
this._addClass(this.tooltip_min, 'top');
this.tooltip_min.style.top = -this.tooltip_min.outerHeight - 14 + 'px';
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -this.tooltip_max.outerHeight - 14 + 'px';
}
if (this.options.value instanceof Array) {
this.options.range = true;
} else if (this.options.range) {
// User wants a range, but value is not an array
this.options.value = [this.options.value, this.options.max];
}
this.trackSelection = sliderTrackSelection || this.trackSelection;
if (this.options.selection === 'none') {
this._addClass(this.trackSelection, 'hide');
}
this.handle1 = sliderMinHandle || this.handle1;
this.handle2 = sliderMaxHandle || this.handle2;
if (updateSlider === true) {
// Reset classes
this._removeClass(this.handle1, 'round triangle');
this._removeClass(this.handle2, 'round triangle hide');
}
var availableHandleModifiers = ['round', 'triangle', 'custom'];
var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
if (isValidHandleType) {
this._addClass(this.handle1, this.options.handle);
this._addClass(this.handle2, this.options.handle);
}
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
this.setValue(this.options.value);
/******************************************
Bind Event Listeners
******************************************/
// Bind keyboard handlers
this.handle1Keydown = this._keydown.bind(this, 0);
this.handle1.addEventListener("keydown", this.handle1Keydown, false);
this.handle2Keydown = this._keydown.bind(this, 0);
this.handle2.addEventListener("keydown", this.handle2Keydown, false);
if (this.touchCapable) {
// Bind touch handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("touchstart", this.mousedown, false);
} else {
// Bind mouse handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("mousedown", this.mousedown, false);
}
// Bind tooltip-related handlers
if(this.options.tooltip === 'hide') {
this._addClass(this.tooltip, 'hide');
this._addClass(this.tooltip_min, 'hide');
this._addClass(this.tooltip_max, 'hide');
} else if(this.options.tooltip === 'always') {
this._showTooltip();
this._alwaysShowTooltip = true;
} else {
this.showTooltip = this._showTooltip.bind(this);
this.hideTooltip = this._hideTooltip.bind(this);
this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
this.handle1.addEventListener("focus", this.showTooltip, false);
this.handle1.addEventListener("blur", this.hideTooltip, false);
this.handle2.addEventListener("focus", this.showTooltip, false);
this.handle2.addEventListener("blur", this.hideTooltip, false);
}
if(this.options.enabled) {
this.enable();
} else {
this.disable();
}
}
/*************************************************
INSTANCE PROPERTIES/METHODS
- Any methods bound to the prototype are considered
part of the plugin's `public` interface
**************************************************/
Slider.prototype = {
_init: function() {}, // NOTE: Must exist to support bridget
constructor: Slider,
defaultOptions: {
id: "",
min: 0,
max: 10,
step: 1,
precision: 0,
orientation: 'horizontal',
value: 5,
range: false,
selection: 'before',
tooltip: 'show',
tooltip_split: false,
handle: 'round',
reversed: false,
enabled: true,
formatter: function(val) {
if(val instanceof Array) {
return val[0] + " : " + val[1];
} else {
return val;
}
},
natural_arrow_keys: false
},
over: false,
inDrag: false,
getValue: function() {
if (this.options.range) {
return this.options.value;
}
return this.options.value[0];
},
setValue: function(val, triggerSlideEvent) {
if (!val) {
val = 0;
}
this.options.value = this._validateInputValue(val);
var applyPrecision = this._applyPrecision.bind(this);
if (this.options.range) {
this.options.value[0] = applyPrecision(this.options.value[0]);
this.options.value[1] = applyPrecision(this.options.value[1]);
this.options.value[0] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[0]));
this.options.value[1] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[1]));
} else {
this.options.value = applyPrecision(this.options.value);
this.options.value = [ Math.max(this.options.min, Math.min(this.options.max, this.options.value))];
this._addClass(this.handle2, 'hide');
if (this.options.selection === 'after') {
this.options.value[1] = this.options.max;
} else {
this.options.value[1] = this.options.min;
}
}
this.diff = this.options.max - this.options.min;
if (this.diff > 0) {
this.percentage = [
(this.options.value[0] - this.options.min) * 100 / this.diff,
(this.options.value[1] - this.options.min) * 100 / this.diff,
this.options.step * 100 / this.diff
];
} else {
this.percentage = [0, 0, 100];
}
this._layout();
var sliderValue = this.options.range ? this.options.value : this.options.value[0];
this._setDataVal(sliderValue);
if(triggerSlideEvent === true) {
this._trigger('slide', sliderValue);
}
return this;
},
destroy: function(){
// Remove event handlers on slider elements
this._removeSliderEventHandlers();
// Remove the slider from the DOM
this.sliderElem.parentNode.removeChild(this.sliderElem);
/* Show original <input> element */
this.element.style.display = "";
// Clear out custom event bindings
this._cleanUpEventCallbacksMap();
// Remove data values
this.element.removeAttribute("data");
// Remove JQuery handlers/data
if($) {
this._unbindJQueryEventHandlers();
this.$element.removeData('slider');
}
},
disable: function() {
this.options.enabled = false;
this.handle1.removeAttribute("tabindex");
this.handle2.removeAttribute("tabindex");
this._addClass(this.sliderElem, 'slider-disabled');
this._trigger('slideDisabled');
return this;
},
enable: function() {
this.options.enabled = true;
this.handle1.setAttribute("tabindex", 0);
this.handle2.setAttribute("tabindex", 0);
this._removeClass(this.sliderElem, 'slider-disabled');
this._trigger('slideEnabled');
return this;
},
toggle: function() {
if(this.options.enabled) {
this.disable();
} else {
this.enable();
}
return this;
},
isEnabled: function() {
return this.options.enabled;
},
on: function(evt, callback) {
if($) {
this.$element.on(evt, callback);
this.$sliderElem.on(evt, callback);
} else {
this._bindNonQueryEventHandler(evt, callback);
}
return this;
},
getAttribute: function(attribute) {
if(attribute) {
return this.options[attribute];
} else {
return this.options;
}
},
setAttribute: function(attribute, value) {
this.options[attribute] = value;
return this;
},
refresh: function() {
this._removeSliderEventHandlers();
createNewSlider.call(this, this.element, this.options);
if($) {
// Bind new instance of slider to the element
$.data(this.element, 'slider', this);
}
return this;
},
/******************************+
HELPERS
- Any method that is not part of the public interface.
- Place it underneath this comment block and write its signature like so:
_fnName : function() {...}
********************************/
_removeSliderEventHandlers: function() {
// Remove event listeners from handle1
this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
this.handle1.removeEventListener("focus", this.showTooltip, false);
this.handle1.removeEventListener("blur", this.hideTooltip, false);
// Remove event listeners from handle2
this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
this.handle2.removeEventListener("focus", this.handle2Keydown, false);
this.handle2.removeEventListener("blur", this.handle2Keydown, false);
// Remove event listeners from sliderElem
this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
this.sliderElem.removeEventListener("touchstart", this.mousedown, false);
this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
},
_bindNonQueryEventHandler: function(evt, callback) {
if(this.eventToCallbackMap[evt]===undefined) {
this.eventToCallbackMap[evt] = [];
}
this.eventToCallbackMap[evt].push(callback);
},
_cleanUpEventCallbacksMap: function() {
var eventNames = Object.keys(this.eventToCallbackMap);
for(var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
this.eventToCallbackMap[eventName] = null;
}
},
_showTooltip: function() {
if (this.options.tooltip_split === false ){
this._addClass(this.tooltip, 'in');
} else {
this._addClass(this.tooltip_min, 'in');
this._addClass(this.tooltip_max, 'in');
}
this.over = true;
},
_hideTooltip: function() {
if (this.inDrag === false && this.alwaysShowTooltip !== true) {
this._removeClass(this.tooltip, 'in');
this._removeClass(this.tooltip_min, 'in');
this._removeClass(this.tooltip_max, 'in');
}
this.over = false;
},
_layout: function() {
var positionPercentages;
if(this.options.reversed) {
positionPercentages = [ 100 - this.percentage[0], this.percentage[1] ];
} else {
positionPercentages = [ this.percentage[0], this.percentage[1] ];
}
this.handle1.style[this.stylePos] = positionPercentages[0]+'%';
this.handle2.style[this.stylePos] = positionPercentages[1]+'%';
if (this.options.orientation === 'vertical') {
this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
} else {
this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
var offset_min = this.tooltip_min.getBoundingClientRect();
var offset_max = this.tooltip_max.getBoundingClientRect();
if (offset_min.right > offset_max.left) {
this._removeClass(this.tooltip_max, 'top');
this._addClass(this.tooltip_max, 'bottom');
this.tooltip_max.style.top = 18 + 'px';
} else {
this._removeClass(this.tooltip_max, 'bottom');
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -30 + 'px';
}
}
var formattedTooltipVal;
if (this.options.range) {
formattedTooltipVal = this.options.formatter(this.options.value);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0])/2 + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
var innerTooltipMinText = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner_min, innerTooltipMinText);
var innerTooltipMaxText = this.options.formatter(this.options.value[1]);
this._setText(this.tooltipInner_max, innerTooltipMaxText);
this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px');
}
this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px');
}
} else {
formattedTooltipVal = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
}
},
_removeProperty: function(element, prop) {
if (element.style.removeProperty) {
element.style.removeProperty(prop);
} else {
element.style.removeAttribute(prop);
}
},
_mousedown: function(ev) {
if(!this.options.enabled) {
return false;
}
this._triggerFocusOnHandle();
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
var percentage = this._getPercentage(ev);
if (this.options.range) {
var diff1 = Math.abs(this.percentage[0] - percentage);
var diff2 = Math.abs(this.percentage[1] - percentage);
this.dragged = (diff1 < diff2) ? 0 : 1;
} else {
this.dragged = 0;
}
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
this.mousemove = this._mousemove.bind(this);
this.mouseup = this._mouseup.bind(this);
if (this.touchCapable) {
// Touch: Bind touch events:
document.addEventListener("touchmove", this.mousemove, false);
document.addEventListener("touchend", this.mouseup, false);
} else {
// Bind mouse events:
document.addEventListener("mousemove", this.mousemove, false);
document.addEventListener("mouseup", this.mouseup, false);
}
this.inDrag = true;
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val);
this._pauseEvent(ev);
return true;
},
_triggerFocusOnHandle: function(handleIdx) {
if(handleIdx === 0) {
this.handle1.focus();
}
if(handleIdx === 1) {
this.handle2.focus();
}
},
_keydown: function(handleIdx, ev) {
if(!this.options.enabled) {
return false;
}
var dir;
switch (ev.keyCode) {
case 37: // left
case 40: // down
dir = -1;
break;
case 39: // right
case 38: // up
dir = 1;
break;
}
if (!dir) {
return;
}
// use natural arrow keys instead of from min to max
if (this.options.natural_arrow_keys) {
var ifVerticalAndNotReversed = (this.options.orientation === 'vertical' && !this.options.reversed);
var ifHorizontalAndReversed = (this.options.orientation === 'horizontal' && this.options.reversed);
if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
dir = dir * -1;
}
}
var oneStepValuePercentageChange = dir * this.percentage[2];
var percentage = this.percentage[handleIdx] + oneStepValuePercentageChange;
if (percentage > 100) {
percentage = 100;
} else if (percentage < 0) {
percentage = 0;
}
this.dragged = handleIdx;
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = percentage;
this._layout();
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val, true);
this._trigger('slideStop', val);
this._setDataVal(val);
this._pauseEvent(ev);
return false;
},
_pauseEvent: function(ev) {
if(ev.stopPropagation) {
ev.stopPropagation();
}
if(ev.preventDefault) {
ev.preventDefault();
}
ev.cancelBubble=true;
ev.returnValue=false;
},
_mousemove: function(ev) {
if(!this.options.enabled) {
return false;
}
var percentage = this._getPercentage(ev);
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
var val = this._calculateValue();
this.setValue(val, true);
return false;
},
_adjustPercentageForRangeSliders: function(percentage) {
if (this.options.range) {
if (this.dragged === 0 && this.percentage[1] < percentage) {
this.percentage[0] = this.percentage[1];
this.dragged = 1;
} else if (this.dragged === 1 && this.percentage[0] > percentage) {
this.percentage[1] = this.percentage[0];
this.dragged = 0;
}
}
},
_mouseup: function() {
if(!this.options.enabled) {
return false;
}
if (this.touchCapable) {
// Touch: Unbind touch event handlers:
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
} else {
// Unbind mouse event handlers:
document.removeEventListener("mousemove", this.mousemove, false);
document.removeEventListener("mouseup", this.mouseup, false);
}
this.inDrag = false;
if (this.over === false) {
this._hideTooltip();
}
var val = this._calculateValue();
this._layout();
this._setDataVal(val);
this._trigger('slideStop', val);
return false;
},
_calculateValue: function() {
var val;
if (this.options.range) {
val = [this.options.min,this.options.max];
if (this.percentage[0] !== 0){
val[0] = (Math.max(this.options.min, this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step));
val[0] = this._applyPrecision(val[0]);
}
if (this.percentage[1] !== 100){
val[1] = (Math.min(this.options.max, this.options.min + Math.round((this.diff * this.percentage[1]/100)/this.options.step)*this.options.step));
val[1] = this._applyPrecision(val[1]);
}
this.options.value = val;
} else {
val = (this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step);
if (val < this.options.min) {
val = this.options.min;
}
else if (val > this.options.max) {
val = this.options.max;
}
val = parseFloat(val);
val = this._applyPrecision(val);
this.options.value = [val, this.options.value[1]];
}
return val;
},
_applyPrecision: function(val) {
var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.step);
return this._applyToFixedAndParseFloat(val, precision);
},
_getNumDigitsAfterDecimalPlace: function(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
},
_applyToFixedAndParseFloat: function(num, toFixedInput) {
var truncatedNum = num.toFixed(toFixedInput);
return parseFloat(truncatedNum);
},
/*
Credits to Mike Samuel for the following method!
Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
*/
_getPercentage: function(ev) {
if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
ev = ev.touches[0];
}
var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size;
percentage = Math.round(percentage/this.percentage[2])*this.percentage[2];
return Math.max(0, Math.min(100, percentage));
},
_validateInputValue: function(val) {
if(typeof val === 'number') {
return val;
} else if(val instanceof Array) {
this._validateArray(val);
return val;
} else {
throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) );
}
},
_validateArray: function(val) {
for(var i = 0; i < val.length; i++) {
var input = val[i];
if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); }
}
},
_setDataVal: function(val) {
var value = "value: '" + val + "'";
this.element.setAttribute('data', value);
this.element.setAttribute('value', val);
},
_trigger: function(evt, val) {
val = val || undefined;
var callbackFnArray = this.eventToCallbackMap[evt];
if(callbackFnArray && callbackFnArray.length) {
for(var i = 0; i < callbackFnArray.length; i++) {
var callbackFn = callbackFnArray[i];
callbackFn(val);
}
}
/* If JQuery exists, trigger JQuery events */
if($) {
this._triggerJQueryEvent(evt, val);
}
},
_triggerJQueryEvent: function(evt, val) {
var eventData = {
type: evt,
value: val
};
this.$element.trigger(eventData);
this.$sliderElem.trigger(eventData);
},
_unbindJQueryEventHandlers: function() {
this.$element.off();
this.$sliderElem.off();
},
_setText: function(element, text) {
if(typeof element.innerText !== "undefined") {
element.innerText = text;
} else if(typeof element.textContent !== "undefined") {
element.textContent = text;
}
},
_removeClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
newClasses = newClasses.replace(regex, " ");
}
element.className = newClasses.trim();
},
_addClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
var ifClassExists = regex.test(newClasses);
if(!ifClassExists) {
newClasses += " " + classTag;
}
}
element.className = newClasses.trim();
},
_offset: function (obj) {
var ol = 0;
var ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
left: ol,
top: ot
};
},
_css: function(elementRef, styleName, value) {
elementRef.style[styleName] = value;
}
};
/*********************************
Attach to global namespace
*********************************/
if($) {
var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider';
$.bridget(namespace, Slider);
} else {
window.Slider = Slider;
}
})( $ );
})( window.jQuery ); | Vulcania/GSB_Symfony | web/bundles/general/bootstrapup/js/plugins/bootstrap-slider/bootstrap-slider.js | JavaScript | mit | 36,164 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/SuppMathOperators.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({MathJax_AMS:{10846:[[4,7,1],[5,8,1],[6,9,1],[7,12,2],[8,14,2],[10,16,2],[11,18,2],[13,22,3],[16,26,3],[19,31,4],[22,36,4],[26,43,5],[31,51,6],[37,61,7]],10877:[[5,7,2],[6,8,2],[8,9,2],[9,10,2],[10,11,2],[12,14,3],[14,16,3],[17,19,4],[20,22,4],[24,26,5],[28,31,6],[34,37,7],[40,44,8],[48,51,9]],10878:[[5,7,2],[6,8,2],[7,9,2],[9,10,2],[10,11,2],[12,14,3],[14,16,3],[17,19,4],[20,22,4],[23,26,5],[28,31,6],[33,37,7],[39,44,8],[46,51,9]],10885:[[5,8,2],[6,10,3],[7,11,3],[9,13,4],[10,15,4],[12,18,5],[14,21,6],[17,25,7],[20,31,9],[24,36,10],[29,42,12],[34,50,14],[40,60,17],[48,71,20]],10886:[[5,8,2],[6,10,3],[7,11,3],[9,13,4],[10,15,4],[12,18,5],[14,21,6],[17,25,7],[20,30,8],[24,36,10],[29,42,12],[34,50,14],[40,59,16],[48,70,19]],10887:[[5,7,2],[6,9,3],[7,10,3],[9,11,3],[10,13,4],[12,16,5],[14,18,5],[17,21,6],[20,25,7],[23,30,9],[28,35,10],[33,42,12],[39,50,14],[46,58,16]],10888:[[5,7,2],[6,9,3],[7,10,3],[9,11,3],[10,13,4],[12,16,5],[14,18,5],[17,21,6],[20,25,7],[23,30,9],[28,35,10],[33,42,12],[39,50,14],[46,58,16]],10889:[[5,9,3],[6,11,4],[8,12,4],[9,14,5],[10,17,6],[12,20,7],[14,23,8],[17,27,9],[20,33,11],[24,39,13],[29,46,16],[34,54,18],[40,65,22],[48,77,26]],10890:[[5,9,3],[6,11,4],[8,12,4],[9,14,5],[10,17,6],[12,20,7],[14,23,8],[17,27,9],[20,33,11],[24,39,13],[29,46,16],[34,54,18],[40,65,22],[48,77,26]],10891:[[5,11,4],[6,13,4],[7,15,5],[9,18,6],[10,21,7],[12,25,8],[14,30,10],[17,35,11],[20,41,13],[23,49,16],[28,59,19],[33,69,22],[39,82,26],[47,97,31]],10892:[[5,11,4],[6,13,4],[7,15,5],[9,18,6],[10,21,7],[12,25,8],[14,30,10],[17,35,11],[20,41,13],[23,49,16],[28,59,19],[33,69,22],[39,82,26],[46,97,31]],10901:[[5,6,1],[6,8,2],[8,9,2],[9,10,2],[10,11,2],[12,14,3],[14,16,3],[17,19,4],[20,22,4],[24,26,5],[28,31,6],[34,37,7],[40,43,8],[48,52,10]],10902:[[5,6,1],[6,8,2],[7,9,2],[9,10,2],[10,11,2],[12,14,3],[14,16,3],[17,19,4],[20,22,4],[23,26,5],[28,31,6],[33,37,7],[39,43,8],[46,52,10]],10933:[[5,8,2],[6,10,3],[7,11,3],[9,13,4],[10,15,4],[12,18,5],[14,21,6],[17,25,7],[20,29,8],[23,35,10],[28,42,12],[33,49,14],[39,58,16],[46,69,19]],10934:[[5,8,2],[6,10,3],[7,11,3],[9,13,4],[10,15,4],[12,18,5],[14,21,6],[17,25,7],[20,29,8],[23,35,10],[28,42,12],[33,49,14],[39,58,16],[46,69,19]],10935:[[5,8,2],[6,10,3],[8,11,3],[9,13,4],[10,15,4],[12,18,5],[14,21,6],[17,25,7],[20,31,9],[24,36,10],[29,42,12],[34,50,14],[40,60,17],[48,71,20]],10936:[[5,8,2],[6,10,3],[8,11,3],[9,13,4],[10,15,4],[12,18,5],[14,21,6],[17,25,7],[20,31,9],[24,36,10],[29,42,12],[34,50,14],[40,60,17],[48,71,20]],10937:[[5,9,3],[6,10,3],[8,12,4],[9,13,4],[10,16,5],[12,19,6],[15,22,7],[17,26,8],[20,32,10],[24,38,12],[29,44,14],[34,52,16],[40,62,19],[48,73,22]],10938:[[5,9,3],[6,10,3],[8,12,4],[9,13,4],[10,16,5],[12,19,6],[15,22,7],[17,26,8],[20,32,10],[24,38,12],[29,44,14],[34,52,16],[40,62,19],[48,73,22]],10949:[[5,8,2],[6,9,2],[7,10,2],[9,12,3],[10,14,3],[12,17,4],[14,20,5],[16,23,5],[20,28,7],[23,33,8],[27,39,9],[32,46,11],[39,55,13],[46,65,15]],10950:[[5,8,2],[6,9,2],[7,10,2],[9,12,3],[10,14,3],[12,17,4],[14,19,4],[17,23,5],[20,27,6],[24,32,7],[28,39,9],[33,46,10],[39,54,12],[47,64,14]],10955:[[5,9,3],[6,11,4],[7,12,4],[9,15,5],[10,17,6],[12,20,7],[14,24,8],[17,28,9],[20,33,11],[23,39,13],[28,47,16],[33,55,18],[39,66,22],[46,78,26]],10956:[[5,9,3],[6,11,4],[7,12,4],[9,14,5],[10,17,6],[12,20,7],[14,24,8],[17,28,9],[20,33,11],[23,39,13],[28,47,16],[33,55,18],[39,66,22],[46,78,26]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/AMS/Regular"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/SuppMathOperators.js");
| urish/cdnjs | ajax/libs/mathjax/2.4.0/fonts/HTML-CSS/TeX/png/AMS/Regular/SuppMathOperators.js | JavaScript | mit | 3,974 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/GeneralPunctuation.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({"MathJax_Main-bold":{8194:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],8195:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],8196:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],8197:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],8198:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],8201:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],8202:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],8211:[[4,1,-1],[5,1,-2],[6,1,-3],[7,1,-3],[8,1,-3],[10,1,-4],[12,2,-4],[14,3,-5],[16,3,-6],[19,2,-8],[23,3,-10],[27,3,-12],[32,3,-14],[38,4,-17]],8212:[[8,1,-1],[10,1,-2],[12,1,-3],[14,1,-3],[16,1,-3],[20,1,-4],[23,2,-4],[27,3,-5],[32,3,-6],[38,2,-8],[45,3,-10],[54,3,-12],[64,3,-14],[76,4,-17]],8216:[[2,3,-2],[3,3,-3],[3,4,-4],[3,4,-4],[4,5,-4],[5,7,-5],[5,8,-6],[6,9,-8],[7,11,-9],[9,12,-11],[10,15,-13],[12,17,-15],[14,20,-18],[17,25,-21]],8217:[[2,3,-2],[3,4,-2],[3,4,-4],[4,4,-4],[4,5,-4],[5,7,-5],[6,8,-6],[7,9,-8],[8,11,-9],[9,13,-10],[11,15,-13],[13,17,-15],[15,20,-18],[18,25,-21]],8220:[[4,3,-2],[5,3,-3],[6,4,-4],[7,4,-4],[8,5,-4],[10,7,-5],[11,8,-6],[14,9,-8],[16,11,-9],[19,12,-11],[23,15,-13],[27,17,-15],[32,20,-18],[38,25,-21]],8221:[[4,3,-2],[5,4,-2],[5,4,-4],[6,4,-4],[7,5,-4],[9,7,-5],[10,8,-6],[12,9,-8],[14,11,-9],[17,13,-10],[20,15,-13],[23,17,-15],[28,20,-18],[33,25,-21]],8224:[[4,6,1],[4,8,2],[5,10,2],[6,10,2],[7,12,3],[8,15,3],[9,18,4],[11,22,5],[13,26,6],[15,29,6],[18,36,8],[21,41,9],[25,49,11],[30,61,14]],8225:[[4,6,1],[4,8,2],[5,10,2],[6,10,2],[7,12,3],[8,15,3],[9,18,4],[11,22,5],[13,26,6],[15,29,6],[18,36,8],[21,41,9],[25,49,11],[29,59,13]],8230:[[9,2,0],[11,2,0],[12,2,0],[15,2,0],[17,3,0],[21,4,0],[24,4,0],[29,5,0],[34,5,0],[41,6,0],[48,7,0],[57,8,0],[68,10,0],[81,12,0]],8242:[[3,4,0],[3,5,0],[4,6,0],[4,6,0],[5,7,0],[6,10,-1],[7,11,-1],[8,13,-1],[10,15,-1],[11,18,-1],[13,21,-1],[16,25,-2],[19,30,-2],[22,35,-2]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Main/Bold"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/GeneralPunctuation.js");
| mayur404/cdnjs | ajax/libs/mathjax/2.4.0/fonts/HTML-CSS/TeX/png/Main/Bold/GeneralPunctuation.js | JavaScript | mit | 2,893 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/CombDiacritMarks.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({"MathJax_Main-bold":{768:[[3,2,-3],[3,2,-4],[3,3,-5],[4,3,-5],[4,3,-6],[5,4,-8],[5,5,-9],[6,5,-12],[7,6,-14],[9,7,-16],[10,9,-19],[11,10,-23],[13,12,-27],[16,14,-33]],769:[[3,2,-3],[3,2,-4],[3,3,-5],[3,3,-5],[4,3,-6],[5,4,-8],[5,5,-9],[6,5,-12],[7,6,-14],[9,7,-16],[10,9,-19],[11,10,-23],[13,12,-27],[16,14,-33]],770:[[4,2,-3],[3,2,-5],[4,2,-6],[5,2,-6],[6,3,-7],[6,4,-9],[7,4,-10],[9,5,-13],[10,5,-15],[11,6,-17],[14,7,-21],[16,9,-24],[18,10,-29],[22,12,-35]],771:[[4,1,-4],[4,1,-5],[5,3,-6],[5,3,-6],[6,4,-6],[7,4,-9],[9,4,-11],[10,5,-13],[12,5,-16],[13,6,-18],[16,7,-22],[19,8,-25],[22,9,-30],[26,11,-36]],772:[[4,1,-3],[5,1,-5],[5,1,-6],[6,1,-6],[6,1,-7],[8,2,-9],[9,3,-10],[11,2,-13],[12,2,-16],[15,3,-18],[17,3,-22],[20,4,-25],[24,4,-30],[28,5,-36]],774:[[4,2,-3],[4,2,-4],[4,2,-6],[5,2,-6],[6,3,-6],[7,4,-8],[8,4,-10],[9,5,-12],[12,6,-14],[13,7,-16],[15,8,-20],[18,9,-23],[22,11,-27],[26,13,-33]],775:[[2,2,-3],[3,2,-4],[3,2,-6],[3,2,-6],[4,3,-6],[4,3,-9],[5,4,-10],[5,5,-12],[6,5,-15],[7,6,-17],[8,7,-21],[9,8,-24],[10,10,-28],[12,12,-34]],776:[[4,2,-3],[4,2,-4],[5,2,-6],[5,2,-6],[6,3,-6],[7,3,-9],[9,4,-10],[10,4,-13],[12,5,-15],[13,6,-17],[16,7,-21],[19,8,-24],[22,9,-29],[26,11,-35]],778:[[2,1,-4],[3,2,-4],[4,2,-6],[4,2,-6],[4,2,-7],[5,3,-9],[6,3,-11],[7,4,-13],[8,6,-14],[9,6,-17],[11,7,-21],[13,8,-24],[15,9,-29],[18,11,-35]],779:[[4,2,-3],[4,2,-4],[5,3,-5],[6,3,-5],[6,3,-6],[7,4,-8],[8,5,-9],[10,5,-12],[11,6,-14],[13,7,-17],[15,9,-19],[18,10,-23],[21,12,-27],[25,14,-33]],780:[[4,1,-3],[3,2,-5],[4,2,-6],[5,2,-6],[6,3,-7],[6,3,-9],[7,4,-10],[8,4,-13],[10,5,-15],[11,6,-17],[13,6,-21],[15,7,-24],[18,9,-28],[22,10,-34]],824:[[5,6,1],[6,8,2],[7,10,2],[8,10,2],[9,12,3],[11,15,3],[12,18,4],[15,22,5],[17,26,6],[20,31,6],[23,37,8],[28,43,9],[33,51,12],[39,61,14]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Main/Bold"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/CombDiacritMarks.js");
| icco/cdnjs | ajax/libs/mathjax/2.2/fonts/HTML-CSS/TeX/png/Main/Bold/CombDiacritMarks.js | JavaScript | mit | 2,359 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/MathOperators.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({"MathJax_Main-bold":{8704:[[6,5,0],[7,7,1],[8,8,1],[9,10,1],[10,10,0],[12,13,1],[14,15,1],[16,18,1],[19,21,1],[23,25,1],[26,28,1],[31,34,1],[37,40,1],[44,48,2]],8706:[[5,5,0],[6,6,0],[7,7,0],[8,9,0],[10,11,1],[11,13,1],[13,15,1],[16,18,1],[19,21,1],[22,25,1],[26,29,1],[31,34,1],[37,41,1],[44,49,2]],8707:[[4,5,0],[5,6,0],[6,7,0],[7,8,0],[8,10,0],[10,12,0],[12,14,0],[14,17,0],[16,20,0],[19,23,0],[23,28,0],[27,33,0],[32,39,0],[38,46,0]],8709:[[4,7,1],[5,8,1],[6,9,1],[7,11,1],[8,12,1],[9,15,2],[11,17,2],[13,20,2],[15,25,3],[18,29,3],[21,35,4],[25,40,4],[30,48,5],[35,56,5]],8711:[[7,5,0],[8,6,0],[9,8,1],[11,10,1],[13,11,1],[15,13,1],[18,15,1],[21,17,1],[25,20,1],[30,24,1],[36,28,1],[42,34,2],[50,40,2],[60,48,2]],8712:[[5,5,1],[6,6,1],[7,7,1],[8,8,1],[10,9,1],[12,12,2],[14,14,2],[16,16,2],[19,20,3],[23,23,3],[27,27,4],[31,32,4],[38,38,5],[44,45,6]],8713:[[5,7,2],[6,8,2],[7,10,3],[8,12,3],[10,13,3],[12,16,4],[13,19,5],[16,22,5],[19,26,6],[22,31,7],[27,37,9],[31,43,10],[37,51,12],[44,62,15]],8715:[[5,5,1],[6,6,1],[7,7,1],[8,8,1],[10,9,1],[12,12,2],[14,14,2],[16,16,2],[19,20,3],[23,23,3],[27,27,4],[32,32,4],[37,38,5],[45,45,6]],8722:[[6,1,-1],[7,1,-2],[8,1,-2],[10,2,-2],[12,1,-3],[14,2,-3],[16,2,-4],[19,2,-5],[23,2,-6],[27,3,-7],[32,3,-8],[38,4,-10],[45,4,-12],[53,5,-14]],8723:[[6,6,2],[7,7,2],[9,9,3],[10,10,3],[12,11,3],[14,13,4],[17,16,5],[20,19,6],[23,22,7],[28,26,8],[33,31,9],[39,36,11],[46,43,13],[55,52,16]],8725:[[4,8,2],[5,10,3],[5,11,3],[6,12,3],[8,15,4],[9,18,5],[10,20,5],[12,24,6],[15,28,7],[17,34,9],[20,40,10],[24,47,12],[29,56,14],[34,67,17]],8726:[[4,8,2],[5,10,3],[5,11,3],[6,12,3],[8,15,4],[9,18,5],[10,20,5],[12,24,6],[15,28,7],[17,34,9],[20,40,10],[24,47,12],[29,56,14],[34,67,17]],8727:[[4,4,0],[5,4,0],[5,5,0],[6,6,0],[7,7,0],[9,8,0],[10,10,0],[12,11,0],[14,14,0],[17,16,0],[20,18,-1],[24,21,-1],[28,26,-1],[33,31,-1]],8728:[[4,4,0],[4,4,0],[5,5,0],[6,6,0],[8,7,0],[9,8,0],[10,10,0],[12,11,0],[15,14,0],[17,16,0],[20,18,-1],[24,22,-1],[29,26,-1],[34,31,-1]],8729:[[4,4,0],[5,4,0],[5,5,0],[6,6,0],[8,7,0],[9,8,0],[10,10,0],[12,11,0],[15,14,0],[17,16,0],[20,18,-1],[24,22,-1],[29,26,-1],[34,31,-1]],8730:[[7,8,2],[9,9,2],[10,11,2],[12,13,3],[14,15,3],[17,17,3],[20,20,4],[24,25,5],[28,28,5],[33,33,6],[39,41,8],[47,48,9],[55,56,10],[66,66,12]],8733:[[6,3,0],[7,4,0],[9,5,0],[10,7,1],[12,8,1],[14,9,1],[17,10,1],[20,12,1],[24,14,1],[28,16,1],[33,19,1],[39,22,1],[47,26,1],[55,31,1]],8734:[[8,3,0],[9,4,0],[11,6,1],[13,7,1],[15,8,1],[18,9,1],[22,10,1],[26,12,1],[30,14,1],[36,16,1],[43,19,1],[51,22,1],[61,26,1],[72,31,1]],8736:[[5,5,0],[6,6,0],[7,7,0],[8,9,0],[10,10,0],[12,12,0],[14,14,0],[16,17,0],[19,20,0],[23,24,0],[27,28,0],[32,33,0],[38,40,0],[45,47,0]],8739:[[2,8,2],[2,10,3],[2,11,3],[3,12,3],[3,15,4],[4,18,5],[4,20,5],[5,24,6],[6,28,7],[7,34,9],[8,40,10],[9,47,12],[11,56,14],[13,67,17]],8741:[[3,8,2],[4,10,3],[5,11,3],[6,12,3],[6,15,4],[7,18,5],[9,20,5],[11,24,6],[12,28,7],[15,34,9],[17,40,10],[21,47,12],[24,56,14],[29,67,17]],8743:[[5,6,1],[6,7,1],[7,7,1],[9,9,1],[10,10,1],[12,12,1],[14,13,1],[17,16,1],[20,18,1],[24,21,1],[28,25,1],[33,30,1],[39,35,1],[47,42,2]],8744:[[5,6,1],[6,7,1],[7,7,1],[9,9,1],[10,10,1],[12,12,1],[14,13,1],[17,16,1],[20,18,1],[24,21,1],[28,25,1],[33,30,1],[39,35,1],[47,42,2]],8745:[[5,5,1],[6,6,1],[7,7,1],[9,8,1],[10,10,1],[12,11,1],[14,13,1],[17,15,1],[20,18,1],[24,21,1],[28,25,1],[33,30,1],[39,35,1],[47,41,1]],8746:[[5,5,0],[6,6,0],[7,7,0],[9,8,0],[10,9,0],[12,12,1],[14,13,1],[17,16,1],[20,18,1],[24,21,1],[28,25,1],[33,30,1],[39,35,1],[47,42,2]],8747:[[5,7,2],[6,8,2],[7,10,3],[8,12,3],[9,13,3],[11,16,4],[13,19,5],[15,22,5],[18,26,6],[21,31,7],[25,37,9],[30,43,10],[35,52,12],[42,61,14]],8764:[[6,3,0],[7,3,-1],[8,3,-1],[10,4,-1],[12,5,-1],[14,6,-1],[17,6,-2],[20,8,-2],[23,8,-3],[28,10,-3],[33,12,-4],[39,14,-5],[46,16,-6],[55,19,-7]],8768:[[2,5,1],[2,6,1],[3,7,1],[3,8,1],[4,9,1],[5,12,2],[5,14,2],[6,16,2],[8,20,3],[9,23,3],[10,27,4],[12,32,4],[15,38,5],[17,45,6]],8771:[[6,4,0],[7,4,0],[9,5,0],[10,6,0],[12,7,0],[14,10,1],[17,11,1],[20,13,1],[23,15,1],[28,18,1],[33,21,1],[39,25,1],[46,29,1],[55,35,1]],8773:[[6,5,0],[7,6,0],[9,8,1],[10,9,1],[12,10,1],[14,12,1],[17,14,1],[20,16,1],[23,19,1],[28,22,1],[33,27,2],[39,32,2],[46,38,2],[55,44,2]],8776:[[6,4,0],[7,5,0],[8,5,0],[10,7,0],[12,8,0],[14,9,0],[17,11,0],[20,13,0],[23,15,0],[28,17,-1],[33,20,-1],[39,24,-1],[46,28,-1],[55,33,-2]],8781:[[6,5,1],[7,6,1],[9,7,1],[10,8,1],[12,9,1],[14,10,1],[17,12,1],[20,14,1],[23,16,1],[28,20,2],[33,23,2],[39,27,2],[46,32,2],[55,39,3]],8784:[[6,5,0],[7,5,-1],[9,7,-1],[10,8,-1],[12,9,-1],[14,11,-1],[17,13,-2],[20,15,-2],[23,17,-3],[28,21,-3],[33,25,-4],[39,29,-5],[46,34,-6],[55,41,-7]],8800:[[6,7,2],[7,9,2],[9,10,3],[10,12,3],[12,14,4],[14,16,4],[17,20,5],[20,22,5],[23,26,6],[28,31,7],[33,37,9],[39,43,10],[46,51,12],[55,61,14]],8801:[[6,4,0],[7,4,0],[9,5,0],[10,6,0],[12,7,0],[14,10,1],[17,11,1],[20,13,1],[23,15,1],[28,18,1],[33,21,1],[39,25,1],[46,29,1],[55,35,1]],8804:[[6,7,2],[7,8,2],[8,9,2],[10,12,3],[12,13,3],[14,16,4],[16,18,4],[19,22,5],[23,26,6],[27,30,7],[32,36,8],[38,43,10],[45,50,11],[53,60,14]],8805:[[6,7,2],[7,8,2],[8,9,2],[10,12,3],[12,13,3],[14,16,4],[16,18,4],[19,22,5],[23,26,6],[27,30,7],[32,36,8],[38,43,10],[45,50,11],[53,60,14]],8810:[[8,6,1],[9,7,1],[11,9,2],[13,10,2],[15,11,2],[18,13,2],[22,16,3],[26,18,3],[30,22,4],[36,25,4],[43,30,5],[51,35,6],[60,42,7],[72,49,8]],8811:[[8,6,1],[10,7,1],[11,9,2],[13,10,2],[16,11,2],[19,13,2],[22,16,3],[26,18,3],[31,22,4],[36,25,4],[43,30,5],[51,35,6],[61,42,7],[72,49,8]],8826:[[6,6,1],[7,6,1],[8,7,1],[10,8,1],[12,11,2],[14,12,2],[16,14,2],[19,16,2],[23,20,3],[27,23,3],[32,27,4],[38,32,4],[45,38,5],[53,45,6]],8827:[[6,6,1],[7,6,1],[8,7,1],[10,9,2],[11,11,2],[14,12,2],[16,14,2],[19,16,2],[22,20,3],[27,23,3],[32,27,4],[37,32,4],[44,38,5],[53,45,6]],8834:[[6,5,1],[7,6,1],[8,7,1],[10,8,1],[12,9,1],[14,12,2],[16,14,2],[19,16,2],[23,20,3],[27,23,3],[32,27,4],[37,32,4],[45,38,5],[53,45,6]],8835:[[6,6,1],[7,6,1],[8,7,1],[10,8,1],[12,10,1],[14,12,2],[16,14,2],[19,16,2],[23,20,3],[27,23,3],[32,27,4],[38,32,4],[45,38,5],[53,45,6]],8838:[[6,7,2],[7,8,2],[8,9,2],[10,12,3],[12,13,3],[14,16,4],[16,18,4],[19,22,5],[23,26,6],[27,30,7],[32,36,8],[37,43,10],[45,50,11],[53,60,14]],8839:[[6,7,2],[7,8,2],[8,9,2],[10,12,3],[11,13,3],[14,16,4],[16,18,4],[19,22,5],[23,26,6],[27,30,7],[32,36,8],[38,43,10],[44,50,11],[53,60,14]],8846:[[5,5,0],[6,6,0],[7,6,0],[9,8,0],[10,9,0],[12,12,1],[14,13,1],[17,16,1],[20,18,1],[24,21,1],[28,25,1],[33,29,1],[39,35,1],[47,42,2]],8849:[[6,7,2],[7,8,2],[9,9,2],[10,12,3],[12,13,3],[14,16,4],[17,18,4],[20,22,5],[23,26,6],[28,30,7],[33,36,8],[39,43,10],[46,50,11],[55,60,14]],8850:[[6,7,2],[7,8,2],[8,9,2],[10,12,3],[12,13,3],[14,16,4],[16,18,4],[19,22,5],[23,26,6],[27,30,7],[32,36,8],[38,43,10],[45,50,11],[53,60,14]],8851:[[5,5,1],[6,5,0],[7,6,0],[9,8,1],[10,10,1],[12,11,0],[14,12,0],[17,15,0],[20,17,0],[23,20,0],[28,25,1],[33,29,0],[39,34,0],[47,40,0]],8852:[[5,5,0],[6,6,0],[7,6,0],[9,8,0],[10,9,0],[12,11,0],[14,12,0],[17,15,0],[20,17,0],[23,20,0],[28,24,0],[33,29,0],[39,34,0],[47,40,0]],8853:[[7,6,1],[7,7,1],[8,8,2],[10,10,2],[12,11,2],[14,14,3],[17,16,3],[20,19,4],[23,22,4],[28,26,5],[33,31,6],[39,37,7],[46,43,8],[55,51,9]],8854:[[6,6,1],[7,7,1],[9,8,2],[10,10,2],[12,11,2],[14,14,3],[17,16,3],[20,19,4],[23,22,4],[28,26,5],[33,31,6],[39,37,7],[46,43,8],[55,51,9]],8855:[[6,6,1],[7,7,1],[8,8,2],[10,10,2],[12,11,2],[14,14,3],[17,16,3],[20,19,4],[23,22,4],[28,26,5],[33,31,6],[39,37,7],[46,43,8],[55,51,9]],8856:[[6,6,1],[7,7,1],[8,8,2],[10,10,2],[12,11,2],[14,14,3],[17,16,3],[20,19,4],[23,22,4],[28,26,5],[33,31,6],[39,37,7],[46,43,8],[55,51,9]],8857:[[6,6,1],[7,7,1],[8,8,2],[10,10,2],[12,11,2],[14,14,3],[17,16,3],[20,19,4],[23,22,4],[28,26,5],[33,31,6],[39,37,7],[46,43,8],[55,51,9]],8866:[[5,5,0],[6,6,0],[7,7,0],[8,9,0],[9,10,0],[11,12,0],[13,14,0],[15,17,0],[18,20,0],[21,23,0],[25,28,0],[30,33,0],[36,39,0],[42,46,0]],8867:[[5,5,0],[6,6,0],[7,7,0],[8,9,0],[9,10,0],[11,12,0],[13,14,0],[15,17,0],[18,20,0],[21,23,0],[25,28,0],[30,33,0],[36,39,0],[42,46,0]],8868:[[6,5,0],[7,6,0],[9,7,0],[10,10,1],[12,10,0],[14,13,1],[17,15,1],[20,17,0],[23,21,1],[28,23,0],[33,28,0],[39,34,1],[46,39,0],[55,46,0]],8869:[[6,5,0],[7,6,0],[9,7,0],[10,9,0],[12,10,0],[14,12,0],[17,14,0],[20,17,0],[23,20,0],[28,23,0],[33,28,0],[39,33,0],[46,39,0],[55,46,0]],8872:[[7,8,2],[8,10,3],[10,11,3],[11,12,3],[13,15,4],[16,18,5],[19,20,5],[22,24,6],[26,28,7],[31,34,9],[36,40,10],[43,47,12],[51,56,14],[61,67,17]],8900:[[4,5,1],[5,6,1],[6,7,1],[7,8,1],[8,9,1],[10,10,1],[11,12,1],[14,14,1],[16,16,1],[19,19,1],[22,22,1],[27,26,1],[32,31,2],[37,37,2]],8901:[[2,2,-1],[3,2,-1],[3,3,-1],[3,3,-1],[4,3,-2],[5,4,-2],[5,4,-3],[6,5,-3],[7,6,-4],[9,7,-5],[10,8,-6],[12,9,-7],[14,10,-9],[17,13,-10]],8902:[[4,4,0],[5,5,0],[6,5,0],[7,6,0],[8,7,0],[10,9,0],[11,10,0],[13,12,0],[16,14,0],[19,17,0],[22,20,0],[26,24,0],[31,28,0],[37,34,0]],8904:[[7,5,1],[8,6,1],[10,7,1],[12,8,1],[13,9,1],[17,10,1],[19,12,1],[23,14,1],[27,17,2],[32,20,2],[38,24,2],[45,28,2],[54,33,3],[64,39,3]],8942:[[2,8,1],[3,9,1],[3,11,1],[3,13,1],[4,15,1],[5,17,1],[5,20,1],[6,24,1],[7,28,1],[9,33,1],[10,40,2],[12,47,2],[14,55,2],[17,65,2]],8943:[[9,2,-1],[11,2,-1],[13,3,-1],[15,3,-1],[17,3,-2],[21,4,-2],[24,4,-3],[29,5,-3],[34,6,-4],[41,7,-5],[48,8,-6],[57,9,-7],[68,10,-9],[81,13,-10]],8945:[[9,7,0],[10,8,0],[12,9,0],[15,10,-1],[17,12,-1],[20,14,-1],[24,16,-1],[28,19,-2],[33,23,-2],[40,26,-3],[47,32,-3],[56,37,-4],[67,44,-5],[79,52,-6]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Main/Bold"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/MathOperators.js");
| hare1039/cdnjs | ajax/libs/mathjax/2.7.0-beta.0/fonts/HTML-CSS/TeX/png/Main/Bold/MathOperators.js | JavaScript | mit | 10,049 |
/*
* /MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/Arrows.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({"MathJax_Main-bold":{8592:[[8,5,1],[9,5,0],[11,7,1],[13,7,1],[15,9,1],[18,10,1],[22,11,1],[26,13,1],[30,16,1],[36,18,1],[43,22,1],[51,25,1],[60,30,1],[72,36,2]],8593:[[5,7,2],[5,8,2],[6,9,2],[7,12,3],[9,13,3],[10,16,4],[11,18,4],[14,22,5],[16,26,6],[19,30,7],[22,36,8],[27,42,9],[31,50,11],[37,59,13]],8594:[[8,5,1],[9,5,0],[11,7,1],[13,7,1],[15,9,1],[18,10,1],[22,11,1],[26,13,1],[30,16,1],[36,18,1],[43,22,1],[51,26,1],[60,30,1],[72,36,1]],8595:[[5,7,2],[5,8,2],[6,9,2],[7,12,3],[9,13,3],[10,16,4],[11,18,4],[14,22,5],[16,26,6],[19,30,7],[22,36,8],[27,43,10],[31,50,11],[38,59,13]],8596:[[8,5,1],[9,5,0],[11,7,1],[13,7,1],[15,9,1],[18,10,1],[21,11,1],[26,13,1],[30,16,1],[36,18,1],[43,22,1],[51,25,1],[60,30,1],[71,36,2]],8597:[[5,8,2],[5,10,3],[6,11,3],[7,14,4],[9,15,4],[10,18,5],[11,21,6],[14,25,7],[16,30,8],[19,35,9],[22,42,11],[27,49,13],[31,58,15],[38,69,18]],8598:[[8,7,2],[9,9,2],[11,10,2],[13,12,3],[15,13,3],[18,17,4],[21,19,4],[26,22,5],[30,26,6],[36,31,7],[43,37,8],[51,43,9],[60,51,11],[72,61,13]],8599:[[8,8,2],[9,9,2],[11,10,2],[13,12,3],[15,13,3],[18,17,4],[22,19,4],[26,22,5],[30,26,6],[36,31,7],[43,37,8],[51,43,9],[60,52,11],[72,62,13]],8600:[[8,7,2],[9,9,3],[11,10,3],[13,12,3],[15,13,3],[18,16,4],[22,19,5],[26,23,6],[30,27,7],[36,31,8],[43,37,9],[51,44,11],[60,52,13],[72,61,15]],8601:[[8,7,2],[9,9,3],[11,10,3],[13,12,3],[15,13,3],[18,16,4],[22,19,5],[26,23,6],[30,26,6],[36,31,8],[43,37,9],[51,44,11],[60,52,13],[72,61,15]],8614:[[8,5,1],[9,5,0],[11,7,1],[13,7,1],[15,9,1],[18,9,0],[21,11,1],[26,14,1],[30,16,1],[36,18,1],[43,22,1],[51,26,1],[60,30,1],[71,36,1]],8617:[[9,5,1],[10,5,0],[12,7,1],[15,7,1],[17,9,1],[21,10,1],[24,11,1],[29,13,1],[34,16,1],[40,18,1],[48,22,1],[57,25,1],[68,30,1],[80,36,2]],8618:[[9,5,1],[11,5,0],[12,7,1],[15,7,1],[17,9,1],[21,10,1],[24,11,1],[29,14,1],[34,16,1],[40,19,1],[48,22,1],[57,26,1],[68,30,1],[80,36,1]],8636:[[8,3,-1],[9,3,-2],[11,4,-2],[13,4,-2],[15,5,-3],[18,6,-3],[22,6,-4],[26,7,-5],[30,9,-6],[36,10,-7],[43,13,-8],[51,15,-10],[60,17,-12],[72,20,-14]],8637:[[8,3,1],[9,3,0],[11,4,1],[13,5,1],[15,5,1],[18,6,1],[22,7,1],[26,8,1],[30,9,1],[36,11,1],[43,12,1],[51,15,1],[60,18,2],[72,21,2]],8640:[[8,3,-1],[9,3,-2],[11,4,-2],[13,4,-2],[15,5,-3],[18,6,-3],[22,6,-4],[26,7,-5],[30,9,-6],[36,10,-7],[43,13,-8],[51,15,-10],[60,17,-12],[72,20,-14]],8641:[[8,3,1],[9,3,0],[11,4,1],[13,5,1],[15,5,1],[18,6,1],[22,7,1],[26,8,1],[30,9,1],[36,11,1],[43,12,1],[51,15,1],[60,18,2],[72,21,2]],8652:[[8,7,1],[9,6,0],[11,9,1],[13,10,1],[15,12,1],[18,13,1],[22,15,1],[26,18,1],[30,21,1],[36,25,1],[43,30,1],[51,35,1],[60,42,2],[72,50,2]],8656:[[8,5,1],[9,6,1],[11,7,1],[13,8,1],[15,9,1],[18,11,1],[22,13,1],[26,15,2],[30,18,2],[36,21,2],[43,24,2],[51,29,3],[60,34,3],[72,41,4]],8657:[[5,7,2],[6,8,2],[7,9,2],[8,12,3],[10,13,3],[12,16,4],[13,18,4],[16,22,5],[19,26,6],[22,30,7],[26,36,8],[32,42,9],[37,50,11],[44,59,13]],8658:[[8,5,1],[9,6,1],[11,7,1],[13,8,1],[15,9,1],[18,11,1],[22,12,1],[26,14,1],[30,18,2],[36,21,2],[43,24,2],[51,28,2],[60,34,3],[72,40,3]],8659:[[5,7,2],[6,8,2],[7,9,2],[8,12,3],[10,13,3],[12,16,4],[14,18,4],[16,22,5],[19,26,6],[23,30,7],[27,36,8],[32,43,10],[38,50,11],[45,59,13]],8660:[[8,5,1],[10,6,1],[11,7,1],[13,8,1],[16,9,1],[19,11,1],[22,12,1],[26,15,2],[31,18,2],[37,21,2],[44,24,2],[52,29,3],[61,34,3],[73,41,4]],8661:[[5,8,2],[6,10,3],[7,11,3],[8,13,4],[10,15,4],[11,18,5],[14,21,6],[16,25,7],[19,30,8],[22,35,9],[27,41,11],[32,49,13],[38,58,15],[45,69,18]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Main/Bold"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/Arrows.js");
| mival/cdnjs | ajax/libs/mathjax/2.2/fonts/HTML-CSS/TeX/png/Main/Bold/Arrows.js | JavaScript | mit | 4,005 |
/**
* editable_selects.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
var TinyMCE_EditableSelects = {
editSelectElm : null,
init : function() {
var nl = document.getElementsByTagName("select"), i, d = document, o;
for (i=0; i<nl.length; i++) {
if (nl[i].className.indexOf('mceEditableSelect') != -1) {
o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__');
o.className = 'mceAddSelectValue';
nl[i].options[nl[i].options.length] = o;
nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect;
}
}
},
onChangeEditableSelect : function(e) {
var d = document, ne, se = window.event ? window.event.srcElement : e.target;
if (se.options[se.selectedIndex].value == '__mce_add_custom__') {
ne = d.createElement("input");
ne.id = se.id + "_custom";
ne.name = se.name + "_custom";
ne.type = "text";
ne.style.width = se.offsetWidth + 'px';
se.parentNode.insertBefore(ne, se);
se.style.display = 'none';
ne.focus();
ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput;
ne.onkeydown = TinyMCE_EditableSelects.onKeyDown;
TinyMCE_EditableSelects.editSelectElm = se;
}
},
onBlurEditableSelectInput : function() {
var se = TinyMCE_EditableSelects.editSelectElm;
if (se) {
if (se.previousSibling.value != '') {
addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value);
selectByValue(document.forms[0], se.id, se.previousSibling.value);
} else
selectByValue(document.forms[0], se.id, '');
se.style.display = 'inline';
se.parentNode.removeChild(se.previousSibling);
TinyMCE_EditableSelects.editSelectElm = null;
}
},
onKeyDown : function(e) {
e = e || window.event;
if (e.keyCode == 13)
TinyMCE_EditableSelects.onBlurEditableSelectInput();
}
};
| moay/jsdelivr | files/wordpress/3.6.1/js/tinymce/utils/editable_selects.js | JavaScript | mit | 1,976 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.