Last active
March 17, 2021 11:01
-
-
Save abernier/d773d6efc9640e3600ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mk |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.CSS3DObject = function ( element ) { | |
THREE.Object3D.call( this ); | |
this.element = element; | |
this.element.style.position = 'absolute'; | |
this.addEventListener( 'removed', function ( event ) { | |
if ( this.element.parentNode !== null ) { | |
this.element.parentNode.removeChild( this.element ); | |
} | |
} ); | |
}; | |
THREE.CSS3DObject.prototype = Object.create( THREE.Object3D.prototype ); | |
THREE.CSS3DSprite = function ( element ) { | |
THREE.CSS3DObject.call( this, element ); | |
}; | |
THREE.CSS3DSprite.prototype = Object.create( THREE.CSS3DObject.prototype ); | |
// | |
THREE.CSS3DRenderer = function (domElement, cameraElement) { | |
console.log( 'THREE.CSS3DRenderer', THREE.REVISION ); | |
var _width, _height; | |
var _widthHalf, _heightHalf; | |
var matrix = new THREE.Matrix4(); | |
var cache = { | |
camera: { fov: 0, style: '' }, | |
objects: {} | |
}; | |
var domElement = domElement || document.createElement( 'div' ); | |
this.domElement = domElement; | |
domElement.style.overflow = 'hidden'; | |
domElement.style.WebkitTransformStyle = 'preserve-3d'; | |
domElement.style.MozTransformStyle = 'preserve-3d'; | |
domElement.style.oTransformStyle = 'preserve-3d'; | |
domElement.style.transformStyle = 'preserve-3d'; | |
var cameraElement = cameraElement || document.createElement( 'div' ) && domElement.appendChild(cameraElement); | |
cameraElement.style.WebkitTransformStyle = 'preserve-3d'; | |
cameraElement.style.MozTransformStyle = 'preserve-3d'; | |
cameraElement.style.oTransformStyle = 'preserve-3d'; | |
cameraElement.style.transformStyle = 'preserve-3d'; | |
this.setClearColor = function () { | |
}; | |
this.setSize = function ( width, height ) { | |
_width = width; | |
_height = height; | |
_widthHalf = _width / 2; | |
_heightHalf = _height / 2; | |
domElement.style.width = width + 'px'; | |
domElement.style.height = height + 'px'; | |
cameraElement.style.width = width + 'px'; | |
cameraElement.style.height = height + 'px'; | |
}; | |
var epsilon = function ( value ) { | |
return Math.abs( value ) < 0.000001 ? 0 : value; | |
}; | |
var getCameraCSSMatrix = function ( matrix ) { | |
var elements = matrix.elements; | |
return 'matrix3d(' + | |
epsilon( elements[ 0 ] ) + ',' + | |
epsilon( - elements[ 1 ] ) + ',' + | |
epsilon( elements[ 2 ] ) + ',' + | |
epsilon( elements[ 3 ] ) + ',' + | |
epsilon( elements[ 4 ] ) + ',' + | |
epsilon( - elements[ 5 ] ) + ',' + | |
epsilon( elements[ 6 ] ) + ',' + | |
epsilon( elements[ 7 ] ) + ',' + | |
epsilon( elements[ 8 ] ) + ',' + | |
epsilon( - elements[ 9 ] ) + ',' + | |
epsilon( elements[ 10 ] ) + ',' + | |
epsilon( elements[ 11 ] ) + ',' + | |
epsilon( elements[ 12 ] ) + ',' + | |
epsilon( - elements[ 13 ] ) + ',' + | |
epsilon( elements[ 14 ] ) + ',' + | |
epsilon( elements[ 15 ] ) + | |
')'; | |
}; | |
var getObjectCSSMatrix = function ( matrix ) { | |
var elements = matrix.elements; | |
return 'translate3d(-50%,-50%,0) matrix3d(' + | |
epsilon( elements[ 0 ] ) + ',' + | |
epsilon( elements[ 1 ] ) + ',' + | |
epsilon( elements[ 2 ] ) + ',' + | |
epsilon( elements[ 3 ] ) + ',' + | |
epsilon( - elements[ 4 ] ) + ',' + | |
epsilon( - elements[ 5 ] ) + ',' + | |
epsilon( - elements[ 6 ] ) + ',' + | |
epsilon( - elements[ 7 ] ) + ',' + | |
epsilon( elements[ 8 ] ) + ',' + | |
epsilon( elements[ 9 ] ) + ',' + | |
epsilon( elements[ 10 ] ) + ',' + | |
epsilon( elements[ 11 ] ) + ',' + | |
epsilon( elements[ 12 ] ) + ',' + | |
epsilon( elements[ 13 ] ) + ',' + | |
epsilon( elements[ 14 ] ) + ',' + | |
epsilon( elements[ 15 ] ) + | |
')'; | |
}; | |
var renderObject = function ( object, camera ) { | |
if ( object instanceof THREE.CSS3DObject ) { | |
var style; | |
if ( object instanceof THREE.CSS3DSprite ) { | |
// http://swiftcoder.wordpress.com/2008/11/25/constructing-a-billboard-matrix/ | |
matrix.copy( camera.matrixWorldInverse ); | |
matrix.transpose(); | |
matrix.copyPosition( object.matrixWorld ); | |
matrix.scale( object.scale ); | |
matrix.elements[ 3 ] = 0; | |
matrix.elements[ 7 ] = 0; | |
matrix.elements[ 11 ] = 0; | |
matrix.elements[ 15 ] = 1; | |
style = getObjectCSSMatrix( matrix ); | |
} else { | |
style = getObjectCSSMatrix( object.matrixWorld ); | |
} | |
var element = object.element; | |
var cachedStyle = cache.objects[ object.id ]; | |
if ( cachedStyle === undefined || cachedStyle !== style ) { | |
element.style.WebkitTransform = style; | |
element.style.MozTransform = style; | |
element.style.oTransform = style; | |
element.style.transform = style; | |
cache.objects[ object.id ] = style; | |
} | |
if ( element.parentNode !== cameraElement ) { | |
cameraElement.appendChild( element ); | |
} | |
} | |
for ( var i = 0, l = object.children.length; i < l; i ++ ) { | |
renderObject( object.children[ i ], camera ); | |
} | |
}; | |
this.render = function ( scene, camera ) { | |
var fov = 0.5 / Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * _height; | |
if ( cache.camera.fov !== fov ) { | |
domElement.style.WebkitPerspective = fov + "px"; | |
domElement.style.MozPerspective = fov + "px"; | |
domElement.style.oPerspective = fov + "px"; | |
domElement.style.perspective = fov + "px"; | |
cache.camera.fov = fov; | |
} | |
scene.updateMatrixWorld(); | |
if ( camera.parent === undefined ) camera.updateMatrixWorld(); | |
camera.matrixWorldInverse.getInverse( camera.matrixWorld ); | |
var style = "translate3d(0,0," + fov + "px)" + getCameraCSSMatrix( camera.matrixWorldInverse ) + | |
" translate3d(" + _widthHalf + "px," + _heightHalf + "px, 0)"; | |
if ( cache.camera.style !== style ) { | |
cameraElement.style.WebkitTransform = style; | |
cameraElement.style.MozTransform = style; | |
cameraElement.style.oTransform = style; | |
cameraElement.style.transform = style; | |
cache.camera.style = style; | |
} | |
renderObject( scene, camera ); | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* dat-gui JavaScript Controller Library | |
* http://code.google.com/p/dat-gui | |
* | |
* Copyright 2011 Data Arts Team, Google Creative Lab | |
* | |
* 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 | |
*/ | |
/** @namespace */ | |
var dat = dat || {}; | |
/** @namespace */ | |
dat.gui = dat.gui || {}; | |
/** @namespace */ | |
dat.utils = dat.utils || {}; | |
/** @namespace */ | |
dat.controllers = dat.controllers || {}; | |
/** @namespace */ | |
dat.dom = dat.dom || {}; | |
/** @namespace */ | |
dat.color = dat.color || {}; | |
dat.utils.css = (function () { | |
return { | |
load: function (url, doc) { | |
doc = doc || document; | |
var link = doc.createElement('link'); | |
link.type = 'text/css'; | |
link.rel = 'stylesheet'; | |
link.href = url; | |
doc.getElementsByTagName('head')[0].appendChild(link); | |
}, | |
inject: function(css, doc) { | |
doc = doc || document; | |
var injected = document.createElement('style'); | |
injected.type = 'text/css'; | |
injected.innerHTML = css; | |
doc.getElementsByTagName('head')[0].appendChild(injected); | |
} | |
} | |
})(); | |
dat.utils.common = (function () { | |
var ARR_EACH = Array.prototype.forEach; | |
var ARR_SLICE = Array.prototype.slice; | |
/** | |
* Band-aid methods for things that should be a lot easier in JavaScript. | |
* Implementation and structure inspired by underscore.js | |
* http://documentcloud.github.com/underscore/ | |
*/ | |
return { | |
BREAK: {}, | |
extend: function(target) { | |
this.each(ARR_SLICE.call(arguments, 1), function(obj) { | |
for (var key in obj) | |
if (!this.isUndefined(obj[key])) | |
target[key] = obj[key]; | |
}, this); | |
return target; | |
}, | |
defaults: function(target) { | |
this.each(ARR_SLICE.call(arguments, 1), function(obj) { | |
for (var key in obj) | |
if (this.isUndefined(target[key])) | |
target[key] = obj[key]; | |
}, this); | |
return target; | |
}, | |
compose: function() { | |
var toCall = ARR_SLICE.call(arguments); | |
return function() { | |
var args = ARR_SLICE.call(arguments); | |
for (var i = toCall.length -1; i >= 0; i--) { | |
args = [toCall[i].apply(this, args)]; | |
} | |
return args[0]; | |
} | |
}, | |
each: function(obj, itr, scope) { | |
if (!obj) return; | |
if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) { | |
obj.forEach(itr, scope); | |
} else if (obj.length === obj.length + 0) { // Is number but not NaN | |
for (var key = 0, l = obj.length; key < l; key++) | |
if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) | |
return; | |
} else { | |
for (var key in obj) | |
if (itr.call(scope, obj[key], key) === this.BREAK) | |
return; | |
} | |
}, | |
defer: function(fnc) { | |
setTimeout(fnc, 0); | |
}, | |
toArray: function(obj) { | |
if (obj.toArray) return obj.toArray(); | |
return ARR_SLICE.call(obj); | |
}, | |
isUndefined: function(obj) { | |
return obj === undefined; | |
}, | |
isNull: function(obj) { | |
return obj === null; | |
}, | |
isNaN: function(obj) { | |
return obj !== obj; | |
}, | |
isArray: Array.isArray || function(obj) { | |
return obj.constructor === Array; | |
}, | |
isObject: function(obj) { | |
return obj === Object(obj); | |
}, | |
isNumber: function(obj) { | |
return obj === obj+0; | |
}, | |
isString: function(obj) { | |
return obj === obj+''; | |
}, | |
isBoolean: function(obj) { | |
return obj === false || obj === true; | |
}, | |
isFunction: function(obj) { | |
return Object.prototype.toString.call(obj) === '[object Function]'; | |
} | |
}; | |
})(); | |
dat.controllers.Controller = (function (common) { | |
/** | |
* @class An "abstract" class that represents a given property of an object. | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* | |
* @member dat.controllers | |
*/ | |
var Controller = function(object, property) { | |
this.initialValue = object[property]; | |
/** | |
* Those who extend this class will put their DOM elements in here. | |
* @type {DOMElement} | |
*/ | |
this.domElement = document.createElement('div'); | |
/** | |
* The object to manipulate | |
* @type {Object} | |
*/ | |
this.object = object; | |
/** | |
* The name of the property to manipulate | |
* @type {String} | |
*/ | |
this.property = property; | |
/** | |
* The function to be called on change. | |
* @type {Function} | |
* @ignore | |
*/ | |
this.__onChange = undefined; | |
/** | |
* The function to be called on finishing change. | |
* @type {Function} | |
* @ignore | |
*/ | |
this.__onFinishChange = undefined; | |
}; | |
common.extend( | |
Controller.prototype, | |
/** @lends dat.controllers.Controller.prototype */ | |
{ | |
/** | |
* Specify that a function fire every time someone changes the value with | |
* this Controller. | |
* | |
* @param {Function} fnc This function will be called whenever the value | |
* is modified via this Controller. | |
* @returns {dat.controllers.Controller} this | |
*/ | |
onChange: function(fnc) { | |
this.__onChange = fnc; | |
return this; | |
}, | |
/** | |
* Specify that a function fire every time someone "finishes" changing | |
* the value wih this Controller. Useful for values that change | |
* incrementally like numbers or strings. | |
* | |
* @param {Function} fnc This function will be called whenever | |
* someone "finishes" changing the value via this Controller. | |
* @returns {dat.controllers.Controller} this | |
*/ | |
onFinishChange: function(fnc) { | |
this.__onFinishChange = fnc; | |
return this; | |
}, | |
/** | |
* Change the value of <code>object[property]</code> | |
* | |
* @param {Object} newValue The new value of <code>object[property]</code> | |
*/ | |
setValue: function(newValue) { | |
this.object[this.property] = newValue; | |
if (this.__onChange) { | |
this.__onChange.call(this, newValue); | |
} | |
this.updateDisplay(); | |
return this; | |
}, | |
/** | |
* Gets the value of <code>object[property]</code> | |
* | |
* @returns {Object} The current value of <code>object[property]</code> | |
*/ | |
getValue: function() { | |
return this.object[this.property]; | |
}, | |
/** | |
* Refreshes the visual display of a Controller in order to keep sync | |
* with the object's current value. | |
* @returns {dat.controllers.Controller} this | |
*/ | |
updateDisplay: function() { | |
return this; | |
}, | |
/** | |
* @returns {Boolean} true if the value has deviated from initialValue | |
*/ | |
isModified: function() { | |
return this.initialValue !== this.getValue() | |
} | |
} | |
); | |
return Controller; | |
})(dat.utils.common); | |
dat.dom.dom = (function (common) { | |
var EVENT_MAP = { | |
'HTMLEvents': ['change'], | |
'MouseEvents': ['click','mousemove','mousedown','mouseup', 'mouseover'], | |
'KeyboardEvents': ['keydown'] | |
}; | |
var EVENT_MAP_INV = {}; | |
common.each(EVENT_MAP, function(v, k) { | |
common.each(v, function(e) { | |
EVENT_MAP_INV[e] = k; | |
}); | |
}); | |
var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/; | |
function cssValueToPixels(val) { | |
if (val === '0' || common.isUndefined(val)) return 0; | |
var match = val.match(CSS_VALUE_PIXELS); | |
if (!common.isNull(match)) { | |
return parseFloat(match[1]); | |
} | |
// TODO ...ems? %? | |
return 0; | |
} | |
/** | |
* @namespace | |
* @member dat.dom | |
*/ | |
var dom = { | |
/** | |
* | |
* @param elem | |
* @param selectable | |
*/ | |
makeSelectable: function(elem, selectable) { | |
if (elem === undefined || elem.style === undefined) return; | |
elem.onselectstart = selectable ? function() { | |
return false; | |
} : function() { | |
}; | |
elem.style.MozUserSelect = selectable ? 'auto' : 'none'; | |
elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none'; | |
elem.unselectable = selectable ? 'on' : 'off'; | |
}, | |
/** | |
* | |
* @param elem | |
* @param horizontal | |
* @param vertical | |
*/ | |
makeFullscreen: function(elem, horizontal, vertical) { | |
if (common.isUndefined(horizontal)) horizontal = true; | |
if (common.isUndefined(vertical)) vertical = true; | |
elem.style.position = 'absolute'; | |
if (horizontal) { | |
elem.style.left = 0; | |
elem.style.right = 0; | |
} | |
if (vertical) { | |
elem.style.top = 0; | |
elem.style.bottom = 0; | |
} | |
}, | |
/** | |
* | |
* @param elem | |
* @param eventType | |
* @param params | |
*/ | |
fakeEvent: function(elem, eventType, params, aux) { | |
params = params || {}; | |
var className = EVENT_MAP_INV[eventType]; | |
if (!className) { | |
throw new Error('Event type ' + eventType + ' not supported.'); | |
} | |
var evt = document.createEvent(className); | |
switch (className) { | |
case 'MouseEvents': | |
var clientX = params.x || params.clientX || 0; | |
var clientY = params.y || params.clientY || 0; | |
evt.initMouseEvent(eventType, params.bubbles || false, | |
params.cancelable || true, window, params.clickCount || 1, | |
0, //screen X | |
0, //screen Y | |
clientX, //client X | |
clientY, //client Y | |
false, false, false, false, 0, null); | |
break; | |
case 'KeyboardEvents': | |
var init = evt.initKeyboardEvent || evt.initKeyEvent; // webkit || moz | |
common.defaults(params, { | |
cancelable: true, | |
ctrlKey: false, | |
altKey: false, | |
shiftKey: false, | |
metaKey: false, | |
keyCode: undefined, | |
charCode: undefined | |
}); | |
init(eventType, params.bubbles || false, | |
params.cancelable, window, | |
params.ctrlKey, params.altKey, | |
params.shiftKey, params.metaKey, | |
params.keyCode, params.charCode); | |
break; | |
default: | |
evt.initEvent(eventType, params.bubbles || false, | |
params.cancelable || true); | |
break; | |
} | |
common.defaults(evt, aux); | |
elem.dispatchEvent(evt); | |
}, | |
/** | |
* | |
* @param elem | |
* @param event | |
* @param func | |
* @param bool | |
*/ | |
bind: function(elem, event, func, bool) { | |
bool = bool || false; | |
if (elem.addEventListener) | |
elem.addEventListener(event, func, bool); | |
else if (elem.attachEvent) | |
elem.attachEvent('on' + event, func); | |
return dom; | |
}, | |
/** | |
* | |
* @param elem | |
* @param event | |
* @param func | |
* @param bool | |
*/ | |
unbind: function(elem, event, func, bool) { | |
bool = bool || false; | |
if (elem.removeEventListener) | |
elem.removeEventListener(event, func, bool); | |
else if (elem.detachEvent) | |
elem.detachEvent('on' + event, func); | |
return dom; | |
}, | |
/** | |
* | |
* @param elem | |
* @param className | |
*/ | |
addClass: function(elem, className) { | |
if (elem.className === undefined) { | |
elem.className = className; | |
} else if (elem.className !== className) { | |
var classes = elem.className.split(/ +/); | |
if (classes.indexOf(className) == -1) { | |
classes.push(className); | |
elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, ''); | |
} | |
} | |
return dom; | |
}, | |
/** | |
* | |
* @param elem | |
* @param className | |
*/ | |
removeClass: function(elem, className) { | |
if (className) { | |
if (elem.className === undefined) { | |
// elem.className = className; | |
} else if (elem.className === className) { | |
elem.removeAttribute('class'); | |
} else { | |
var classes = elem.className.split(/ +/); | |
var index = classes.indexOf(className); | |
if (index != -1) { | |
classes.splice(index, 1); | |
elem.className = classes.join(' '); | |
} | |
} | |
} else { | |
elem.className = undefined; | |
} | |
return dom; | |
}, | |
hasClass: function(elem, className) { | |
return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false; | |
}, | |
/** | |
* | |
* @param elem | |
*/ | |
getWidth: function(elem) { | |
var style = getComputedStyle(elem); | |
return cssValueToPixels(style['border-left-width']) + | |
cssValueToPixels(style['border-right-width']) + | |
cssValueToPixels(style['padding-left']) + | |
cssValueToPixels(style['padding-right']) + | |
cssValueToPixels(style['width']); | |
}, | |
/** | |
* | |
* @param elem | |
*/ | |
getHeight: function(elem) { | |
var style = getComputedStyle(elem); | |
return cssValueToPixels(style['border-top-width']) + | |
cssValueToPixels(style['border-bottom-width']) + | |
cssValueToPixels(style['padding-top']) + | |
cssValueToPixels(style['padding-bottom']) + | |
cssValueToPixels(style['height']); | |
}, | |
/** | |
* | |
* @param elem | |
*/ | |
getOffset: function(elem) { | |
var offset = {left: 0, top:0}; | |
if (elem.offsetParent) { | |
do { | |
offset.left += elem.offsetLeft; | |
offset.top += elem.offsetTop; | |
} while (elem = elem.offsetParent); | |
} | |
return offset; | |
}, | |
// http://stackoverflow.com/posts/2684561/revisions | |
/** | |
* | |
* @param elem | |
*/ | |
isActive: function(elem) { | |
return elem === document.activeElement && ( elem.type || elem.href ); | |
} | |
}; | |
return dom; | |
})(dat.utils.common); | |
dat.controllers.OptionController = (function (Controller, dom, common) { | |
/** | |
* @class Provides a select input to alter the property of an object, using a | |
* list of accepted values. | |
* | |
* @extends dat.controllers.Controller | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* @param {Object|string[]} options A map of labels to acceptable values, or | |
* a list of acceptable string values. | |
* | |
* @member dat.controllers | |
*/ | |
var OptionController = function(object, property, options) { | |
OptionController.superclass.call(this, object, property); | |
var _this = this; | |
/** | |
* The drop down menu | |
* @ignore | |
*/ | |
this.__select = document.createElement('select'); | |
if (common.isArray(options)) { | |
var map = {}; | |
common.each(options, function(element) { | |
map[element] = element; | |
}); | |
options = map; | |
} | |
common.each(options, function(value, key) { | |
var opt = document.createElement('option'); | |
opt.innerHTML = key; | |
opt.setAttribute('value', value); | |
_this.__select.appendChild(opt); | |
}); | |
// Acknowledge original value | |
this.updateDisplay(); | |
dom.bind(this.__select, 'change', function() { | |
var desiredValue = this.options[this.selectedIndex].value; | |
_this.setValue(desiredValue); | |
}); | |
this.domElement.appendChild(this.__select); | |
}; | |
OptionController.superclass = Controller; | |
common.extend( | |
OptionController.prototype, | |
Controller.prototype, | |
{ | |
setValue: function(v) { | |
var toReturn = OptionController.superclass.prototype.setValue.call(this, v); | |
if (this.__onFinishChange) { | |
this.__onFinishChange.call(this, this.getValue()); | |
} | |
return toReturn; | |
}, | |
updateDisplay: function() { | |
this.__select.value = this.getValue(); | |
return OptionController.superclass.prototype.updateDisplay.call(this); | |
} | |
} | |
); | |
return OptionController; | |
})(dat.controllers.Controller, | |
dat.dom.dom, | |
dat.utils.common); | |
dat.controllers.NumberController = (function (Controller, common) { | |
/** | |
* @class Represents a given property of an object that is a number. | |
* | |
* @extends dat.controllers.Controller | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* @param {Object} [params] Optional parameters | |
* @param {Number} [params.min] Minimum allowed value | |
* @param {Number} [params.max] Maximum allowed value | |
* @param {Number} [params.step] Increment by which to change value | |
* | |
* @member dat.controllers | |
*/ | |
var NumberController = function(object, property, params) { | |
NumberController.superclass.call(this, object, property); | |
params = params || {}; | |
this.__min = params.min; | |
this.__max = params.max; | |
this.__step = params.step; | |
if (common.isUndefined(this.__step)) { | |
if (this.initialValue == 0) { | |
this.__impliedStep = 1; // What are we, psychics? | |
} else { | |
// Hey Doug, check this out. | |
this.__impliedStep = Math.pow(10, Math.floor(Math.log(this.initialValue)/Math.LN10))/10; | |
} | |
} else { | |
this.__impliedStep = this.__step; | |
} | |
this.__precision = numDecimals(this.__impliedStep); | |
}; | |
NumberController.superclass = Controller; | |
common.extend( | |
NumberController.prototype, | |
Controller.prototype, | |
/** @lends dat.controllers.NumberController.prototype */ | |
{ | |
setValue: function(v) { | |
if (this.__min !== undefined && v < this.__min) { | |
v = this.__min; | |
} else if (this.__max !== undefined && v > this.__max) { | |
v = this.__max; | |
} | |
if (this.__step !== undefined && v % this.__step != 0) { | |
v = Math.round(v / this.__step) * this.__step; | |
} | |
return NumberController.superclass.prototype.setValue.call(this, v); | |
}, | |
/** | |
* Specify a minimum value for <code>object[property]</code>. | |
* | |
* @param {Number} minValue The minimum value for | |
* <code>object[property]</code> | |
* @returns {dat.controllers.NumberController} this | |
*/ | |
min: function(v) { | |
this.__min = v; | |
return this; | |
}, | |
/** | |
* Specify a maximum value for <code>object[property]</code>. | |
* | |
* @param {Number} maxValue The maximum value for | |
* <code>object[property]</code> | |
* @returns {dat.controllers.NumberController} this | |
*/ | |
max: function(v) { | |
this.__max = v; | |
return this; | |
}, | |
/** | |
* Specify a step value that dat.controllers.NumberController | |
* increments by. | |
* | |
* @param {Number} stepValue The step value for | |
* dat.controllers.NumberController | |
* @default if minimum and maximum specified increment is 1% of the | |
* difference otherwise stepValue is 1 | |
* @returns {dat.controllers.NumberController} this | |
*/ | |
step: function(v) { | |
this.__step = v; | |
this.__impliedStep = v; | |
this.__precision = numDecimals(v); | |
return this; | |
} | |
} | |
); | |
function numDecimals(x) { | |
x = x.toString(); | |
if (x.indexOf('.') > -1) { | |
return x.length - x.indexOf('.') - 1; | |
} else { | |
return 0; | |
} | |
} | |
return NumberController; | |
})(dat.controllers.Controller, | |
dat.utils.common); | |
dat.controllers.NumberControllerBox = (function (NumberController, dom, common) { | |
/** | |
* @class Represents a given property of an object that is a number and | |
* provides an input element with which to manipulate it. | |
* | |
* @extends dat.controllers.Controller | |
* @extends dat.controllers.NumberController | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* @param {Object} [params] Optional parameters | |
* @param {Number} [params.min] Minimum allowed value | |
* @param {Number} [params.max] Maximum allowed value | |
* @param {Number} [params.step] Increment by which to change value | |
* | |
* @member dat.controllers | |
*/ | |
var NumberControllerBox = function(object, property, params) { | |
this.__truncationSuspended = false; | |
NumberControllerBox.superclass.call(this, object, property, params); | |
var _this = this; | |
/** | |
* {Number} Previous mouse y position | |
* @ignore | |
*/ | |
var prev_y; | |
this.__input = document.createElement('input'); | |
this.__input.setAttribute('type', 'text'); | |
// Makes it so manually specified values are not truncated. | |
dom.bind(this.__input, 'change', onChange); | |
dom.bind(this.__input, 'blur', onBlur); | |
dom.bind(this.__input, 'mousedown', onMouseDown); | |
dom.bind(this.__input, 'keydown', function(e) { | |
// When pressing entire, you can be as precise as you want. | |
if (e.keyCode === 13) { | |
_this.__truncationSuspended = true; | |
this.blur(); | |
_this.__truncationSuspended = false; | |
} | |
}); | |
function onChange() { | |
var attempted = parseFloat(_this.__input.value); | |
if (!common.isNaN(attempted)) _this.setValue(attempted); | |
} | |
function onBlur() { | |
onChange(); | |
if (_this.__onFinishChange) { | |
_this.__onFinishChange.call(_this, _this.getValue()); | |
} | |
} | |
function onMouseDown(e) { | |
dom.bind(window, 'mousemove', onMouseDrag); | |
dom.bind(window, 'mouseup', onMouseUp); | |
prev_y = e.clientY; | |
} | |
function onMouseDrag(e) { | |
var diff = prev_y - e.clientY; | |
_this.setValue(_this.getValue() + diff * _this.__impliedStep); | |
prev_y = e.clientY; | |
} | |
function onMouseUp() { | |
dom.unbind(window, 'mousemove', onMouseDrag); | |
dom.unbind(window, 'mouseup', onMouseUp); | |
} | |
this.updateDisplay(); | |
this.domElement.appendChild(this.__input); | |
}; | |
NumberControllerBox.superclass = NumberController; | |
common.extend( | |
NumberControllerBox.prototype, | |
NumberController.prototype, | |
{ | |
updateDisplay: function() { | |
this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision); | |
return NumberControllerBox.superclass.prototype.updateDisplay.call(this); | |
} | |
} | |
); | |
function roundToDecimal(value, decimals) { | |
var tenTo = Math.pow(10, decimals); | |
return Math.round(value * tenTo) / tenTo; | |
} | |
return NumberControllerBox; | |
})(dat.controllers.NumberController, | |
dat.dom.dom, | |
dat.utils.common); | |
dat.controllers.NumberControllerSlider = (function (NumberController, dom, css, common, styleSheet) { | |
/** | |
* @class Represents a given property of an object that is a number, contains | |
* a minimum and maximum, and provides a slider element with which to | |
* manipulate it. It should be noted that the slider element is made up of | |
* <code><div></code> tags, <strong>not</strong> the html5 | |
* <code><slider></code> element. | |
* | |
* @extends dat.controllers.Controller | |
* @extends dat.controllers.NumberController | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* @param {Number} minValue Minimum allowed value | |
* @param {Number} maxValue Maximum allowed value | |
* @param {Number} stepValue Increment by which to change value | |
* | |
* @member dat.controllers | |
*/ | |
var NumberControllerSlider = function(object, property, min, max, step) { | |
NumberControllerSlider.superclass.call(this, object, property, { min: min, max: max, step: step }); | |
var _this = this; | |
this.__background = document.createElement('div'); | |
this.__foreground = document.createElement('div'); | |
dom.bind(this.__background, 'mousedown', onMouseDown); | |
dom.addClass(this.__background, 'slider'); | |
dom.addClass(this.__foreground, 'slider-fg'); | |
function onMouseDown(e) { | |
dom.bind(window, 'mousemove', onMouseDrag); | |
dom.bind(window, 'mouseup', onMouseUp); | |
onMouseDrag(e); | |
} | |
function onMouseDrag(e) { | |
e.preventDefault(); | |
var offset = dom.getOffset(_this.__background); | |
var width = dom.getWidth(_this.__background); | |
_this.setValue( | |
map(e.clientX, offset.left, offset.left + width, _this.__min, _this.__max) | |
); | |
return false; | |
} | |
function onMouseUp() { | |
dom.unbind(window, 'mousemove', onMouseDrag); | |
dom.unbind(window, 'mouseup', onMouseUp); | |
if (_this.__onFinishChange) { | |
_this.__onFinishChange.call(_this, _this.getValue()); | |
} | |
} | |
this.updateDisplay(); | |
this.__background.appendChild(this.__foreground); | |
this.domElement.appendChild(this.__background); | |
}; | |
NumberControllerSlider.superclass = NumberController; | |
/** | |
* Injects default stylesheet for slider elements. | |
*/ | |
NumberControllerSlider.useDefaultStyles = function() { | |
css.inject(styleSheet); | |
}; | |
common.extend( | |
NumberControllerSlider.prototype, | |
NumberController.prototype, | |
{ | |
updateDisplay: function() { | |
var pct = (this.getValue() - this.__min)/(this.__max - this.__min); | |
this.__foreground.style.width = pct*100+'%'; | |
return NumberControllerSlider.superclass.prototype.updateDisplay.call(this); | |
} | |
} | |
); | |
function map(v, i1, i2, o1, o2) { | |
return o1 + (o2 - o1) * ((v - i1) / (i2 - i1)); | |
} | |
return NumberControllerSlider; | |
})(dat.controllers.NumberController, | |
dat.dom.dom, | |
dat.utils.css, | |
dat.utils.common, | |
"/**\n * dat-gui JavaScript Controller Library\n * http://code.google.com/p/dat-gui\n *\n * Copyright 2011 Data Arts Team, Google Creative Lab\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n */\n\n.slider {\n box-shadow: inset 0 2px 4px rgba(0,0,0,0.15);\n height: 1em;\n border-radius: 1em;\n background-color: #eee;\n padding: 0 0.5em;\n overflow: hidden;\n}\n\n.slider-fg {\n padding: 1px 0 2px 0;\n background-color: #aaa;\n height: 1em;\n margin-left: -0.5em;\n padding-right: 0.5em;\n border-radius: 1em 0 0 1em;\n}\n\n.slider-fg:after {\n display: inline-block;\n border-radius: 1em;\n background-color: #fff;\n border: 1px solid #aaa;\n content: '';\n float: right;\n margin-right: -1em;\n margin-top: -1px;\n height: 0.9em;\n width: 0.9em;\n}"); | |
dat.controllers.FunctionController = (function (Controller, dom, common) { | |
/** | |
* @class Provides a GUI interface to fire a specified method, a property of an object. | |
* | |
* @extends dat.controllers.Controller | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* | |
* @member dat.controllers | |
*/ | |
var FunctionController = function(object, property, text) { | |
FunctionController.superclass.call(this, object, property); | |
var _this = this; | |
this.__button = document.createElement('div'); | |
this.__button.innerHTML = text === undefined ? 'Fire' : text; | |
dom.bind(this.__button, 'click', function(e) { | |
e.preventDefault(); | |
_this.fire(); | |
return false; | |
}); | |
dom.addClass(this.__button, 'button'); | |
this.domElement.appendChild(this.__button); | |
}; | |
FunctionController.superclass = Controller; | |
common.extend( | |
FunctionController.prototype, | |
Controller.prototype, | |
{ | |
fire: function() { | |
if (this.__onChange) { | |
this.__onChange.call(this); | |
} | |
if (this.__onFinishChange) { | |
this.__onFinishChange.call(this, this.getValue()); | |
} | |
this.getValue().call(this.object); | |
} | |
} | |
); | |
return FunctionController; | |
})(dat.controllers.Controller, | |
dat.dom.dom, | |
dat.utils.common); | |
dat.controllers.BooleanController = (function (Controller, dom, common) { | |
/** | |
* @class Provides a checkbox input to alter the boolean property of an object. | |
* @extends dat.controllers.Controller | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* | |
* @member dat.controllers | |
*/ | |
var BooleanController = function(object, property) { | |
BooleanController.superclass.call(this, object, property); | |
var _this = this; | |
this.__prev = this.getValue(); | |
this.__checkbox = document.createElement('input'); | |
this.__checkbox.setAttribute('type', 'checkbox'); | |
dom.bind(this.__checkbox, 'change', onChange, false); | |
this.domElement.appendChild(this.__checkbox); | |
// Match original value | |
this.updateDisplay(); | |
function onChange() { | |
_this.setValue(!_this.__prev); | |
} | |
}; | |
BooleanController.superclass = Controller; | |
common.extend( | |
BooleanController.prototype, | |
Controller.prototype, | |
{ | |
setValue: function(v) { | |
var toReturn = BooleanController.superclass.prototype.setValue.call(this, v); | |
if (this.__onFinishChange) { | |
this.__onFinishChange.call(this, this.getValue()); | |
} | |
this.__prev = this.getValue(); | |
return toReturn; | |
}, | |
updateDisplay: function() { | |
if (this.getValue() === true) { | |
this.__checkbox.setAttribute('checked', 'checked'); | |
this.__checkbox.checked = true; | |
} else { | |
this.__checkbox.checked = false; | |
} | |
return BooleanController.superclass.prototype.updateDisplay.call(this); | |
} | |
} | |
); | |
return BooleanController; | |
})(dat.controllers.Controller, | |
dat.dom.dom, | |
dat.utils.common); | |
dat.color.toString = (function (common) { | |
return function(color) { | |
if (color.a == 1 || common.isUndefined(color.a)) { | |
var s = color.hex.toString(16); | |
while (s.length < 6) { | |
s = '0' + s; | |
} | |
return '#' + s; | |
} else { | |
return 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',' + color.a + ')'; | |
} | |
} | |
})(dat.utils.common); | |
dat.color.interpret = (function (toString, common) { | |
var result, toReturn; | |
var interpret = function() { | |
toReturn = false; | |
var original = arguments.length > 1 ? common.toArray(arguments) : arguments[0]; | |
common.each(INTERPRETATIONS, function(family) { | |
if (family.litmus(original)) { | |
common.each(family.conversions, function(conversion, conversionName) { | |
result = conversion.read(original); | |
if (toReturn === false && result !== false) { | |
toReturn = result; | |
result.conversionName = conversionName; | |
result.conversion = conversion; | |
return common.BREAK; | |
} | |
}); | |
return common.BREAK; | |
} | |
}); | |
return toReturn; | |
}; | |
var INTERPRETATIONS = [ | |
// Strings | |
{ | |
litmus: common.isString, | |
conversions: { | |
THREE_CHAR_HEX: { | |
read: function(original) { | |
var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i); | |
if (test === null) return false; | |
return { | |
space: 'HEX', | |
hex: parseInt( | |
'0x' + | |
test[1].toString() + test[1].toString() + | |
test[2].toString() + test[2].toString() + | |
test[3].toString() + test[3].toString()) | |
}; | |
}, | |
write: toString | |
}, | |
SIX_CHAR_HEX: { | |
read: function(original) { | |
var test = original.match(/^#([A-F0-9]{6})$/i); | |
if (test === null) return false; | |
return { | |
space: 'HEX', | |
hex: parseInt('0x' + test[1].toString()) | |
}; | |
}, | |
write: toString | |
}, | |
CSS_RGB: { | |
read: function(original) { | |
var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/); | |
if (test === null) return false; | |
return { | |
space: 'RGB', | |
r: parseFloat(test[1]), | |
g: parseFloat(test[2]), | |
b: parseFloat(test[3]) | |
}; | |
}, | |
write: toString | |
}, | |
CSS_RGBA: { | |
read: function(original) { | |
var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/); | |
if (test === null) return false; | |
return { | |
space: 'RGB', | |
r: parseFloat(test[1]), | |
g: parseFloat(test[2]), | |
b: parseFloat(test[3]), | |
a: parseFloat(test[4]) | |
}; | |
}, | |
write: toString | |
} | |
} | |
}, | |
// Numbers | |
{ | |
litmus: common.isNumber, | |
conversions: { | |
HEX: { | |
read: function(original) { | |
return { | |
space: 'HEX', | |
hex: original, | |
conversionName: 'HEX' | |
} | |
}, | |
write: function(color) { | |
return color.hex; | |
} | |
} | |
} | |
}, | |
// Arrays | |
{ | |
litmus: common.isArray, | |
conversions: { | |
RGB_ARRAY: { | |
read: function(original) { | |
if (original.length != 3) return false; | |
return { | |
space: 'RGB', | |
r: original[0], | |
g: original[1], | |
b: original[2] | |
}; | |
}, | |
write: function(color) { | |
return [color.r, color.g, color.b]; | |
} | |
}, | |
RGBA_ARRAY: { | |
read: function(original) { | |
if (original.length != 4) return false; | |
return { | |
space: 'RGB', | |
r: original[0], | |
g: original[1], | |
b: original[2], | |
a: original[3] | |
}; | |
}, | |
write: function(color) { | |
return [color.r, color.g, color.b, color.a]; | |
} | |
} | |
} | |
}, | |
// Objects | |
{ | |
litmus: common.isObject, | |
conversions: { | |
RGBA_OBJ: { | |
read: function(original) { | |
if (common.isNumber(original.r) && | |
common.isNumber(original.g) && | |
common.isNumber(original.b) && | |
common.isNumber(original.a)) { | |
return { | |
space: 'RGB', | |
r: original.r, | |
g: original.g, | |
b: original.b, | |
a: original.a | |
} | |
} | |
return false; | |
}, | |
write: function(color) { | |
return { | |
r: color.r, | |
g: color.g, | |
b: color.b, | |
a: color.a | |
} | |
} | |
}, | |
RGB_OBJ: { | |
read: function(original) { | |
if (common.isNumber(original.r) && | |
common.isNumber(original.g) && | |
common.isNumber(original.b)) { | |
return { | |
space: 'RGB', | |
r: original.r, | |
g: original.g, | |
b: original.b | |
} | |
} | |
return false; | |
}, | |
write: function(color) { | |
return { | |
r: color.r, | |
g: color.g, | |
b: color.b | |
} | |
} | |
}, | |
HSVA_OBJ: { | |
read: function(original) { | |
if (common.isNumber(original.h) && | |
common.isNumber(original.s) && | |
common.isNumber(original.v) && | |
common.isNumber(original.a)) { | |
return { | |
space: 'HSV', | |
h: original.h, | |
s: original.s, | |
v: original.v, | |
a: original.a | |
} | |
} | |
return false; | |
}, | |
write: function(color) { | |
return { | |
h: color.h, | |
s: color.s, | |
v: color.v, | |
a: color.a | |
} | |
} | |
}, | |
HSV_OBJ: { | |
read: function(original) { | |
if (common.isNumber(original.h) && | |
common.isNumber(original.s) && | |
common.isNumber(original.v)) { | |
return { | |
space: 'HSV', | |
h: original.h, | |
s: original.s, | |
v: original.v | |
} | |
} | |
return false; | |
}, | |
write: function(color) { | |
return { | |
h: color.h, | |
s: color.s, | |
v: color.v | |
} | |
} | |
} | |
} | |
} | |
]; | |
return interpret; | |
})(dat.color.toString, | |
dat.utils.common); | |
dat.GUI = dat.gui.GUI = (function (css, saveDialogueContents, styleSheet, controllerFactory, Controller, BooleanController, FunctionController, NumberControllerBox, NumberControllerSlider, OptionController, ColorController, requestAnimationFrame, CenteredDiv, dom, common) { | |
css.inject(styleSheet); | |
/** Outer-most className for GUI's */ | |
var CSS_NAMESPACE = 'dg'; | |
var HIDE_KEY_CODE = 72; | |
/** The only value shared between the JS and SCSS. Use caution. */ | |
var CLOSE_BUTTON_HEIGHT = 20; | |
var DEFAULT_DEFAULT_PRESET_NAME = 'Default'; | |
var SUPPORTS_LOCAL_STORAGE = (function() { | |
try { | |
return 'localStorage' in window && window['localStorage'] !== null; | |
} catch (e) { | |
return false; | |
} | |
})(); | |
var SAVE_DIALOGUE; | |
/** Have we yet to create an autoPlace GUI? */ | |
var auto_place_virgin = true; | |
/** Fixed position div that auto place GUI's go inside */ | |
var auto_place_container; | |
/** Are we hiding the GUI's ? */ | |
var hide = false; | |
/** GUI's which should be hidden */ | |
var hideable_guis = []; | |
/** | |
* A lightweight controller library for JavaScript. It allows you to easily | |
* manipulate variables and fire functions on the fly. | |
* @class | |
* | |
* @member dat.gui | |
* | |
* @param {Object} [params] | |
* @param {String} [params.name] The name of this GUI. | |
* @param {Object} [params.load] JSON object representing the saved state of | |
* this GUI. | |
* @param {Boolean} [params.auto=true] | |
* @param {dat.gui.GUI} [params.parent] The GUI I'm nested in. | |
* @param {Boolean} [params.closed] If true, starts closed | |
*/ | |
var GUI = function(params) { | |
var _this = this; | |
/** | |
* Outermost DOM Element | |
* @type DOMElement | |
*/ | |
this.domElement = document.createElement('div'); | |
this.__ul = document.createElement('ul'); | |
this.domElement.appendChild(this.__ul); | |
dom.addClass(this.domElement, CSS_NAMESPACE); | |
/** | |
* Nested GUI's by name | |
* @ignore | |
*/ | |
this.__folders = {}; | |
this.__controllers = []; | |
/** | |
* List of objects I'm remembering for save, only used in top level GUI | |
* @ignore | |
*/ | |
this.__rememberedObjects = []; | |
/** | |
* Maps the index of remembered objects to a map of controllers, only used | |
* in top level GUI. | |
* | |
* @private | |
* @ignore | |
* | |
* @example | |
* [ | |
* { | |
* propertyName: Controller, | |
* anotherPropertyName: Controller | |
* }, | |
* { | |
* propertyName: Controller | |
* } | |
* ] | |
*/ | |
this.__rememberedObjectIndecesToControllers = []; | |
this.__listening = []; | |
params = params || {}; | |
// Default parameters | |
params = common.defaults(params, { | |
autoPlace: true, | |
width: GUI.DEFAULT_WIDTH | |
}); | |
params = common.defaults(params, { | |
resizable: params.autoPlace, | |
hideable: params.autoPlace | |
}); | |
if (!common.isUndefined(params.load)) { | |
// Explicit preset | |
if (params.preset) params.load.preset = params.preset; | |
} else { | |
params.load = { preset: DEFAULT_DEFAULT_PRESET_NAME }; | |
} | |
if (common.isUndefined(params.parent) && params.hideable) { | |
hideable_guis.push(this); | |
} | |
// Only root level GUI's are resizable. | |
params.resizable = common.isUndefined(params.parent) && params.resizable; | |
if (params.autoPlace && common.isUndefined(params.scrollable)) { | |
params.scrollable = true; | |
} | |
// params.scrollable = common.isUndefined(params.parent) && params.scrollable === true; | |
// Not part of params because I don't want people passing this in via | |
// constructor. Should be a 'remembered' value. | |
var use_local_storage = | |
SUPPORTS_LOCAL_STORAGE && | |
localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true'; | |
var saveToLocalStorage; | |
Object.defineProperties(this, | |
/** @lends dat.gui.GUI.prototype */ | |
{ | |
/** | |
* The parent <code>GUI</code> | |
* @type dat.gui.GUI | |
*/ | |
parent: { | |
get: function() { | |
return params.parent; | |
} | |
}, | |
scrollable: { | |
get: function() { | |
return params.scrollable; | |
} | |
}, | |
/** | |
* Handles <code>GUI</code>'s element placement for you | |
* @type Boolean | |
*/ | |
autoPlace: { | |
get: function() { | |
return params.autoPlace; | |
} | |
}, | |
/** | |
* The identifier for a set of saved values | |
* @type String | |
*/ | |
preset: { | |
get: function() { | |
if (_this.parent) { | |
return _this.getRoot().preset; | |
} else { | |
return params.load.preset; | |
} | |
}, | |
set: function(v) { | |
if (_this.parent) { | |
_this.getRoot().preset = v; | |
} else { | |
params.load.preset = v; | |
} | |
setPresetSelectIndex(this); | |
_this.revert(); | |
} | |
}, | |
/** | |
* The width of <code>GUI</code> element | |
* @type Number | |
*/ | |
width: { | |
get: function() { | |
return params.width; | |
}, | |
set: function(v) { | |
params.width = v; | |
setWidth(_this, v); | |
} | |
}, | |
/** | |
* The name of <code>GUI</code>. Used for folders. i.e | |
* a folder's name | |
* @type String | |
*/ | |
name: { | |
get: function() { | |
return params.name; | |
}, | |
set: function(v) { | |
// TODO Check for collisions among sibling folders | |
params.name = v; | |
if (title_row_name) { | |
title_row_name.innerHTML = params.name; | |
} | |
} | |
}, | |
/** | |
* Whether the <code>GUI</code> is collapsed or not | |
* @type Boolean | |
*/ | |
closed: { | |
get: function() { | |
return params.closed; | |
}, | |
set: function(v) { | |
params.closed = v; | |
if (params.closed) { | |
dom.addClass(_this.__ul, GUI.CLASS_CLOSED); | |
} else { | |
dom.removeClass(_this.__ul, GUI.CLASS_CLOSED); | |
} | |
// For browsers that aren't going to respect the CSS transition, | |
// Lets just check our height against the window height right off | |
// the bat. | |
this.onResize(); | |
if (_this.__closeButton) { | |
_this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED; | |
} | |
} | |
}, | |
/** | |
* Contains all presets | |
* @type Object | |
*/ | |
load: { | |
get: function() { | |
return params.load; | |
} | |
}, | |
/** | |
* Determines whether or not to use <a href="https://developer.mozilla.org/en/DOM/Storage#localStorage">localStorage</a> as the means for | |
* <code>remember</code>ing | |
* @type Boolean | |
*/ | |
useLocalStorage: { | |
get: function() { | |
return use_local_storage; | |
}, | |
set: function(bool) { | |
if (SUPPORTS_LOCAL_STORAGE) { | |
use_local_storage = bool; | |
if (bool) { | |
dom.bind(window, 'unload', saveToLocalStorage); | |
} else { | |
dom.unbind(window, 'unload', saveToLocalStorage); | |
} | |
localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool); | |
} | |
} | |
} | |
}); | |
// Are we a root level GUI? | |
if (common.isUndefined(params.parent)) { | |
params.closed = false; | |
dom.addClass(this.domElement, GUI.CLASS_MAIN); | |
dom.makeSelectable(this.domElement, false); | |
// Are we supposed to be loading locally? | |
if (SUPPORTS_LOCAL_STORAGE) { | |
if (use_local_storage) { | |
_this.useLocalStorage = true; | |
var saved_gui = localStorage.getItem(getLocalStorageHash(this, 'gui')); | |
if (saved_gui) { | |
params.load = JSON.parse(saved_gui); | |
} | |
} | |
} | |
this.__closeButton = document.createElement('div'); | |
this.__closeButton.innerHTML = GUI.TEXT_CLOSED; | |
dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON); | |
this.domElement.appendChild(this.__closeButton); | |
dom.bind(this.__closeButton, 'click', function() { | |
_this.closed = !_this.closed; | |
}); | |
// Oh, you're a nested GUI! | |
} else { | |
if (params.closed === undefined) { | |
params.closed = true; | |
} | |
var title_row_name = document.createTextNode(params.name); | |
dom.addClass(title_row_name, 'controller-name'); | |
var title_row = addRow(_this, title_row_name); | |
var on_click_title = function(e) { | |
e.preventDefault(); | |
_this.closed = !_this.closed; | |
return false; | |
}; | |
dom.addClass(this.__ul, GUI.CLASS_CLOSED); | |
dom.addClass(title_row, 'title'); | |
dom.bind(title_row, 'click', on_click_title); | |
if (!params.closed) { | |
this.closed = false; | |
} | |
} | |
if (params.autoPlace) { | |
if (common.isUndefined(params.parent)) { | |
if (auto_place_virgin) { | |
auto_place_container = document.createElement('div'); | |
dom.addClass(auto_place_container, CSS_NAMESPACE); | |
dom.addClass(auto_place_container, GUI.CLASS_AUTO_PLACE_CONTAINER); | |
document.body.appendChild(auto_place_container); | |
auto_place_virgin = false; | |
} | |
// Put it in the dom for you. | |
auto_place_container.appendChild(this.domElement); | |
// Apply the auto styles | |
dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE); | |
} | |
// Make it not elastic. | |
if (!this.parent) setWidth(_this, params.width); | |
} | |
dom.bind(window, 'resize', function() { _this.onResize() }); | |
dom.bind(this.__ul, 'webkitTransitionEnd', function() { _this.onResize(); }); | |
dom.bind(this.__ul, 'transitionend', function() { _this.onResize() }); | |
dom.bind(this.__ul, 'oTransitionEnd', function() { _this.onResize() }); | |
this.onResize(); | |
if (params.resizable) { | |
addResizeHandle(this); | |
} | |
saveToLocalStorage = function () { | |
if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') { | |
localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject())); | |
} | |
} | |
// expose this method publicly | |
this.saveToLocalStorageIfPossible = saveToLocalStorage; | |
var root = _this.getRoot(); | |
function resetWidth() { | |
var root = _this.getRoot(); | |
root.width += 1; | |
common.defer(function() { | |
root.width -= 1; | |
}); | |
} | |
if (!params.parent) { | |
resetWidth(); | |
} | |
}; | |
GUI.toggleHide = function() { | |
hide = !hide; | |
common.each(hideable_guis, function(gui) { | |
gui.domElement.style.zIndex = hide ? -999 : 999; | |
gui.domElement.style.opacity = hide ? 0 : 1; | |
}); | |
}; | |
GUI.CLASS_AUTO_PLACE = 'a'; | |
GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac'; | |
GUI.CLASS_MAIN = 'main'; | |
GUI.CLASS_CONTROLLER_ROW = 'cr'; | |
GUI.CLASS_TOO_TALL = 'taller-than-window'; | |
GUI.CLASS_CLOSED = 'closed'; | |
GUI.CLASS_CLOSE_BUTTON = 'close-button'; | |
GUI.CLASS_DRAG = 'drag'; | |
GUI.DEFAULT_WIDTH = 245; | |
GUI.TEXT_CLOSED = 'Close Controls'; | |
GUI.TEXT_OPEN = 'Open Controls'; | |
dom.bind(window, 'keydown', function(e) { | |
if (document.activeElement.type !== 'text' && | |
(e.which === HIDE_KEY_CODE || e.keyCode == HIDE_KEY_CODE)) { | |
GUI.toggleHide(); | |
} | |
}, false); | |
common.extend( | |
GUI.prototype, | |
/** @lends dat.gui.GUI */ | |
{ | |
/** | |
* @param object | |
* @param property | |
* @returns {dat.controllers.Controller} The new controller that was added. | |
* @instance | |
*/ | |
add: function(object, property) { | |
return add( | |
this, | |
object, | |
property, | |
{ | |
factoryArgs: Array.prototype.slice.call(arguments, 2) | |
} | |
); | |
}, | |
/** | |
* @param object | |
* @param property | |
* @returns {dat.controllers.ColorController} The new controller that was added. | |
* @instance | |
*/ | |
addColor: function(object, property) { | |
return add( | |
this, | |
object, | |
property, | |
{ | |
color: true | |
} | |
); | |
}, | |
/** | |
* @param controller | |
* @instance | |
*/ | |
remove: function(controller) { | |
// TODO listening? | |
this.__ul.removeChild(controller.__li); | |
this.__controllers.slice(this.__controllers.indexOf(controller), 1); | |
var _this = this; | |
common.defer(function() { | |
_this.onResize(); | |
}); | |
}, | |
destroy: function() { | |
if (this.autoPlace) { | |
auto_place_container.removeChild(this.domElement); | |
} | |
}, | |
/** | |
* @param name | |
* @returns {dat.gui.GUI} The new folder. | |
* @throws {Error} if this GUI already has a folder by the specified | |
* name | |
* @instance | |
*/ | |
addFolder: function(name) { | |
// We have to prevent collisions on names in order to have a key | |
// by which to remember saved values | |
if (this.__folders[name] !== undefined) { | |
throw new Error('You already have a folder in this GUI by the' + | |
' name "' + name + '"'); | |
} | |
var new_gui_params = { name: name, parent: this }; | |
// We need to pass down the autoPlace trait so that we can | |
// attach event listeners to open/close folder actions to | |
// ensure that a scrollbar appears if the window is too short. | |
new_gui_params.autoPlace = this.autoPlace; | |
// Do we have saved appearance data for this folder? | |
if (this.load && // Anything loaded? | |
this.load.folders && // Was my parent a dead-end? | |
this.load.folders[name]) { // Did daddy remember me? | |
// Start me closed if I was closed | |
new_gui_params.closed = this.load.folders[name].closed; | |
// Pass down the loaded data | |
new_gui_params.load = this.load.folders[name]; | |
} | |
var gui = new GUI(new_gui_params); | |
this.__folders[name] = gui; | |
var li = addRow(this, gui.domElement); | |
dom.addClass(li, 'folder'); | |
return gui; | |
}, | |
open: function() { | |
this.closed = false; | |
}, | |
close: function() { | |
this.closed = true; | |
}, | |
onResize: function() { | |
var root = this.getRoot(); | |
if (root.scrollable) { | |
var top = dom.getOffset(root.__ul).top; | |
var h = 0; | |
common.each(root.__ul.childNodes, function(node) { | |
if (! (root.autoPlace && node === root.__save_row)) | |
h += dom.getHeight(node); | |
}); | |
if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) { | |
dom.addClass(root.domElement, GUI.CLASS_TOO_TALL); | |
root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px'; | |
} else { | |
dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL); | |
root.__ul.style.height = 'auto'; | |
} | |
} | |
if (root.__resize_handle) { | |
common.defer(function() { | |
root.__resize_handle.style.height = root.__ul.offsetHeight + 'px'; | |
}); | |
} | |
if (root.__closeButton) { | |
root.__closeButton.style.width = root.width + 'px'; | |
} | |
}, | |
/** | |
* Mark objects for saving. The order of these objects cannot change as | |
* the GUI grows. When remembering new objects, append them to the end | |
* of the list. | |
* | |
* @param {Object...} objects | |
* @throws {Error} if not called on a top level GUI. | |
* @instance | |
*/ | |
remember: function() { | |
if (common.isUndefined(SAVE_DIALOGUE)) { | |
SAVE_DIALOGUE = new CenteredDiv(); | |
SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents; | |
} | |
if (this.parent) { | |
throw new Error("You can only call remember on a top level GUI."); | |
} | |
var _this = this; | |
common.each(Array.prototype.slice.call(arguments), function(object) { | |
if (_this.__rememberedObjects.length == 0) { | |
addSaveMenu(_this); | |
} | |
if (_this.__rememberedObjects.indexOf(object) == -1) { | |
_this.__rememberedObjects.push(object); | |
} | |
}); | |
if (this.autoPlace) { | |
// Set save row width | |
setWidth(this, this.width); | |
} | |
}, | |
/** | |
* @returns {dat.gui.GUI} the topmost parent GUI of a nested GUI. | |
* @instance | |
*/ | |
getRoot: function() { | |
var gui = this; | |
while (gui.parent) { | |
gui = gui.parent; | |
} | |
return gui; | |
}, | |
/** | |
* @returns {Object} a JSON object representing the current state of | |
* this GUI as well as its remembered properties. | |
* @instance | |
*/ | |
getSaveObject: function() { | |
var toReturn = this.load; | |
toReturn.closed = this.closed; | |
// Am I remembering any values? | |
if (this.__rememberedObjects.length > 0) { | |
toReturn.preset = this.preset; | |
if (!toReturn.remembered) { | |
toReturn.remembered = {}; | |
} | |
toReturn.remembered[this.preset] = getCurrentPreset(this); | |
} | |
toReturn.folders = {}; | |
common.each(this.__folders, function(element, key) { | |
toReturn.folders[key] = element.getSaveObject(); | |
}); | |
return toReturn; | |
}, | |
save: function() { | |
if (!this.load.remembered) { | |
this.load.remembered = {}; | |
} | |
this.load.remembered[this.preset] = getCurrentPreset(this); | |
markPresetModified(this, false); | |
this.saveToLocalStorageIfPossible(); | |
}, | |
saveAs: function(presetName) { | |
if (!this.load.remembered) { | |
// Retain default values upon first save | |
this.load.remembered = {}; | |
this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true); | |
} | |
this.load.remembered[presetName] = getCurrentPreset(this); | |
this.preset = presetName; | |
addPresetOption(this, presetName, true); | |
this.saveToLocalStorageIfPossible(); | |
}, | |
revert: function(gui) { | |
common.each(this.__controllers, function(controller) { | |
// Make revert work on Default. | |
if (!this.getRoot().load.remembered) { | |
controller.setValue(controller.initialValue); | |
} else { | |
recallSavedValue(gui || this.getRoot(), controller); | |
} | |
}, this); | |
common.each(this.__folders, function(folder) { | |
folder.revert(folder); | |
}); | |
if (!gui) { | |
markPresetModified(this.getRoot(), false); | |
} | |
}, | |
listen: function(controller) { | |
var init = this.__listening.length == 0; | |
this.__listening.push(controller); | |
if (init) updateDisplays(this.__listening); | |
} | |
} | |
); | |
function add(gui, object, property, params) { | |
if (object[property] === undefined) { | |
throw new Error("Object " + object + " has no property \"" + property + "\""); | |
} | |
var controller; | |
if (params.color) { | |
controller = new ColorController(object, property); | |
} else { | |
var factoryArgs = [object,property].concat(params.factoryArgs); | |
controller = controllerFactory.apply(gui, factoryArgs); | |
} | |
if (params.before instanceof Controller) { | |
params.before = params.before.__li; | |
} | |
recallSavedValue(gui, controller); | |
dom.addClass(controller.domElement, 'c'); | |
var name = document.createElement('span'); | |
dom.addClass(name, 'property-name'); | |
name.innerHTML = controller.property; | |
var container = document.createElement('div'); | |
container.appendChild(name); | |
container.appendChild(controller.domElement); | |
var li = addRow(gui, container, params.before); | |
dom.addClass(li, GUI.CLASS_CONTROLLER_ROW); | |
dom.addClass(li, typeof controller.getValue()); | |
augmentController(gui, li, controller); | |
gui.__controllers.push(controller); | |
return controller; | |
} | |
/** | |
* Add a row to the end of the GUI or before another row. | |
* | |
* @param gui | |
* @param [dom] If specified, inserts the dom content in the new row | |
* @param [liBefore] If specified, places the new row before another row | |
*/ | |
function addRow(gui, dom, liBefore) { | |
var li = document.createElement('li'); | |
if (dom) li.appendChild(dom); | |
if (liBefore) { | |
gui.__ul.insertBefore(li, params.before); | |
} else { | |
gui.__ul.appendChild(li); | |
} | |
gui.onResize(); | |
return li; | |
} | |
function augmentController(gui, li, controller) { | |
controller.__li = li; | |
controller.__gui = gui; | |
common.extend(controller, { | |
options: function(options) { | |
if (arguments.length > 1) { | |
controller.remove(); | |
return add( | |
gui, | |
controller.object, | |
controller.property, | |
{ | |
before: controller.__li.nextElementSibling, | |
factoryArgs: [common.toArray(arguments)] | |
} | |
); | |
} | |
if (common.isArray(options) || common.isObject(options)) { | |
controller.remove(); | |
return add( | |
gui, | |
controller.object, | |
controller.property, | |
{ | |
before: controller.__li.nextElementSibling, | |
factoryArgs: [options] | |
} | |
); | |
} | |
}, | |
name: function(v) { | |
controller.__li.firstElementChild.firstElementChild.innerHTML = v; | |
return controller; | |
}, | |
listen: function() { | |
controller.__gui.listen(controller); | |
return controller; | |
}, | |
remove: function() { | |
controller.__gui.remove(controller); | |
return controller; | |
} | |
}); | |
// All sliders should be accompanied by a box. | |
if (controller instanceof NumberControllerSlider) { | |
var box = new NumberControllerBox(controller.object, controller.property, | |
{ min: controller.__min, max: controller.__max, step: controller.__step }); | |
common.each(['updateDisplay', 'onChange', 'onFinishChange'], function(method) { | |
var pc = controller[method]; | |
var pb = box[method]; | |
controller[method] = box[method] = function() { | |
var args = Array.prototype.slice.call(arguments); | |
pc.apply(controller, args); | |
return pb.apply(box, args); | |
} | |
}); | |
dom.addClass(li, 'has-slider'); | |
controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild); | |
} | |
else if (controller instanceof NumberControllerBox) { | |
var r = function(returned) { | |
// Have we defined both boundaries? | |
if (common.isNumber(controller.__min) && common.isNumber(controller.__max)) { | |
// Well, then lets just replace this with a slider. | |
controller.remove(); | |
return add( | |
gui, | |
controller.object, | |
controller.property, | |
{ | |
before: controller.__li.nextElementSibling, | |
factoryArgs: [controller.__min, controller.__max, controller.__step] | |
}); | |
} | |
return returned; | |
}; | |
controller.min = common.compose(r, controller.min); | |
controller.max = common.compose(r, controller.max); | |
} | |
else if (controller instanceof BooleanController) { | |
dom.bind(li, 'click', function() { | |
dom.fakeEvent(controller.__checkbox, 'click'); | |
}); | |
dom.bind(controller.__checkbox, 'click', function(e) { | |
e.stopPropagation(); // Prevents double-toggle | |
}) | |
} | |
else if (controller instanceof FunctionController) { | |
dom.bind(li, 'click', function() { | |
dom.fakeEvent(controller.__button, 'click'); | |
}); | |
dom.bind(li, 'mouseover', function() { | |
dom.addClass(controller.__button, 'hover'); | |
}); | |
dom.bind(li, 'mouseout', function() { | |
dom.removeClass(controller.__button, 'hover'); | |
}); | |
} | |
else if (controller instanceof ColorController) { | |
dom.addClass(li, 'color'); | |
controller.updateDisplay = common.compose(function(r) { | |
li.style.borderLeftColor = controller.__color.toString(); | |
return r; | |
}, controller.updateDisplay); | |
controller.updateDisplay(); | |
} | |
controller.setValue = common.compose(function(r) { | |
if (gui.getRoot().__preset_select && controller.isModified()) { | |
markPresetModified(gui.getRoot(), true); | |
} | |
return r; | |
}, controller.setValue); | |
} | |
function recallSavedValue(gui, controller) { | |
// Find the topmost GUI, that's where remembered objects live. | |
var root = gui.getRoot(); | |
// Does the object we're controlling match anything we've been told to | |
// remember? | |
var matched_index = root.__rememberedObjects.indexOf(controller.object); | |
// Why yes, it does! | |
if (matched_index != -1) { | |
// Let me fetch a map of controllers for thcommon.isObject. | |
var controller_map = | |
root.__rememberedObjectIndecesToControllers[matched_index]; | |
// Ohp, I believe this is the first controller we've created for this | |
// object. Lets make the map fresh. | |
if (controller_map === undefined) { | |
controller_map = {}; | |
root.__rememberedObjectIndecesToControllers[matched_index] = | |
controller_map; | |
} | |
// Keep track of this controller | |
controller_map[controller.property] = controller; | |
// Okay, now have we saved any values for this controller? | |
if (root.load && root.load.remembered) { | |
var preset_map = root.load.remembered; | |
// Which preset are we trying to load? | |
var preset; | |
if (preset_map[gui.preset]) { | |
preset = preset_map[gui.preset]; | |
} else if (preset_map[DEFAULT_DEFAULT_PRESET_NAME]) { | |
// Uhh, you can have the default instead? | |
preset = preset_map[DEFAULT_DEFAULT_PRESET_NAME]; | |
} else { | |
// Nada. | |
return; | |
} | |
// Did the loaded object remember thcommon.isObject? | |
if (preset[matched_index] && | |
// Did we remember this particular property? | |
preset[matched_index][controller.property] !== undefined) { | |
// We did remember something for this guy ... | |
var value = preset[matched_index][controller.property]; | |
// And that's what it is. | |
controller.initialValue = value; | |
controller.setValue(value); | |
} | |
} | |
} | |
} | |
function getLocalStorageHash(gui, key) { | |
// TODO how does this deal with multiple GUI's? | |
return document.location.href + '.' + key; | |
} | |
function addSaveMenu(gui) { | |
var div = gui.__save_row = document.createElement('li'); | |
dom.addClass(gui.domElement, 'has-save'); | |
gui.__ul.insertBefore(div, gui.__ul.firstChild); | |
dom.addClass(div, 'save-row'); | |
var gears = document.createElement('span'); | |
gears.innerHTML = ' '; | |
dom.addClass(gears, 'button gears'); | |
// TODO replace with FunctionController | |
var button = document.createElement('span'); | |
button.innerHTML = 'Save'; | |
dom.addClass(button, 'button'); | |
dom.addClass(button, 'save'); | |
var button2 = document.createElement('span'); | |
button2.innerHTML = 'New'; | |
dom.addClass(button2, 'button'); | |
dom.addClass(button2, 'save-as'); | |
var button3 = document.createElement('span'); | |
button3.innerHTML = 'Revert'; | |
dom.addClass(button3, 'button'); | |
dom.addClass(button3, 'revert'); | |
var select = gui.__preset_select = document.createElement('select'); | |
if (gui.load && gui.load.remembered) { | |
common.each(gui.load.remembered, function(value, key) { | |
addPresetOption(gui, key, key == gui.preset); | |
}); | |
} else { | |
addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false); | |
} | |
dom.bind(select, 'change', function() { | |
for (var index = 0; index < gui.__preset_select.length; index++) { | |
gui.__preset_select[index].innerHTML = gui.__preset_select[index].value; | |
} | |
gui.preset = this.value; | |
}); | |
div.appendChild(select); | |
div.appendChild(gears); | |
div.appendChild(button); | |
div.appendChild(button2); | |
div.appendChild(button3); | |
if (SUPPORTS_LOCAL_STORAGE) { | |
var saveLocally = document.getElementById('dg-save-locally'); | |
var explain = document.getElementById('dg-local-explain'); | |
saveLocally.style.display = 'block'; | |
var localStorageCheckBox = document.getElementById('dg-local-storage'); | |
if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') { | |
localStorageCheckBox.setAttribute('checked', 'checked'); | |
} | |
function showHideExplain() { | |
explain.style.display = gui.useLocalStorage ? 'block' : 'none'; | |
} | |
showHideExplain(); | |
// TODO: Use a boolean controller, fool! | |
dom.bind(localStorageCheckBox, 'change', function() { | |
gui.useLocalStorage = !gui.useLocalStorage; | |
showHideExplain(); | |
}); | |
} | |
var newConstructorTextArea = document.getElementById('dg-new-constructor'); | |
dom.bind(newConstructorTextArea, 'keydown', function(e) { | |
if (e.metaKey && (e.which === 67 || e.keyCode == 67)) { | |
SAVE_DIALOGUE.hide(); | |
} | |
}); | |
dom.bind(gears, 'click', function() { | |
newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2); | |
SAVE_DIALOGUE.show(); | |
newConstructorTextArea.focus(); | |
newConstructorTextArea.select(); | |
}); | |
dom.bind(button, 'click', function() { | |
gui.save(); | |
}); | |
dom.bind(button2, 'click', function() { | |
var presetName = prompt('Enter a new preset name.'); | |
if (presetName) gui.saveAs(presetName); | |
}); | |
dom.bind(button3, 'click', function() { | |
gui.revert(); | |
}); | |
// div.appendChild(button2); | |
} | |
function addResizeHandle(gui) { | |
gui.__resize_handle = document.createElement('div'); | |
common.extend(gui.__resize_handle.style, { | |
width: '6px', | |
marginLeft: '-3px', | |
height: '200px', | |
cursor: 'ew-resize', | |
position: 'absolute' | |
// border: '1px solid blue' | |
}); | |
var pmouseX; | |
dom.bind(gui.__resize_handle, 'mousedown', dragStart); | |
dom.bind(gui.__closeButton, 'mousedown', dragStart); | |
gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild); | |
function dragStart(e) { | |
e.preventDefault(); | |
pmouseX = e.clientX; | |
dom.addClass(gui.__closeButton, GUI.CLASS_DRAG); | |
dom.bind(window, 'mousemove', drag); | |
dom.bind(window, 'mouseup', dragStop); | |
return false; | |
} | |
function drag(e) { | |
e.preventDefault(); | |
gui.width += pmouseX - e.clientX; | |
gui.onResize(); | |
pmouseX = e.clientX; | |
return false; | |
} | |
function dragStop() { | |
dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG); | |
dom.unbind(window, 'mousemove', drag); | |
dom.unbind(window, 'mouseup', dragStop); | |
} | |
} | |
function setWidth(gui, w) { | |
gui.domElement.style.width = w + 'px'; | |
// Auto placed save-rows are position fixed, so we have to | |
// set the width manually if we want it to bleed to the edge | |
if (gui.__save_row && gui.autoPlace) { | |
gui.__save_row.style.width = w + 'px'; | |
}if (gui.__closeButton) { | |
gui.__closeButton.style.width = w + 'px'; | |
} | |
} | |
function getCurrentPreset(gui, useInitialValues) { | |
var toReturn = {}; | |
// For each object I'm remembering | |
common.each(gui.__rememberedObjects, function(val, index) { | |
var saved_values = {}; | |
// The controllers I've made for thcommon.isObject by property | |
var controller_map = | |
gui.__rememberedObjectIndecesToControllers[index]; | |
// Remember each value for each property | |
common.each(controller_map, function(controller, property) { | |
saved_values[property] = useInitialValues ? controller.initialValue : controller.getValue(); | |
}); | |
// Save the values for thcommon.isObject | |
toReturn[index] = saved_values; | |
}); | |
return toReturn; | |
} | |
function addPresetOption(gui, name, setSelected) { | |
var opt = document.createElement('option'); | |
opt.innerHTML = name; | |
opt.value = name; | |
gui.__preset_select.appendChild(opt); | |
if (setSelected) { | |
gui.__preset_select.selectedIndex = gui.__preset_select.length - 1; | |
} | |
} | |
function setPresetSelectIndex(gui) { | |
for (var index = 0; index < gui.__preset_select.length; index++) { | |
if (gui.__preset_select[index].value == gui.preset) { | |
gui.__preset_select.selectedIndex = index; | |
} | |
} | |
} | |
function markPresetModified(gui, modified) { | |
var opt = gui.__preset_select[gui.__preset_select.selectedIndex]; | |
// console.log('mark', modified, opt); | |
if (modified) { | |
opt.innerHTML = opt.value + "*"; | |
} else { | |
opt.innerHTML = opt.value; | |
} | |
} | |
function updateDisplays(controllerArray) { | |
if (controllerArray.length != 0) { | |
requestAnimationFrame(function() { | |
updateDisplays(controllerArray); | |
}); | |
} | |
common.each(controllerArray, function(c) { | |
c.updateDisplay(); | |
}); | |
} | |
return GUI; | |
})(dat.utils.css, | |
"<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n \n </div>\n \n </div>\n\n</div>", | |
".dg {\n /** Clear list styles */\n /* Auto-place container */\n /* Auto-placed GUI's */\n /* Line items that don't contain folders. */\n /** Folder names */\n /** Hides closed items */\n /** Controller row */\n /** Name-half (left) */\n /** Controller-half (right) */\n /** Controller placement */\n /** Shorter number boxes when slider is present. */\n /** Ensure the entire boolean and function row shows a hand */ }\n .dg ul {\n list-style: none;\n margin: 0;\n padding: 0;\n width: 100%;\n clear: both; }\n .dg.ac {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n height: 0;\n z-index: 0; }\n .dg:not(.ac) .main {\n /** Exclude mains in ac so that we don't hide close button */\n overflow: hidden; }\n .dg.main {\n -webkit-transition: opacity 0.1s linear;\n -o-transition: opacity 0.1s linear;\n -moz-transition: opacity 0.1s linear;\n transition: opacity 0.1s linear; }\n .dg.main.taller-than-window {\n overflow-y: auto; }\n .dg.main.taller-than-window .close-button {\n opacity: 1;\n /* TODO, these are style notes */\n margin-top: -1px;\n border-top: 1px solid #2c2c2c; }\n .dg.main ul.closed .close-button {\n opacity: 1 !important; }\n .dg.main:hover .close-button,\n .dg.main .close-button.drag {\n opacity: 1; }\n .dg.main .close-button {\n /*opacity: 0;*/\n -webkit-transition: opacity 0.1s linear;\n -o-transition: opacity 0.1s linear;\n -moz-transition: opacity 0.1s linear;\n transition: opacity 0.1s linear;\n border: 0;\n position: absolute;\n line-height: 19px;\n height: 20px;\n /* TODO, these are style notes */\n cursor: pointer;\n text-align: center;\n background-color: #000; }\n .dg.main .close-button:hover {\n background-color: #111; }\n .dg.a {\n float: right;\n margin-right: 15px;\n overflow-x: hidden; }\n .dg.a.has-save > ul {\n margin-top: 27px; }\n .dg.a.has-save > ul.closed {\n margin-top: 0; }\n .dg.a .save-row {\n position: fixed;\n top: 0;\n z-index: 1002; }\n .dg li {\n -webkit-transition: height 0.1s ease-out;\n -o-transition: height 0.1s ease-out;\n -moz-transition: height 0.1s ease-out;\n transition: height 0.1s ease-out; }\n .dg li:not(.folder) {\n cursor: auto;\n height: 27px;\n line-height: 27px;\n overflow: hidden;\n padding: 0 4px 0 5px; }\n .dg li.folder {\n padding: 0;\n border-left: 4px solid rgba(0, 0, 0, 0); }\n .dg li.title {\n cursor: pointer;\n margin-left: -4px; }\n .dg .closed li:not(.title),\n .dg .closed ul li,\n .dg .closed ul li > * {\n height: 0;\n overflow: hidden;\n border: 0; }\n .dg .cr {\n clear: both;\n padding-left: 3px;\n height: 27px; }\n .dg .property-name {\n cursor: default;\n float: left;\n clear: left;\n width: 40%;\n overflow: hidden;\n text-overflow: ellipsis; }\n .dg .c {\n float: left;\n width: 60%; }\n .dg .c input[type=text] {\n border: 0;\n margin-top: 4px;\n padding: 3px;\n width: 100%;\n float: right; }\n .dg .has-slider input[type=text] {\n width: 30%;\n /*display: none;*/\n margin-left: 0; }\n .dg .slider {\n float: left;\n width: 66%;\n margin-left: -5px;\n margin-right: 0;\n height: 19px;\n margin-top: 4px; }\n .dg .slider-fg {\n height: 100%; }\n .dg .c input[type=checkbox] {\n margin-top: 9px; }\n .dg .c select {\n margin-top: 5px; }\n .dg .cr.function,\n .dg .cr.function .property-name,\n .dg .cr.function *,\n .dg .cr.boolean,\n .dg .cr.boolean * {\n cursor: pointer; }\n .dg .selector {\n display: none;\n position: absolute;\n margin-left: -9px;\n margin-top: 23px;\n z-index: 10; }\n .dg .c:hover .selector,\n .dg .selector.drag {\n display: block; }\n .dg li.save-row {\n padding: 0; }\n .dg li.save-row .button {\n display: inline-block;\n padding: 0px 6px; }\n .dg.dialogue {\n background-color: #222;\n width: 460px;\n padding: 15px;\n font-size: 13px;\n line-height: 15px; }\n\n/* TODO Separate style and structure */\n#dg-new-constructor {\n padding: 10px;\n color: #222;\n font-family: Monaco, monospace;\n font-size: 10px;\n border: 0;\n resize: none;\n box-shadow: inset 1px 1px 1px #888;\n word-wrap: break-word;\n margin: 12px 0;\n display: block;\n width: 440px;\n overflow-y: scroll;\n height: 100px;\n position: relative; }\n\n#dg-local-explain {\n display: none;\n font-size: 11px;\n line-height: 17px;\n border-radius: 3px;\n background-color: #333;\n padding: 8px;\n margin-top: 10px; }\n #dg-local-explain code {\n font-size: 10px; }\n\n#dat-gui-save-locally {\n display: none; }\n\n/** Main type */\n.dg {\n color: #eee;\n font: 11px 'Lucida Grande', sans-serif;\n text-shadow: 0 -1px 0 #111;\n /** Auto place */\n /* Controller row, <li> */\n /** Controllers */ }\n .dg.main {\n /** Scrollbar */ }\n .dg.main::-webkit-scrollbar {\n width: 5px;\n background: #1a1a1a; }\n .dg.main::-webkit-scrollbar-corner {\n height: 0;\n display: none; }\n .dg.main::-webkit-scrollbar-thumb {\n border-radius: 5px;\n background: #676767; }\n .dg li:not(.folder) {\n background: #1a1a1a;\n border-bottom: 1px solid #2c2c2c; }\n .dg li.save-row {\n line-height: 25px;\n background: #dad5cb;\n border: 0; }\n .dg li.save-row select {\n margin-left: 5px;\n width: 108px; }\n .dg li.save-row .button {\n margin-left: 5px;\n margin-top: 1px;\n border-radius: 2px;\n font-size: 9px;\n line-height: 7px;\n padding: 4px 4px 5px 4px;\n background: #c5bdad;\n color: #fff;\n text-shadow: 0 1px 0 #b0a58f;\n box-shadow: 0 -1px 0 #b0a58f;\n cursor: pointer; }\n .dg li.save-row .button.gears {\n background: #c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;\n height: 7px;\n width: 8px; }\n .dg li.save-row .button:hover {\n background-color: #bab19e;\n box-shadow: 0 -1px 0 #b0a58f; }\n .dg li.folder {\n border-bottom: 0; }\n .dg li.title {\n padding-left: 16px;\n background: black url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;\n cursor: pointer;\n border-bottom: 1px solid rgba(255, 255, 255, 0.2); }\n .dg .closed li.title {\n background-image: url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==); }\n .dg .cr.boolean {\n border-left: 3px solid #806787; }\n .dg .cr.function {\n border-left: 3px solid #e61d5f; }\n .dg .cr.number {\n border-left: 3px solid #2fa1d6; }\n .dg .cr.number input[type=text] {\n color: #2fa1d6; }\n .dg .cr.string {\n border-left: 3px solid #1ed36f; }\n .dg .cr.string input[type=text] {\n color: #1ed36f; }\n .dg .cr.function:hover, .dg .cr.boolean:hover {\n background: #111; }\n .dg .c input[type=text] {\n background: #303030;\n outline: none; }\n .dg .c input[type=text]:hover {\n background: #3c3c3c; }\n .dg .c input[type=text]:focus {\n background: #494949;\n color: #fff; }\n .dg .c .slider {\n background: #303030;\n cursor: ew-resize; }\n .dg .c .slider-fg {\n background: #2fa1d6; }\n .dg .c .slider:hover {\n background: #3c3c3c; }\n .dg .c .slider:hover .slider-fg {\n background: #44abda; }\n", | |
dat.controllers.factory = (function (OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) { | |
return function(object, property) { | |
var initialValue = object[property]; | |
// Providing options? | |
if (common.isArray(arguments[2]) || common.isObject(arguments[2])) { | |
return new OptionController(object, property, arguments[2]); | |
} | |
// Providing a map? | |
if (common.isNumber(initialValue)) { | |
if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) { | |
// Has min and max. | |
return new NumberControllerSlider(object, property, arguments[2], arguments[3]); | |
} else { | |
return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] }); | |
} | |
} | |
if (common.isString(initialValue)) { | |
return new StringController(object, property); | |
} | |
if (common.isFunction(initialValue)) { | |
return new FunctionController(object, property, ''); | |
} | |
if (common.isBoolean(initialValue)) { | |
return new BooleanController(object, property); | |
} | |
} | |
})(dat.controllers.OptionController, | |
dat.controllers.NumberControllerBox, | |
dat.controllers.NumberControllerSlider, | |
dat.controllers.StringController = (function (Controller, dom, common) { | |
/** | |
* @class Provides a text input to alter the string property of an object. | |
* | |
* @extends dat.controllers.Controller | |
* | |
* @param {Object} object The object to be manipulated | |
* @param {string} property The name of the property to be manipulated | |
* | |
* @member dat.controllers | |
*/ | |
var StringController = function(object, property) { | |
StringController.superclass.call(this, object, property); | |
var _this = this; | |
this.__input = document.createElement('input'); | |
this.__input.setAttribute('type', 'text'); | |
dom.bind(this.__input, 'keyup', onChange); | |
dom.bind(this.__input, 'change', onChange); | |
dom.bind(this.__input, 'blur', onBlur); | |
dom.bind(this.__input, 'keydown', function(e) { | |
if (e.keyCode === 13) { | |
this.blur(); | |
} | |
}); | |
function onChange() { | |
_this.setValue(_this.__input.value); | |
} | |
function onBlur() { | |
if (_this.__onFinishChange) { | |
_this.__onFinishChange.call(_this, _this.getValue()); | |
} | |
} | |
this.updateDisplay(); | |
this.domElement.appendChild(this.__input); | |
}; | |
StringController.superclass = Controller; | |
common.extend( | |
StringController.prototype, | |
Controller.prototype, | |
{ | |
updateDisplay: function() { | |
// Stops the caret from moving on account of: | |
// keyup -> setValue -> updateDisplay | |
if (!dom.isActive(this.__input)) { | |
this.__input.value = this.getValue(); | |
} | |
return StringController.superclass.prototype.updateDisplay.call(this); | |
} | |
} | |
); | |
return StringController; | |
})(dat.controllers.Controller, | |
dat.dom.dom, | |
dat.utils.common), | |
dat.controllers.FunctionController, | |
dat.controllers.BooleanController, | |
dat.utils.common), | |
dat.controllers.Controller, | |
dat.controllers.BooleanController, | |
dat.controllers.FunctionController, | |
dat.controllers.NumberControllerBox, | |
dat.controllers.NumberControllerSlider, | |
dat.controllers.OptionController, | |
dat.controllers.ColorController = (function (Controller, dom, Color, interpret, common) { | |
var ColorController = function(object, property) { | |
ColorController.superclass.call(this, object, property); | |
this.__color = new Color(this.getValue()); | |
this.__temp = new Color(0); | |
var _this = this; | |
this.domElement = document.createElement('div'); | |
dom.makeSelectable(this.domElement, false); | |
this.__selector = document.createElement('div'); | |
this.__selector.className = 'selector'; | |
this.__saturation_field = document.createElement('div'); | |
this.__saturation_field.className = 'saturation-field'; | |
this.__field_knob = document.createElement('div'); | |
this.__field_knob.className = 'field-knob'; | |
this.__field_knob_border = '2px solid '; | |
this.__hue_knob = document.createElement('div'); | |
this.__hue_knob.className = 'hue-knob'; | |
this.__hue_field = document.createElement('div'); | |
this.__hue_field.className = 'hue-field'; | |
this.__input = document.createElement('input'); | |
this.__input.type = 'text'; | |
this.__input_textShadow = '0 1px 1px '; | |
dom.bind(this.__input, 'keydown', function(e) { | |
if (e.keyCode === 13) { // on enter | |
onBlur.call(this); | |
} | |
}); | |
dom.bind(this.__input, 'blur', onBlur); | |
dom.bind(this.__selector, 'mousedown', function(e) { | |
dom | |
.addClass(this, 'drag') | |
.bind(window, 'mouseup', function(e) { | |
dom.removeClass(_this.__selector, 'drag'); | |
}); | |
}); | |
var value_field = document.createElement('div'); | |
common.extend(this.__selector.style, { | |
width: '122px', | |
height: '102px', | |
padding: '3px', | |
backgroundColor: '#222', | |
boxShadow: '0px 1px 3px rgba(0,0,0,0.3)' | |
}); | |
common.extend(this.__field_knob.style, { | |
position: 'absolute', | |
width: '12px', | |
height: '12px', | |
border: this.__field_knob_border + (this.__color.v < .5 ? '#fff' : '#000'), | |
boxShadow: '0px 1px 3px rgba(0,0,0,0.5)', | |
borderRadius: '12px', | |
zIndex: 1 | |
}); | |
common.extend(this.__hue_knob.style, { | |
position: 'absolute', | |
width: '15px', | |
height: '2px', | |
borderRight: '4px solid #fff', | |
zIndex: 1 | |
}); | |
common.extend(this.__saturation_field.style, { | |
width: '100px', | |
height: '100px', | |
border: '1px solid #555', | |
marginRight: '3px', | |
display: 'inline-block', | |
cursor: 'pointer' | |
}); | |
common.extend(value_field.style, { | |
width: '100%', | |
height: '100%', | |
background: 'none' | |
}); | |
linearGradient(value_field, 'top', 'rgba(0,0,0,0)', '#000'); | |
common.extend(this.__hue_field.style, { | |
width: '15px', | |
height: '100px', | |
display: 'inline-block', | |
border: '1px solid #555', | |
cursor: 'ns-resize' | |
}); | |
hueGradient(this.__hue_field); | |
common.extend(this.__input.style, { | |
outline: 'none', | |
// width: '120px', | |
textAlign: 'center', | |
// padding: '4px', | |
// marginBottom: '6px', | |
color: '#fff', | |
border: 0, | |
fontWeight: 'bold', | |
textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)' | |
}); | |
dom.bind(this.__saturation_field, 'mousedown', fieldDown); | |
dom.bind(this.__field_knob, 'mousedown', fieldDown); | |
dom.bind(this.__hue_field, 'mousedown', function(e) { | |
setH(e); | |
dom.bind(window, 'mousemove', setH); | |
dom.bind(window, 'mouseup', unbindH); | |
}); | |
function fieldDown(e) { | |
setSV(e); | |
// document.body.style.cursor = 'none'; | |
dom.bind(window, 'mousemove', setSV); | |
dom.bind(window, 'mouseup', unbindSV); | |
} | |
function unbindSV() { | |
dom.unbind(window, 'mousemove', setSV); | |
dom.unbind(window, 'mouseup', unbindSV); | |
// document.body.style.cursor = 'default'; | |
} | |
function onBlur() { | |
var i = interpret(this.value); | |
if (i !== false) { | |
_this.__color.__state = i; | |
_this.setValue(_this.__color.toOriginal()); | |
} else { | |
this.value = _this.__color.toString(); | |
} | |
} | |
function unbindH() { | |
dom.unbind(window, 'mousemove', setH); | |
dom.unbind(window, 'mouseup', unbindH); | |
} | |
this.__saturation_field.appendChild(value_field); | |
this.__selector.appendChild(this.__field_knob); | |
this.__selector.appendChild(this.__saturation_field); | |
this.__selector.appendChild(this.__hue_field); | |
this.__hue_field.appendChild(this.__hue_knob); | |
this.domElement.appendChild(this.__input); | |
this.domElement.appendChild(this.__selector); | |
this.updateDisplay(); | |
function setSV(e) { | |
e.preventDefault(); | |
var w = dom.getWidth(_this.__saturation_field); | |
var o = dom.getOffset(_this.__saturation_field); | |
var s = (e.clientX - o.left + document.body.scrollLeft) / w; | |
var v = 1 - (e.clientY - o.top + document.body.scrollTop) / w; | |
if (v > 1) v = 1; | |
else if (v < 0) v = 0; | |
if (s > 1) s = 1; | |
else if (s < 0) s = 0; | |
_this.__color.v = v; | |
_this.__color.s = s; | |
_this.setValue(_this.__color.toOriginal()); | |
return false; | |
} | |
function setH(e) { | |
e.preventDefault(); | |
var s = dom.getHeight(_this.__hue_field); | |
var o = dom.getOffset(_this.__hue_field); | |
var h = 1 - (e.clientY - o.top + document.body.scrollTop) / s; | |
if (h > 1) h = 1; | |
else if (h < 0) h = 0; | |
_this.__color.h = h * 360; | |
_this.setValue(_this.__color.toOriginal()); | |
return false; | |
} | |
}; | |
ColorController.superclass = Controller; | |
common.extend( | |
ColorController.prototype, | |
Controller.prototype, | |
{ | |
updateDisplay: function() { | |
var i = interpret(this.getValue()); | |
if (i !== false) { | |
var mismatch = false; | |
// Check for mismatch on the interpreted value. | |
common.each(Color.COMPONENTS, function(component) { | |
if (!common.isUndefined(i[component]) && | |
!common.isUndefined(this.__color.__state[component]) && | |
i[component] !== this.__color.__state[component]) { | |
mismatch = true; | |
return {}; // break | |
} | |
}, this); | |
// If nothing diverges, we keep our previous values | |
// for statefulness, otherwise we recalculate fresh | |
if (mismatch) { | |
common.extend(this.__color.__state, i); | |
} | |
} | |
common.extend(this.__temp.__state, this.__color.__state); | |
this.__temp.a = 1; | |
var flip = (this.__color.v < .5 || this.__color.s > .5) ? 255 : 0; | |
var _flip = 255 - flip; | |
common.extend(this.__field_knob.style, { | |
marginLeft: 100 * this.__color.s - 7 + 'px', | |
marginTop: 100 * (1 - this.__color.v) - 7 + 'px', | |
backgroundColor: this.__temp.toString(), | |
border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip +')' | |
}); | |
this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px' | |
this.__temp.s = 1; | |
this.__temp.v = 1; | |
linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString()); | |
common.extend(this.__input.style, { | |
backgroundColor: this.__input.value = this.__color.toString(), | |
color: 'rgb(' + flip + ',' + flip + ',' + flip +')', | |
textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip +',.7)' | |
}); | |
} | |
} | |
); | |
var vendors = ['-moz-','-o-','-webkit-','-ms-','']; | |
function linearGradient(elem, x, a, b) { | |
elem.style.background = ''; | |
common.each(vendors, function(vendor) { | |
elem.style.cssText += 'background: ' + vendor + 'linear-gradient('+x+', '+a+' 0%, ' + b + ' 100%); '; | |
}); | |
} | |
function hueGradient(elem) { | |
elem.style.background = ''; | |
elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);' | |
elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);' | |
elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);' | |
elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);' | |
elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);' | |
} | |
return ColorController; | |
})(dat.controllers.Controller, | |
dat.dom.dom, | |
dat.color.Color = (function (interpret, math, toString, common) { | |
var Color = function() { | |
this.__state = interpret.apply(this, arguments); | |
if (this.__state === false) { | |
throw 'Failed to interpret color arguments'; | |
} | |
this.__state.a = this.__state.a || 1; | |
}; | |
Color.COMPONENTS = ['r','g','b','h','s','v','hex','a']; | |
common.extend(Color.prototype, { | |
toString: function() { | |
return toString(this); | |
}, | |
toOriginal: function() { | |
return this.__state.conversion.write(this); | |
} | |
}); | |
defineRGBComponent(Color.prototype, 'r', 2); | |
defineRGBComponent(Color.prototype, 'g', 1); | |
defineRGBComponent(Color.prototype, 'b', 0); | |
defineHSVComponent(Color.prototype, 'h'); | |
defineHSVComponent(Color.prototype, 's'); | |
defineHSVComponent(Color.prototype, 'v'); | |
Object.defineProperty(Color.prototype, 'a', { | |
get: function() { | |
return this.__state.a; | |
}, | |
set: function(v) { | |
this.__state.a = v; | |
} | |
}); | |
Object.defineProperty(Color.prototype, 'hex', { | |
get: function() { | |
if (!this.__state.space !== 'HEX') { | |
this.__state.hex = math.rgb_to_hex(this.r, this.g, this.b); | |
} | |
return this.__state.hex; | |
}, | |
set: function(v) { | |
this.__state.space = 'HEX'; | |
this.__state.hex = v; | |
} | |
}); | |
function defineRGBComponent(target, component, componentHexIndex) { | |
Object.defineProperty(target, component, { | |
get: function() { | |
if (this.__state.space === 'RGB') { | |
return this.__state[component]; | |
} | |
recalculateRGB(this, component, componentHexIndex); | |
return this.__state[component]; | |
}, | |
set: function(v) { | |
if (this.__state.space !== 'RGB') { | |
recalculateRGB(this, component, componentHexIndex); | |
this.__state.space = 'RGB'; | |
} | |
this.__state[component] = v; | |
} | |
}); | |
} | |
function defineHSVComponent(target, component) { | |
Object.defineProperty(target, component, { | |
get: function() { | |
if (this.__state.space === 'HSV') | |
return this.__state[component]; | |
recalculateHSV(this); | |
return this.__state[component]; | |
}, | |
set: function(v) { | |
if (this.__state.space !== 'HSV') { | |
recalculateHSV(this); | |
this.__state.space = 'HSV'; | |
} | |
this.__state[component] = v; | |
} | |
}); | |
} | |
function recalculateRGB(color, component, componentHexIndex) { | |
if (color.__state.space === 'HEX') { | |
color.__state[component] = math.component_from_hex(color.__state.hex, componentHexIndex); | |
} else if (color.__state.space === 'HSV') { | |
common.extend(color.__state, math.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v)); | |
} else { | |
throw 'Corrupted color state'; | |
} | |
} | |
function recalculateHSV(color) { | |
var result = math.rgb_to_hsv(color.r, color.g, color.b); | |
common.extend(color.__state, | |
{ | |
s: result.s, | |
v: result.v | |
} | |
); | |
if (!common.isNaN(result.h)) { | |
color.__state.h = result.h; | |
} else if (common.isUndefined(color.__state.h)) { | |
color.__state.h = 0; | |
} | |
} | |
return Color; | |
})(dat.color.interpret, | |
dat.color.math = (function () { | |
var tmpComponent; | |
return { | |
hsv_to_rgb: function(h, s, v) { | |
var hi = Math.floor(h / 60) % 6; | |
var f = h / 60 - Math.floor(h / 60); | |
var p = v * (1.0 - s); | |
var q = v * (1.0 - (f * s)); | |
var t = v * (1.0 - ((1.0 - f) * s)); | |
var c = [ | |
[v, t, p], | |
[q, v, p], | |
[p, v, t], | |
[p, q, v], | |
[t, p, v], | |
[v, p, q] | |
][hi]; | |
return { | |
r: c[0] * 255, | |
g: c[1] * 255, | |
b: c[2] * 255 | |
}; | |
}, | |
rgb_to_hsv: function(r, g, b) { | |
var min = Math.min(r, g, b), | |
max = Math.max(r, g, b), | |
delta = max - min, | |
h, s; | |
if (max != 0) { | |
s = delta / max; | |
} else { | |
return { | |
h: NaN, | |
s: 0, | |
v: 0 | |
}; | |
} | |
if (r == max) { | |
h = (g - b) / delta; | |
} else if (g == max) { | |
h = 2 + (b - r) / delta; | |
} else { | |
h = 4 + (r - g) / delta; | |
} | |
h /= 6; | |
if (h < 0) { | |
h += 1; | |
} | |
return { | |
h: h * 360, | |
s: s, | |
v: max / 255 | |
}; | |
}, | |
rgb_to_hex: function(r, g, b) { | |
var hex = this.hex_with_component(0, 2, r); | |
hex = this.hex_with_component(hex, 1, g); | |
hex = this.hex_with_component(hex, 0, b); | |
return hex; | |
}, | |
component_from_hex: function(hex, componentIndex) { | |
return (hex >> (componentIndex * 8)) & 0xFF; | |
}, | |
hex_with_component: function(hex, componentIndex, value) { | |
return value << (tmpComponent = componentIndex * 8) | (hex & ~ (0xFF << tmpComponent)); | |
} | |
} | |
})(), | |
dat.color.toString, | |
dat.utils.common), | |
dat.color.interpret, | |
dat.utils.common), | |
dat.utils.requestAnimationFrame = (function () { | |
/** | |
* requirejs version of Paul Irish's RequestAnimationFrame | |
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/ | |
*/ | |
return window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.oRequestAnimationFrame || | |
window.msRequestAnimationFrame || | |
function(callback, element) { | |
window.setTimeout(callback, 1000 / 60); | |
}; | |
})(), | |
dat.dom.CenteredDiv = (function (dom, common) { | |
var CenteredDiv = function() { | |
this.backgroundElement = document.createElement('div'); | |
common.extend(this.backgroundElement.style, { | |
backgroundColor: 'rgba(0,0,0,0.8)', | |
top: 0, | |
left: 0, | |
display: 'none', | |
zIndex: '1000', | |
opacity: 0, | |
WebkitTransition: 'opacity 0.2s linear' | |
}); | |
dom.makeFullscreen(this.backgroundElement); | |
this.backgroundElement.style.position = 'fixed'; | |
this.domElement = document.createElement('div'); | |
common.extend(this.domElement.style, { | |
position: 'fixed', | |
display: 'none', | |
zIndex: '1001', | |
opacity: 0, | |
WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear' | |
}); | |
document.body.appendChild(this.backgroundElement); | |
document.body.appendChild(this.domElement); | |
var _this = this; | |
dom.bind(this.backgroundElement, 'click', function() { | |
_this.hide(); | |
}); | |
}; | |
CenteredDiv.prototype.show = function() { | |
var _this = this; | |
this.backgroundElement.style.display = 'block'; | |
this.domElement.style.display = 'block'; | |
this.domElement.style.opacity = 0; | |
// this.domElement.style.top = '52%'; | |
this.domElement.style.webkitTransform = 'scale(1.1)'; | |
this.layout(); | |
common.defer(function() { | |
_this.backgroundElement.style.opacity = 1; | |
_this.domElement.style.opacity = 1; | |
_this.domElement.style.webkitTransform = 'scale(1)'; | |
}); | |
}; | |
CenteredDiv.prototype.hide = function() { | |
var _this = this; | |
var hide = function() { | |
_this.domElement.style.display = 'none'; | |
_this.backgroundElement.style.display = 'none'; | |
dom.unbind(_this.domElement, 'webkitTransitionEnd', hide); | |
dom.unbind(_this.domElement, 'transitionend', hide); | |
dom.unbind(_this.domElement, 'oTransitionEnd', hide); | |
}; | |
dom.bind(this.domElement, 'webkitTransitionEnd', hide); | |
dom.bind(this.domElement, 'transitionend', hide); | |
dom.bind(this.domElement, 'oTransitionEnd', hide); | |
this.backgroundElement.style.opacity = 0; | |
// this.domElement.style.top = '48%'; | |
this.domElement.style.opacity = 0; | |
this.domElement.style.webkitTransform = 'scale(1.1)'; | |
}; | |
CenteredDiv.prototype.layout = function() { | |
this.domElement.style.left = window.innerWidth/2 - dom.getWidth(this.domElement) / 2 + 'px'; | |
this.domElement.style.top = window.innerHeight/2 - dom.getHeight(this.domElement) / 2 + 'px'; | |
}; | |
function lockScroll(e) { | |
console.log(e); | |
} | |
return CenteredDiv; | |
})(dat.dom.dom, | |
dat.utils.common), | |
dat.dom.dom, | |
dat.utils.common); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* DeviceOrientationControls - applies device orientation on object rotation | |
* | |
* @param {Object} object - instance of THREE.Object3D | |
* @constructor | |
* | |
* @author richt / http://richt.me | |
* @author WestLangley / http://github.com/WestLangley | |
* @author jonobr1 / http://jonobr1.com | |
* @author arodic / http://aleksandarrodic.com | |
* @author doug / http://github.com/doug | |
* | |
* W3C Device Orientation control | |
* (http://w3c.github.io/deviceorientation/spec-source-orientation.html) | |
*/ | |
THREE.DeviceOrientationControls = function(object) { | |
this.object = object; | |
this.object.rotation.reorder('YXZ'); | |
this.freeze = true; | |
this.movementSpeed = 1.0; | |
this.rollSpeed = 0.005; | |
this.autoAlign = true; | |
this.autoForward = false; | |
this.alpha = 0; | |
this.beta = 0; | |
this.gamma = 0; | |
this.orient = 0; | |
this.alignQuaternion = new THREE.Quaternion(); | |
this.orientationQuaternion = new THREE.Quaternion(); | |
var quaternion = new THREE.Quaternion(); | |
var quaternionLerp = new THREE.Quaternion(); | |
var tempVector3 = new THREE.Vector3(); | |
var tempMatrix4 = new THREE.Matrix4(); | |
var tempEuler = new THREE.Euler(0, 0, 0, 'YXZ'); | |
var tempQuaternion = new THREE.Quaternion(); | |
var zee = new THREE.Vector3(0, 0, 1); | |
var up = new THREE.Vector3(0, 1, 0); | |
var v0 = new THREE.Vector3(0, 0, 0); | |
var euler = new THREE.Euler(); | |
var q0 = new THREE.Quaternion(); // - PI/2 around the x-axis | |
var q1 = new THREE.Quaternion(- Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); | |
this.deviceOrientation = {}; | |
this.screenOrientation = window.orientation || 0; | |
this.onDeviceOrientationChangeEvent = (function(rawEvtData) { | |
this.deviceOrientation = rawEvtData; | |
}).bind(this); | |
var getOrientation = function() { | |
switch (window.screen.orientation || window.screen.mozOrientation) { | |
case 'landscape-primary': | |
return 90; | |
case 'landscape-secondary': | |
return -90; | |
case 'portrait-secondary': | |
return 180; | |
case 'portrait-primary': | |
return 0; | |
} | |
// this returns 90 if width is greater then height | |
// and window orientation is undefined OR 0 | |
// if (!window.orientation && window.innerWidth > window.innerHeight) | |
// return 90; | |
return window.orientation || 0; | |
}; | |
this.onScreenOrientationChangeEvent = (function() { | |
this.screenOrientation = getOrientation(); | |
}).bind(this); | |
this.update = function(delta) { | |
return function() { | |
if (this.freeze) return; | |
// should not need this | |
var orientation = getOrientation(); | |
if (orientation !== this.screenOrientation) { | |
this.screenOrientation = orientation; | |
this.autoAlign = true; | |
} | |
this.alpha = this.deviceOrientation.gamma ? | |
THREE.Math.degToRad(this.deviceOrientation.alpha) : 0; // Z | |
this.beta = this.deviceOrientation.beta ? | |
THREE.Math.degToRad(this.deviceOrientation.beta) : 0; // X' | |
this.gamma = this.deviceOrientation.gamma ? | |
THREE.Math.degToRad(this.deviceOrientation.gamma) : 0; // Y'' | |
this.orient = this.screenOrientation ? | |
THREE.Math.degToRad(this.screenOrientation) : 0; // O | |
// The angles alpha, beta and gamma | |
// form a set of intrinsic Tait-Bryan angles of type Z-X'-Y'' | |
// 'ZXY' for the device, but 'YXZ' for us | |
euler.set(this.beta, this.alpha, - this.gamma, 'YXZ'); | |
quaternion.setFromEuler(euler); | |
quaternionLerp.slerp(quaternion, 0.5); // interpolate | |
// orient the device | |
if (this.autoAlign) this.orientationQuaternion.copy(quaternion); // interpolation breaks the auto alignment | |
else this.orientationQuaternion.copy(quaternionLerp); | |
// camera looks out the back of the device, not the top | |
this.orientationQuaternion.multiply(q1); | |
// adjust for screen orientation | |
this.orientationQuaternion.multiply(q0.setFromAxisAngle(zee, - this.orient)); | |
this.object.quaternion.copy(this.alignQuaternion); | |
this.object.quaternion.multiply(this.orientationQuaternion); | |
if (this.autoForward) { | |
tempVector3 | |
.set(0, 0, -1) | |
.applyQuaternion(this.object.quaternion, 'ZXY') | |
.setLength(this.movementSpeed / 50); // TODO: why 50 :S | |
this.object.position.add(tempVector3); | |
} | |
if (this.autoAlign && this.alpha !== 0) { | |
this.autoAlign = false; | |
this.align(); | |
} | |
}; | |
}(); | |
// //debug | |
// window.addEventListener('click', (function(){ | |
// this.align(); | |
// }).bind(this)); | |
this.align = function() { | |
tempVector3 | |
.set(0, 0, -1) | |
.applyQuaternion( tempQuaternion.copy(this.orientationQuaternion).inverse(), 'ZXY' ); | |
tempEuler.setFromQuaternion( | |
tempQuaternion.setFromRotationMatrix( | |
tempMatrix4.lookAt(tempVector3, v0, up) | |
) | |
); | |
tempEuler.set(0, tempEuler.y, 0); | |
this.alignQuaternion.setFromEuler(tempEuler); | |
}; | |
this.connect = function() { | |
// run once on load | |
this.onScreenOrientationChangeEvent(); | |
// window.addEventListener('orientationchange', this.onScreenOrientationChangeEvent, false); | |
window.addEventListener('deviceorientation', this.onDeviceOrientationChangeEvent, false); | |
this.freeze = false; | |
return this; | |
}; | |
this.disconnect = function() { | |
this.freeze = true; | |
// window.removeEventListener('orientationchange', this.onScreenOrientationChangeEvent, false); | |
window.removeEventListener('deviceorientation', this.onDeviceOrientationChangeEvent, false); | |
}; | |
}; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html class="no-js"> | |
<head> | |
<meta charset="utf-8"> | |
<title></title> | |
<meta name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1,initial-scale=1,user-scalable=no"> | |
<link rel="stylesheet" href="leaflet.css"> | |
<style> | |
html {-webkit-perspective:250;} | |
html, body {width:100%; height:100%; position:relative;} | |
body, body * {-webkit-transform-style:preserve-3d;} | |
body {margin:0; outline:1px solid black;} | |
#map {width:100vw;height:100vh;} | |
</style> | |
</head> | |
<body> | |
<div id="scene"> | |
<div id="camera"> | |
<div id="map"></div> | |
</div> | |
</div> | |
<script src="jquery-2.1.1.js"></script> | |
<script src="leaflet-src.js"></script> | |
<script src="three.js"></script> | |
<script src="CSS3DRenderer.js"></script> | |
<script src="OrbitControls.js"></script> | |
<script src="DeviceOrientationControls.js"></script> | |
<script src="dat.gui.js"></script> | |
<script> | |
var $scene = $('#scene'); | |
var $camera = $('#camera'); | |
var $window = $(window); | |
var $map = $('#map'); | |
var map; | |
(function () { | |
map = L.map('map').setView([51.505, -0.09], 13); | |
window.map = map; | |
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map); | |
}).call(this); | |
(function () { | |
var WW; | |
function setWW() { | |
WW = $window.width(); | |
} | |
setWW(); | |
$window.resize(setWW); | |
var WH = $window.height(); | |
function setWH() { | |
WH = $window.height(); | |
} | |
setWH(); | |
$window.resize(setWH); | |
var clock = new THREE.Clock(); | |
camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700); | |
camera.position.set(0, 50, 0); | |
//camera.up.set(0, 1, 0); | |
var renderer = new THREE.CSS3DRenderer($scene[0], $camera[0]); | |
//renderer.domElement.style.position = 'absolute'; | |
controls = new THREE.OrbitControls(camera, renderer.domElement); | |
controls.rotateUp(Math.PI / 4); | |
controls.rotateLeft(-Math.PI/2); | |
controls.target.set( | |
camera.position.x + 0.1, | |
camera.position.y, | |
camera.position.z | |
); | |
controls.noZoom = true; | |
controls.noPan = true; | |
function setOrientationControls(e) { | |
console.log('setOrientationControls', e); | |
if (!e.alpha) { | |
return; | |
} | |
controls = new THREE.DeviceOrientationControls(camera, true); | |
controls.connect(); | |
controls.update(); | |
//element.addEventListener('click', fullscreen, false); | |
window.removeEventListener('deviceorientation', setOrientationControls); | |
} | |
window.addEventListener('deviceorientation', setOrientationControls, true); | |
var scene = new THREE.Scene(); | |
var mapObj = new THREE.CSS3DObject($map[0]); | |
mapObj.position.set(0,0,0); | |
mapObj.rotation.x = -Math.PI/2; | |
scene.add(mapObj); | |
function resize() { | |
camera.aspect = WW/WH; | |
camera.updateProjectionMatrix(); | |
renderer.setSize(WW, WH); | |
} | |
window.addEventListener('resize', resize, false); | |
setTimeout(resize, 1); | |
function update(dt) { | |
resize(); | |
camera.updateProjectionMatrix(); | |
controls.update(dt); | |
} | |
function render(dt) { | |
renderer.render(scene, camera); | |
} | |
function animate(t) { | |
requestAnimationFrame(animate); | |
update(clock.getDelta()); | |
render(clock.getDelta()); | |
} | |
animate(); | |
var gui = new dat.GUI(); | |
var f1 = gui.addFolder('camera.position'); | |
f1.add(camera.position, 'x', -1000, 1000); | |
f1.add(camera.position, 'y', -1000, 1000); | |
f1.add(camera.position, 'z', -500, 500); | |
var f2 = gui.addFolder('camera.rotation'); | |
f2.add(camera.rotation, 'x', 0, 2*Math.PI); | |
f2.add(camera.rotation, 'y', 0, 2*Math.PI); | |
f2.add(camera.rotation, 'z', 0, 2*Math.PI); | |
}).call(this); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* jQuery JavaScript Library v2.1.1 | |
* http://jquery.com/ | |
* | |
* Includes Sizzle.js | |
* http://sizzlejs.com/ | |
* | |
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors | |
* Released under the MIT license | |
* http://jquery.org/license | |
* | |
* Date: 2014-05-01T17:11Z | |
*/ | |
(function( global, factory ) { | |
if ( typeof module === "object" && typeof module.exports === "object" ) { | |
// For CommonJS and CommonJS-like environments where a proper window is present, | |
// execute the factory and get jQuery | |
// For environments that do not inherently posses a window with a document | |
// (such as Node.js), expose a jQuery-making factory as module.exports | |
// This accentuates the need for the creation of a real window | |
// e.g. var jQuery = require("jquery")(window); | |
// See ticket #14549 for more info | |
module.exports = global.document ? | |
factory( global, true ) : | |
function( w ) { | |
if ( !w.document ) { | |
throw new Error( "jQuery requires a window with a document" ); | |
} | |
return factory( w ); | |
}; | |
} else { | |
factory( global ); | |
} | |
// Pass this if window is not defined yet | |
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { | |
// Can't do this because several apps including ASP.NET trace | |
// the stack via arguments.caller.callee and Firefox dies if | |
// you try to trace through "use strict" call chains. (#13335) | |
// Support: Firefox 18+ | |
// | |
var arr = []; | |
var slice = arr.slice; | |
var concat = arr.concat; | |
var push = arr.push; | |
var indexOf = arr.indexOf; | |
var class2type = {}; | |
var toString = class2type.toString; | |
var hasOwn = class2type.hasOwnProperty; | |
var support = {}; | |
var | |
// Use the correct document accordingly with window argument (sandbox) | |
document = window.document, | |
version = "2.1.1", | |
// Define a local copy of jQuery | |
jQuery = function( selector, context ) { | |
// The jQuery object is actually just the init constructor 'enhanced' | |
// Need init if jQuery is called (just allow error to be thrown if not included) | |
return new jQuery.fn.init( selector, context ); | |
}, | |
// Support: Android<4.1 | |
// Make sure we trim BOM and NBSP | |
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, | |
// Matches dashed string for camelizing | |
rmsPrefix = /^-ms-/, | |
rdashAlpha = /-([\da-z])/gi, | |
// Used by jQuery.camelCase as callback to replace() | |
fcamelCase = function( all, letter ) { | |
return letter.toUpperCase(); | |
}; | |
jQuery.fn = jQuery.prototype = { | |
// The current version of jQuery being used | |
jquery: version, | |
constructor: jQuery, | |
// Start with an empty selector | |
selector: "", | |
// The default length of a jQuery object is 0 | |
length: 0, | |
toArray: function() { | |
return slice.call( this ); | |
}, | |
// Get the Nth element in the matched element set OR | |
// Get the whole matched element set as a clean array | |
get: function( num ) { | |
return num != null ? | |
// Return just the one element from the set | |
( num < 0 ? this[ num + this.length ] : this[ num ] ) : | |
// Return all the elements in a clean array | |
slice.call( this ); | |
}, | |
// Take an array of elements and push it onto the stack | |
// (returning the new matched element set) | |
pushStack: function( elems ) { | |
// Build a new jQuery matched element set | |
var ret = jQuery.merge( this.constructor(), elems ); | |
// Add the old object onto the stack (as a reference) | |
ret.prevObject = this; | |
ret.context = this.context; | |
// Return the newly-formed element set | |
return ret; | |
}, | |
// Execute a callback for every element in the matched set. | |
// (You can seed the arguments with an array of args, but this is | |
// only used internally.) | |
each: function( callback, args ) { | |
return jQuery.each( this, callback, args ); | |
}, | |
map: function( callback ) { | |
return this.pushStack( jQuery.map(this, function( elem, i ) { | |
return callback.call( elem, i, elem ); | |
})); | |
}, | |
slice: function() { | |
return this.pushStack( slice.apply( this, arguments ) ); | |
}, | |
first: function() { | |
return this.eq( 0 ); | |
}, | |
last: function() { | |
return this.eq( -1 ); | |
}, | |
eq: function( i ) { | |
var len = this.length, | |
j = +i + ( i < 0 ? len : 0 ); | |
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); | |
}, | |
end: function() { | |
return this.prevObject || this.constructor(null); | |
}, | |
// For internal use only. | |
// Behaves like an Array's method, not like a jQuery method. | |
push: push, | |
sort: arr.sort, | |
splice: arr.splice | |
}; | |
jQuery.extend = jQuery.fn.extend = function() { | |
var options, name, src, copy, copyIsArray, clone, | |
target = arguments[0] || {}, | |
i = 1, | |
length = arguments.length, | |
deep = false; | |
// Handle a deep copy situation | |
if ( typeof target === "boolean" ) { | |
deep = target; | |
// skip the boolean and the target | |
target = arguments[ i ] || {}; | |
i++; | |
} | |
// Handle case when target is a string or something (possible in deep copy) | |
if ( typeof target !== "object" && !jQuery.isFunction(target) ) { | |
target = {}; | |
} | |
// extend jQuery itself if only one argument is passed | |
if ( i === length ) { | |
target = this; | |
i--; | |
} | |
for ( ; i < length; i++ ) { | |
// Only deal with non-null/undefined values | |
if ( (options = arguments[ i ]) != null ) { | |
// Extend the base object | |
for ( name in options ) { | |
src = target[ name ]; | |
copy = options[ name ]; | |
// Prevent never-ending loop | |
if ( target === copy ) { | |
continue; | |
} | |
// Recurse if we're merging plain objects or arrays | |
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { | |
if ( copyIsArray ) { | |
copyIsArray = false; | |
clone = src && jQuery.isArray(src) ? src : []; | |
} else { | |
clone = src && jQuery.isPlainObject(src) ? src : {}; | |
} | |
// Never move original objects, clone them | |
target[ name ] = jQuery.extend( deep, clone, copy ); | |
// Don't bring in undefined values | |
} else if ( copy !== undefined ) { | |
target[ name ] = copy; | |
} | |
} | |
} | |
} | |
// Return the modified object | |
return target; | |
}; | |
jQuery.extend({ | |
// Unique for each copy of jQuery on the page | |
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), | |
// Assume jQuery is ready without the ready module | |
isReady: true, | |
error: function( msg ) { | |
throw new Error( msg ); | |
}, | |
noop: function() {}, | |
// See test/unit/core.js for details concerning isFunction. | |
// Since version 1.3, DOM methods and functions like alert | |
// aren't supported. They return false on IE (#2968). | |
isFunction: function( obj ) { | |
return jQuery.type(obj) === "function"; | |
}, | |
isArray: Array.isArray, | |
isWindow: function( obj ) { | |
return obj != null && obj === obj.window; | |
}, | |
isNumeric: function( obj ) { | |
// parseFloat NaNs numeric-cast false positives (null|true|false|"") | |
// ...but misinterprets leading-number strings, particularly hex literals ("0x...") | |
// subtraction forces infinities to NaN | |
return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; | |
}, | |
isPlainObject: function( obj ) { | |
// Not plain objects: | |
// - Any object or value whose internal [[Class]] property is not "[object Object]" | |
// - DOM nodes | |
// - window | |
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { | |
return false; | |
} | |
if ( obj.constructor && | |
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { | |
return false; | |
} | |
// If the function hasn't returned already, we're confident that | |
// |obj| is a plain object, created by {} or constructed with new Object | |
return true; | |
}, | |
isEmptyObject: function( obj ) { | |
var name; | |
for ( name in obj ) { | |
return false; | |
} | |
return true; | |
}, | |
type: function( obj ) { | |
if ( obj == null ) { | |
return obj + ""; | |
} | |
// Support: Android < 4.0, iOS < 6 (functionish RegExp) | |
return typeof obj === "object" || typeof obj === "function" ? | |
class2type[ toString.call(obj) ] || "object" : | |
typeof obj; | |
}, | |
// Evaluates a script in a global context | |
globalEval: function( code ) { | |
var script, | |
indirect = eval; | |
code = jQuery.trim( code ); | |
if ( code ) { | |
// If the code includes a valid, prologue position | |
// strict mode pragma, execute code by injecting a | |
// script tag into the document. | |
if ( code.indexOf("use strict") === 1 ) { | |
script = document.createElement("script"); | |
script.text = code; | |
document.head.appendChild( script ).parentNode.removeChild( script ); | |
} else { | |
// Otherwise, avoid the DOM node creation, insertion | |
// and removal by using an indirect global eval | |
indirect( code ); | |
} | |
} | |
}, | |
// Convert dashed to camelCase; used by the css and data modules | |
// Microsoft forgot to hump their vendor prefix (#9572) | |
camelCase: function( string ) { | |
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); | |
}, | |
nodeName: function( elem, name ) { | |
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); | |
}, | |
// args is for internal usage only | |
each: function( obj, callback, args ) { | |
var value, | |
i = 0, | |
length = obj.length, | |
isArray = isArraylike( obj ); | |
if ( args ) { | |
if ( isArray ) { | |
for ( ; i < length; i++ ) { | |
value = callback.apply( obj[ i ], args ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} else { | |
for ( i in obj ) { | |
value = callback.apply( obj[ i ], args ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} | |
// A special, fast, case for the most common use of each | |
} else { | |
if ( isArray ) { | |
for ( ; i < length; i++ ) { | |
value = callback.call( obj[ i ], i, obj[ i ] ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} else { | |
for ( i in obj ) { | |
value = callback.call( obj[ i ], i, obj[ i ] ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} | |
} | |
return obj; | |
}, | |
// Support: Android<4.1 | |
trim: function( text ) { | |
return text == null ? | |
"" : | |
( text + "" ).replace( rtrim, "" ); | |
}, | |
// results is for internal usage only | |
makeArray: function( arr, results ) { | |
var ret = results || []; | |
if ( arr != null ) { | |
if ( isArraylike( Object(arr) ) ) { | |
jQuery.merge( ret, | |
typeof arr === "string" ? | |
[ arr ] : arr | |
); | |
} else { | |
push.call( ret, arr ); | |
} | |
} | |
return ret; | |
}, | |
inArray: function( elem, arr, i ) { | |
return arr == null ? -1 : indexOf.call( arr, elem, i ); | |
}, | |
merge: function( first, second ) { | |
var len = +second.length, | |
j = 0, | |
i = first.length; | |
for ( ; j < len; j++ ) { | |
first[ i++ ] = second[ j ]; | |
} | |
first.length = i; | |
return first; | |
}, | |
grep: function( elems, callback, invert ) { | |
var callbackInverse, | |
matches = [], | |
i = 0, | |
length = elems.length, | |
callbackExpect = !invert; | |
// Go through the array, only saving the items | |
// that pass the validator function | |
for ( ; i < length; i++ ) { | |
callbackInverse = !callback( elems[ i ], i ); | |
if ( callbackInverse !== callbackExpect ) { | |
matches.push( elems[ i ] ); | |
} | |
} | |
return matches; | |
}, | |
// arg is for internal usage only | |
map: function( elems, callback, arg ) { | |
var value, | |
i = 0, | |
length = elems.length, | |
isArray = isArraylike( elems ), | |
ret = []; | |
// Go through the array, translating each of the items to their new values | |
if ( isArray ) { | |
for ( ; i < length; i++ ) { | |
value = callback( elems[ i ], i, arg ); | |
if ( value != null ) { | |
ret.push( value ); | |
} | |
} | |
// Go through every key on the object, | |
} else { | |
for ( i in elems ) { | |
value = callback( elems[ i ], i, arg ); | |
if ( value != null ) { | |
ret.push( value ); | |
} | |
} | |
} | |
// Flatten any nested arrays | |
return concat.apply( [], ret ); | |
}, | |
// A global GUID counter for objects | |
guid: 1, | |
// Bind a function to a context, optionally partially applying any | |
// arguments. | |
proxy: function( fn, context ) { | |
var tmp, args, proxy; | |
if ( typeof context === "string" ) { | |
tmp = fn[ context ]; | |
context = fn; | |
fn = tmp; | |
} | |
// Quick check to determine if target is callable, in the spec | |
// this throws a TypeError, but we will just return undefined. | |
if ( !jQuery.isFunction( fn ) ) { | |
return undefined; | |
} | |
// Simulated bind | |
args = slice.call( arguments, 2 ); | |
proxy = function() { | |
return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); | |
}; | |
// Set the guid of unique handler to the same of original handler, so it can be removed | |
proxy.guid = fn.guid = fn.guid || jQuery.guid++; | |
return proxy; | |
}, | |
now: Date.now, | |
// jQuery.support is not used in Core but other projects attach their | |
// properties to it so it needs to exist. | |
support: support | |
}); | |
// Populate the class2type map | |
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { | |
class2type[ "[object " + name + "]" ] = name.toLowerCase(); | |
}); | |
function isArraylike( obj ) { | |
var length = obj.length, | |
type = jQuery.type( obj ); | |
if ( type === "function" || jQuery.isWindow( obj ) ) { | |
return false; | |
} | |
if ( obj.nodeType === 1 && length ) { | |
return true; | |
} | |
return type === "array" || length === 0 || | |
typeof length === "number" && length > 0 && ( length - 1 ) in obj; | |
} | |
var Sizzle = | |
/*! | |
* Sizzle CSS Selector Engine v1.10.19 | |
* http://sizzlejs.com/ | |
* | |
* Copyright 2013 jQuery Foundation, Inc. and other contributors | |
* Released under the MIT license | |
* http://jquery.org/license | |
* | |
* Date: 2014-04-18 | |
*/ | |
(function( window ) { | |
var i, | |
support, | |
Expr, | |
getText, | |
isXML, | |
tokenize, | |
compile, | |
select, | |
outermostContext, | |
sortInput, | |
hasDuplicate, | |
// Local document vars | |
setDocument, | |
document, | |
docElem, | |
documentIsHTML, | |
rbuggyQSA, | |
rbuggyMatches, | |
matches, | |
contains, | |
// Instance-specific data | |
expando = "sizzle" + -(new Date()), | |
preferredDoc = window.document, | |
dirruns = 0, | |
done = 0, | |
classCache = createCache(), | |
tokenCache = createCache(), | |
compilerCache = createCache(), | |
sortOrder = function( a, b ) { | |
if ( a === b ) { | |
hasDuplicate = true; | |
} | |
return 0; | |
}, | |
// General-purpose constants | |
strundefined = typeof undefined, | |
MAX_NEGATIVE = 1 << 31, | |
// Instance methods | |
hasOwn = ({}).hasOwnProperty, | |
arr = [], | |
pop = arr.pop, | |
push_native = arr.push, | |
push = arr.push, | |
slice = arr.slice, | |
// Use a stripped-down indexOf if we can't use a native one | |
indexOf = arr.indexOf || function( elem ) { | |
var i = 0, | |
len = this.length; | |
for ( ; i < len; i++ ) { | |
if ( this[i] === elem ) { | |
return i; | |
} | |
} | |
return -1; | |
}, | |
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", | |
// Regular expressions | |
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace | |
whitespace = "[\\x20\\t\\r\\n\\f]", | |
// http://www.w3.org/TR/css3-syntax/#characters | |
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", | |
// Loosely modeled on CSS identifier characters | |
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors | |
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier | |
identifier = characterEncoding.replace( "w", "w#" ), | |
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors | |
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + | |
// Operator (capture 2) | |
"*([*^$|!~]?=)" + whitespace + | |
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" | |
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + | |
"*\\]", | |
pseudos = ":(" + characterEncoding + ")(?:\\((" + | |
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: | |
// 1. quoted (capture 3; capture 4 or capture 5) | |
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + | |
// 2. simple (capture 6) | |
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + | |
// 3. anything else (capture 2) | |
".*" + | |
")\\)|)", | |
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter | |
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), | |
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), | |
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), | |
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), | |
rpseudo = new RegExp( pseudos ), | |
ridentifier = new RegExp( "^" + identifier + "$" ), | |
matchExpr = { | |
"ID": new RegExp( "^#(" + characterEncoding + ")" ), | |
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), | |
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), | |
"ATTR": new RegExp( "^" + attributes ), | |
"PSEUDO": new RegExp( "^" + pseudos ), | |
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + | |
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + | |
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ), | |
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ), | |
// For use in libraries implementing .is() | |
// We use this for POS matching in `select` | |
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + | |
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) | |
}, | |
rinputs = /^(?:input|select|textarea|button)$/i, | |
rheader = /^h\d$/i, | |
rnative = /^[^{]+\{\s*\[native \w/, | |
// Easily-parseable/retrievable ID or TAG or CLASS selectors | |
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, | |
rsibling = /[+~]/, | |
rescape = /'|\\/g, | |
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters | |
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), | |
funescape = function( _, escaped, escapedWhitespace ) { | |
var high = "0x" + escaped - 0x10000; | |
// NaN means non-codepoint | |
// Support: Firefox<24 | |
// Workaround erroneous numeric interpretation of +"0x" | |
return high !== high || escapedWhitespace ? | |
escaped : | |
high < 0 ? | |
// BMP codepoint | |
String.fromCharCode( high + 0x10000 ) : | |
// Supplemental Plane codepoint (surrogate pair) | |
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); | |
}; | |
// Optimize for push.apply( _, NodeList ) | |
try { | |
push.apply( | |
(arr = slice.call( preferredDoc.childNodes )), | |
preferredDoc.childNodes | |
); | |
// Support: Android<4.0 | |
// Detect silently failing push.apply | |
arr[ preferredDoc.childNodes.length ].nodeType; | |
} catch ( e ) { | |
push = { apply: arr.length ? | |
// Leverage slice if possible | |
function( target, els ) { | |
push_native.apply( target, slice.call(els) ); | |
} : | |
// Support: IE<9 | |
// Otherwise append directly | |
function( target, els ) { | |
var j = target.length, | |
i = 0; | |
// Can't trust NodeList.length | |
while ( (target[j++] = els[i++]) ) {} | |
target.length = j - 1; | |
} | |
}; | |
} | |
function Sizzle( selector, context, results, seed ) { | |
var match, elem, m, nodeType, | |
// QSA vars | |
i, groups, old, nid, newContext, newSelector; | |
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { | |
setDocument( context ); | |
} | |
context = context || document; | |
results = results || []; | |
if ( !selector || typeof selector !== "string" ) { | |
return results; | |
} | |
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { | |
return []; | |
} | |
if ( documentIsHTML && !seed ) { | |
// Shortcuts | |
if ( (match = rquickExpr.exec( selector )) ) { | |
// Speed-up: Sizzle("#ID") | |
if ( (m = match[1]) ) { | |
if ( nodeType === 9 ) { | |
elem = context.getElementById( m ); | |
// Check parentNode to catch when Blackberry 4.6 returns | |
// nodes that are no longer in the document (jQuery #6963) | |
if ( elem && elem.parentNode ) { | |
// Handle the case where IE, Opera, and Webkit return items | |
// by name instead of ID | |
if ( elem.id === m ) { | |
results.push( elem ); | |
return results; | |
} | |
} else { | |
return results; | |
} | |
} else { | |
// Context is not a document | |
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && | |
contains( context, elem ) && elem.id === m ) { | |
results.push( elem ); | |
return results; | |
} | |
} | |
// Speed-up: Sizzle("TAG") | |
} else if ( match[2] ) { | |
push.apply( results, context.getElementsByTagName( selector ) ); | |
return results; | |
// Speed-up: Sizzle(".CLASS") | |
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { | |
push.apply( results, context.getElementsByClassName( m ) ); | |
return results; | |
} | |
} | |
// QSA path | |
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { | |
nid = old = expando; | |
newContext = context; | |
newSelector = nodeType === 9 && selector; | |
// qSA works strangely on Element-rooted queries | |
// We can work around this by specifying an extra ID on the root | |
// and working up from there (Thanks to Andrew Dupont for the technique) | |
// IE 8 doesn't work on object elements | |
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { | |
groups = tokenize( selector ); | |
if ( (old = context.getAttribute("id")) ) { | |
nid = old.replace( rescape, "\\$&" ); | |
} else { | |
context.setAttribute( "id", nid ); | |
} | |
nid = "[id='" + nid + "'] "; | |
i = groups.length; | |
while ( i-- ) { | |
groups[i] = nid + toSelector( groups[i] ); | |
} | |
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; | |
newSelector = groups.join(","); | |
} | |
if ( newSelector ) { | |
try { | |
push.apply( results, | |
newContext.querySelectorAll( newSelector ) | |
); | |
return results; | |
} catch(qsaError) { | |
} finally { | |
if ( !old ) { | |
context.removeAttribute("id"); | |
} | |
} | |
} | |
} | |
} | |
// All others | |
return select( selector.replace( rtrim, "$1" ), context, results, seed ); | |
} | |
/** | |
* Create key-value caches of limited size | |
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with | |
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) | |
* deleting the oldest entry | |
*/ | |
function createCache() { | |
var keys = []; | |
function cache( key, value ) { | |
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157) | |
if ( keys.push( key + " " ) > Expr.cacheLength ) { | |
// Only keep the most recent entries | |
delete cache[ keys.shift() ]; | |
} | |
return (cache[ key + " " ] = value); | |
} | |
return cache; | |
} | |
/** | |
* Mark a function for special use by Sizzle | |
* @param {Function} fn The function to mark | |
*/ | |
function markFunction( fn ) { | |
fn[ expando ] = true; | |
return fn; | |
} | |
/** | |
* Support testing using an element | |
* @param {Function} fn Passed the created div and expects a boolean result | |
*/ | |
function assert( fn ) { | |
var div = document.createElement("div"); | |
try { | |
return !!fn( div ); | |
} catch (e) { | |
return false; | |
} finally { | |
// Remove from its parent by default | |
if ( div.parentNode ) { | |
div.parentNode.removeChild( div ); | |
} | |
// release memory in IE | |
div = null; | |
} | |
} | |
/** | |
* Adds the same handler for all of the specified attrs | |
* @param {String} attrs Pipe-separated list of attributes | |
* @param {Function} handler The method that will be applied | |
*/ | |
function addHandle( attrs, handler ) { | |
var arr = attrs.split("|"), | |
i = attrs.length; | |
while ( i-- ) { | |
Expr.attrHandle[ arr[i] ] = handler; | |
} | |
} | |
/** | |
* Checks document order of two siblings | |
* @param {Element} a | |
* @param {Element} b | |
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b | |
*/ | |
function siblingCheck( a, b ) { | |
var cur = b && a, | |
diff = cur && a.nodeType === 1 && b.nodeType === 1 && | |
( ~b.sourceIndex || MAX_NEGATIVE ) - | |
( ~a.sourceIndex || MAX_NEGATIVE ); | |
// Use IE sourceIndex if available on both nodes | |
if ( diff ) { | |
return diff; | |
} | |
// Check if b follows a | |
if ( cur ) { | |
while ( (cur = cur.nextSibling) ) { | |
if ( cur === b ) { | |
return -1; | |
} | |
} | |
} | |
return a ? 1 : -1; | |
} | |
/** | |
* Returns a function to use in pseudos for input types | |
* @param {String} type | |
*/ | |
function createInputPseudo( type ) { | |
return function( elem ) { | |
var name = elem.nodeName.toLowerCase(); | |
return name === "input" && elem.type === type; | |
}; | |
} | |
/** | |
* Returns a function to use in pseudos for buttons | |
* @param {String} type | |
*/ | |
function createButtonPseudo( type ) { | |
return function( elem ) { | |
var name = elem.nodeName.toLowerCase(); | |
return (name === "input" || name === "button") && elem.type === type; | |
}; | |
} | |
/** | |
* Returns a function to use in pseudos for positionals | |
* @param {Function} fn | |
*/ | |
function createPositionalPseudo( fn ) { | |
return markFunction(function( argument ) { | |
argument = +argument; | |
return markFunction(function( seed, matches ) { | |
var j, | |
matchIndexes = fn( [], seed.length, argument ), | |
i = matchIndexes.length; | |
// Match elements found at the specified indexes | |
while ( i-- ) { | |
if ( seed[ (j = matchIndexes[i]) ] ) { | |
seed[j] = !(matches[j] = seed[j]); | |
} | |
} | |
}); | |
}); | |
} | |
/** | |
* Checks a node for validity as a Sizzle context | |
* @param {Element|Object=} context | |
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value | |
*/ | |
function testContext( context ) { | |
return context && typeof context.getElementsByTagName !== strundefined && context; | |
} | |
// Expose support vars for convenience | |
support = Sizzle.support = {}; | |
/** | |
* Detects XML nodes | |
* @param {Element|Object} elem An element or a document | |
* @returns {Boolean} True iff elem is a non-HTML XML node | |
*/ | |
isXML = Sizzle.isXML = function( elem ) { | |
// documentElement is verified for cases where it doesn't yet exist | |
// (such as loading iframes in IE - #4833) | |
var documentElement = elem && (elem.ownerDocument || elem).documentElement; | |
return documentElement ? documentElement.nodeName !== "HTML" : false; | |
}; | |
/** | |
* Sets document-related variables once based on the current document | |
* @param {Element|Object} [doc] An element or document object to use to set the document | |
* @returns {Object} Returns the current document | |
*/ | |
setDocument = Sizzle.setDocument = function( node ) { | |
var hasCompare, | |
doc = node ? node.ownerDocument || node : preferredDoc, | |
parent = doc.defaultView; | |
// If no document and documentElement is available, return | |
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { | |
return document; | |
} | |
// Set our document | |
document = doc; | |
docElem = doc.documentElement; | |
// Support tests | |
documentIsHTML = !isXML( doc ); | |
// Support: IE>8 | |
// If iframe document is assigned to "document" variable and if iframe has been reloaded, | |
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 | |
// IE6-8 do not support the defaultView property so parent will be undefined | |
if ( parent && parent !== parent.top ) { | |
// IE11 does not have attachEvent, so all must suffer | |
if ( parent.addEventListener ) { | |
parent.addEventListener( "unload", function() { | |
setDocument(); | |
}, false ); | |
} else if ( parent.attachEvent ) { | |
parent.attachEvent( "onunload", function() { | |
setDocument(); | |
}); | |
} | |
} | |
/* Attributes | |
---------------------------------------------------------------------- */ | |
// Support: IE<8 | |
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) | |
support.attributes = assert(function( div ) { | |
div.className = "i"; | |
return !div.getAttribute("className"); | |
}); | |
/* getElement(s)By* | |
---------------------------------------------------------------------- */ | |
// Check if getElementsByTagName("*") returns only elements | |
support.getElementsByTagName = assert(function( div ) { | |
div.appendChild( doc.createComment("") ); | |
return !div.getElementsByTagName("*").length; | |
}); | |
// Check if getElementsByClassName can be trusted | |
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { | |
div.innerHTML = "<div class='a'></div><div class='a i'></div>"; | |
// Support: Safari<4 | |
// Catch class over-caching | |
div.firstChild.className = "i"; | |
// Support: Opera<10 | |
// Catch gEBCN failure to find non-leading classes | |
return div.getElementsByClassName("i").length === 2; | |
}); | |
// Support: IE<10 | |
// Check if getElementById returns elements by name | |
// The broken getElementById methods don't pick up programatically-set names, | |
// so use a roundabout getElementsByName test | |
support.getById = assert(function( div ) { | |
docElem.appendChild( div ).id = expando; | |
return !doc.getElementsByName || !doc.getElementsByName( expando ).length; | |
}); | |
// ID find and filter | |
if ( support.getById ) { | |
Expr.find["ID"] = function( id, context ) { | |
if ( typeof context.getElementById !== strundefined && documentIsHTML ) { | |
var m = context.getElementById( id ); | |
// Check parentNode to catch when Blackberry 4.6 returns | |
// nodes that are no longer in the document #6963 | |
return m && m.parentNode ? [ m ] : []; | |
} | |
}; | |
Expr.filter["ID"] = function( id ) { | |
var attrId = id.replace( runescape, funescape ); | |
return function( elem ) { | |
return elem.getAttribute("id") === attrId; | |
}; | |
}; | |
} else { | |
// Support: IE6/7 | |
// getElementById is not reliable as a find shortcut | |
delete Expr.find["ID"]; | |
Expr.filter["ID"] = function( id ) { | |
var attrId = id.replace( runescape, funescape ); | |
return function( elem ) { | |
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); | |
return node && node.value === attrId; | |
}; | |
}; | |
} | |
// Tag | |
Expr.find["TAG"] = support.getElementsByTagName ? | |
function( tag, context ) { | |
if ( typeof context.getElementsByTagName !== strundefined ) { | |
return context.getElementsByTagName( tag ); | |
} | |
} : | |
function( tag, context ) { | |
var elem, | |
tmp = [], | |
i = 0, | |
results = context.getElementsByTagName( tag ); | |
// Filter out possible comments | |
if ( tag === "*" ) { | |
while ( (elem = results[i++]) ) { | |
if ( elem.nodeType === 1 ) { | |
tmp.push( elem ); | |
} | |
} | |
return tmp; | |
} | |
return results; | |
}; | |
// Class | |
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { | |
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { | |
return context.getElementsByClassName( className ); | |
} | |
}; | |
/* QSA/matchesSelector | |
---------------------------------------------------------------------- */ | |
// QSA and matchesSelector support | |
// matchesSelector(:active) reports false when true (IE9/Opera 11.5) | |
rbuggyMatches = []; | |
// qSa(:focus) reports false when true (Chrome 21) | |
// We allow this because of a bug in IE8/9 that throws an error | |
// whenever `document.activeElement` is accessed on an iframe | |
// So, we allow :focus to pass through QSA all the time to avoid the IE error | |
// See http://bugs.jquery.com/ticket/13378 | |
rbuggyQSA = []; | |
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { | |
// Build QSA regex | |
// Regex strategy adopted from Diego Perini | |
assert(function( div ) { | |
// Select is set to empty string on purpose | |
// This is to test IE's treatment of not explicitly | |
// setting a boolean content attribute, | |
// since its presence should be enough | |
// http://bugs.jquery.com/ticket/12359 | |
div.innerHTML = "<select msallowclip=''><option selected=''></option></select>"; | |
// Support: IE8, Opera 11-12.16 | |
// Nothing should be selected when empty strings follow ^= or $= or *= | |
// The test attribute must be unknown in Opera but "safe" for WinRT | |
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section | |
if ( div.querySelectorAll("[msallowclip^='']").length ) { | |
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); | |
} | |
// Support: IE8 | |
// Boolean attributes and "value" are not treated correctly | |
if ( !div.querySelectorAll("[selected]").length ) { | |
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); | |
} | |
// Webkit/Opera - :checked should return selected option elements | |
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked | |
// IE8 throws error here and will not see later tests | |
if ( !div.querySelectorAll(":checked").length ) { | |
rbuggyQSA.push(":checked"); | |
} | |
}); | |
assert(function( div ) { | |
// Support: Windows 8 Native Apps | |
// The type and name attributes are restricted during .innerHTML assignment | |
var input = doc.createElement("input"); | |
input.setAttribute( "type", "hidden" ); | |
div.appendChild( input ).setAttribute( "name", "D" ); | |
// Support: IE8 | |
// Enforce case-sensitivity of name attribute | |
if ( div.querySelectorAll("[name=d]").length ) { | |
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); | |
} | |
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) | |
// IE8 throws error here and will not see later tests | |
if ( !div.querySelectorAll(":enabled").length ) { | |
rbuggyQSA.push( ":enabled", ":disabled" ); | |
} | |
// Opera 10-11 does not throw on post-comma invalid pseudos | |
div.querySelectorAll("*,:x"); | |
rbuggyQSA.push(",.*:"); | |
}); | |
} | |
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || | |
docElem.webkitMatchesSelector || | |
docElem.mozMatchesSelector || | |
docElem.oMatchesSelector || | |
docElem.msMatchesSelector) )) ) { | |
assert(function( div ) { | |
// Check to see if it's possible to do matchesSelector | |
// on a disconnected node (IE 9) | |
support.disconnectedMatch = matches.call( div, "div" ); | |
// This should fail with an exception | |
// Gecko does not error, returns false instead | |
matches.call( div, "[s!='']:x" ); | |
rbuggyMatches.push( "!=", pseudos ); | |
}); | |
} | |
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); | |
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); | |
/* Contains | |
---------------------------------------------------------------------- */ | |
hasCompare = rnative.test( docElem.compareDocumentPosition ); | |
// Element contains another | |
// Purposefully does not implement inclusive descendent | |
// As in, an element does not contain itself | |
contains = hasCompare || rnative.test( docElem.contains ) ? | |
function( a, b ) { | |
var adown = a.nodeType === 9 ? a.documentElement : a, | |
bup = b && b.parentNode; | |
return a === bup || !!( bup && bup.nodeType === 1 && ( | |
adown.contains ? | |
adown.contains( bup ) : | |
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 | |
)); | |
} : | |
function( a, b ) { | |
if ( b ) { | |
while ( (b = b.parentNode) ) { | |
if ( b === a ) { | |
return true; | |
} | |
} | |
} | |
return false; | |
}; | |
/* Sorting | |
---------------------------------------------------------------------- */ | |
// Document order sorting | |
sortOrder = hasCompare ? | |
function( a, b ) { | |
// Flag for duplicate removal | |
if ( a === b ) { | |
hasDuplicate = true; | |
return 0; | |
} | |
// Sort on method existence if only one input has compareDocumentPosition | |
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; | |
if ( compare ) { | |
return compare; | |
} | |
// Calculate position if both inputs belong to the same document | |
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? | |
a.compareDocumentPosition( b ) : | |
// Otherwise we know they are disconnected | |
1; | |
// Disconnected nodes | |
if ( compare & 1 || | |
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { | |
// Choose the first element that is related to our preferred document | |
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { | |
return -1; | |
} | |
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { | |
return 1; | |
} | |
// Maintain original order | |
return sortInput ? | |
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : | |
0; | |
} | |
return compare & 4 ? -1 : 1; | |
} : | |
function( a, b ) { | |
// Exit early if the nodes are identical | |
if ( a === b ) { | |
hasDuplicate = true; | |
return 0; | |
} | |
var cur, | |
i = 0, | |
aup = a.parentNode, | |
bup = b.parentNode, | |
ap = [ a ], | |
bp = [ b ]; | |
// Parentless nodes are either documents or disconnected | |
if ( !aup || !bup ) { | |
return a === doc ? -1 : | |
b === doc ? 1 : | |
aup ? -1 : | |
bup ? 1 : | |
sortInput ? | |
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : | |
0; | |
// If the nodes are siblings, we can do a quick check | |
} else if ( aup === bup ) { | |
return siblingCheck( a, b ); | |
} | |
// Otherwise we need full lists of their ancestors for comparison | |
cur = a; | |
while ( (cur = cur.parentNode) ) { | |
ap.unshift( cur ); | |
} | |
cur = b; | |
while ( (cur = cur.parentNode) ) { | |
bp.unshift( cur ); | |
} | |
// Walk down the tree looking for a discrepancy | |
while ( ap[i] === bp[i] ) { | |
i++; | |
} | |
return i ? | |
// Do a sibling check if the nodes have a common ancestor | |
siblingCheck( ap[i], bp[i] ) : | |
// Otherwise nodes in our document sort first | |
ap[i] === preferredDoc ? -1 : | |
bp[i] === preferredDoc ? 1 : | |
0; | |
}; | |
return doc; | |
}; | |
Sizzle.matches = function( expr, elements ) { | |
return Sizzle( expr, null, null, elements ); | |
}; | |
Sizzle.matchesSelector = function( elem, expr ) { | |
// Set document vars if needed | |
if ( ( elem.ownerDocument || elem ) !== document ) { | |
setDocument( elem ); | |
} | |
// Make sure that attribute selectors are quoted | |
expr = expr.replace( rattributeQuotes, "='$1']" ); | |
if ( support.matchesSelector && documentIsHTML && | |
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && | |
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { | |
try { | |
var ret = matches.call( elem, expr ); | |
// IE 9's matchesSelector returns false on disconnected nodes | |
if ( ret || support.disconnectedMatch || | |
// As well, disconnected nodes are said to be in a document | |
// fragment in IE 9 | |
elem.document && elem.document.nodeType !== 11 ) { | |
return ret; | |
} | |
} catch(e) {} | |
} | |
return Sizzle( expr, document, null, [ elem ] ).length > 0; | |
}; | |
Sizzle.contains = function( context, elem ) { | |
// Set document vars if needed | |
if ( ( context.ownerDocument || context ) !== document ) { | |
setDocument( context ); | |
} | |
return contains( context, elem ); | |
}; | |
Sizzle.attr = function( elem, name ) { | |
// Set document vars if needed | |
if ( ( elem.ownerDocument || elem ) !== document ) { | |
setDocument( elem ); | |
} | |
var fn = Expr.attrHandle[ name.toLowerCase() ], | |
// Don't get fooled by Object.prototype properties (jQuery #13807) | |
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? | |
fn( elem, name, !documentIsHTML ) : | |
undefined; | |
return val !== undefined ? | |
val : | |
support.attributes || !documentIsHTML ? | |
elem.getAttribute( name ) : | |
(val = elem.getAttributeNode(name)) && val.specified ? | |
val.value : | |
null; | |
}; | |
Sizzle.error = function( msg ) { | |
throw new Error( "Syntax error, unrecognized expression: " + msg ); | |
}; | |
/** | |
* Document sorting and removing duplicates | |
* @param {ArrayLike} results | |
*/ | |
Sizzle.uniqueSort = function( results ) { | |
var elem, | |
duplicates = [], | |
j = 0, | |
i = 0; | |
// Unless we *know* we can detect duplicates, assume their presence | |
hasDuplicate = !support.detectDuplicates; | |
sortInput = !support.sortStable && results.slice( 0 ); | |
results.sort( sortOrder ); | |
if ( hasDuplicate ) { | |
while ( (elem = results[i++]) ) { | |
if ( elem === results[ i ] ) { | |
j = duplicates.push( i ); | |
} | |
} | |
while ( j-- ) { | |
results.splice( duplicates[ j ], 1 ); | |
} | |
} | |
// Clear input after sorting to release objects | |
// See https://github.com/jquery/sizzle/pull/225 | |
sortInput = null; | |
return results; | |
}; | |
/** | |
* Utility function for retrieving the text value of an array of DOM nodes | |
* @param {Array|Element} elem | |
*/ | |
getText = Sizzle.getText = function( elem ) { | |
var node, | |
ret = "", | |
i = 0, | |
nodeType = elem.nodeType; | |
if ( !nodeType ) { | |
// If no nodeType, this is expected to be an array | |
while ( (node = elem[i++]) ) { | |
// Do not traverse comment nodes | |
ret += getText( node ); | |
} | |
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { | |
// Use textContent for elements | |
// innerText usage removed for consistency of new lines (jQuery #11153) | |
if ( typeof elem.textContent === "string" ) { | |
return elem.textContent; | |
} else { | |
// Traverse its children | |
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { | |
ret += getText( elem ); | |
} | |
} | |
} else if ( nodeType === 3 || nodeType === 4 ) { | |
return elem.nodeValue; | |
} | |
// Do not include comment or processing instruction nodes | |
return ret; | |
}; | |
Expr = Sizzle.selectors = { | |
// Can be adjusted by the user | |
cacheLength: 50, | |
createPseudo: markFunction, | |
match: matchExpr, | |
attrHandle: {}, | |
find: {}, | |
relative: { | |
">": { dir: "parentNode", first: true }, | |
" ": { dir: "parentNode" }, | |
"+": { dir: "previousSibling", first: true }, | |
"~": { dir: "previousSibling" } | |
}, | |
preFilter: { | |
"ATTR": function( match ) { | |
match[1] = match[1].replace( runescape, funescape ); | |
// Move the given value to match[3] whether quoted or unquoted | |
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); | |
if ( match[2] === "~=" ) { | |
match[3] = " " + match[3] + " "; | |
} | |
return match.slice( 0, 4 ); | |
}, | |
"CHILD": function( match ) { | |
/* matches from matchExpr["CHILD"] | |
1 type (only|nth|...) | |
2 what (child|of-type) | |
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) | |
4 xn-component of xn+y argument ([+-]?\d*n|) | |
5 sign of xn-component | |
6 x of xn-component | |
7 sign of y-component | |
8 y of y-component | |
*/ | |
match[1] = match[1].toLowerCase(); | |
if ( match[1].slice( 0, 3 ) === "nth" ) { | |
// nth-* requires argument | |
if ( !match[3] ) { | |
Sizzle.error( match[0] ); | |
} | |
// numeric x and y parameters for Expr.filter.CHILD | |
// remember that false/true cast respectively to 0/1 | |
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); | |
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); | |
// other types prohibit arguments | |
} else if ( match[3] ) { | |
Sizzle.error( match[0] ); | |
} | |
return match; | |
}, | |
"PSEUDO": function( match ) { | |
var excess, | |
unquoted = !match[6] && match[2]; | |
if ( matchExpr["CHILD"].test( match[0] ) ) { | |
return null; | |
} | |
// Accept quoted arguments as-is | |
if ( match[3] ) { | |
match[2] = match[4] || match[5] || ""; | |
// Strip excess characters from unquoted arguments | |
} else if ( unquoted && rpseudo.test( unquoted ) && | |
// Get excess from tokenize (recursively) | |
(excess = tokenize( unquoted, true )) && | |
// advance to the next closing parenthesis | |
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { | |
// excess is a negative index | |
match[0] = match[0].slice( 0, excess ); | |
match[2] = unquoted.slice( 0, excess ); | |
} | |
// Return only captures needed by the pseudo filter method (type and argument) | |
return match.slice( 0, 3 ); | |
} | |
}, | |
filter: { | |
"TAG": function( nodeNameSelector ) { | |
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); | |
return nodeNameSelector === "*" ? | |
function() { return true; } : | |
function( elem ) { | |
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; | |
}; | |
}, | |
"CLASS": function( className ) { | |
var pattern = classCache[ className + " " ]; | |
return pattern || | |
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && | |
classCache( className, function( elem ) { | |
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); | |
}); | |
}, | |
"ATTR": function( name, operator, check ) { | |
return function( elem ) { | |
var result = Sizzle.attr( elem, name ); | |
if ( result == null ) { | |
return operator === "!="; | |
} | |
if ( !operator ) { | |
return true; | |
} | |
result += ""; | |
return operator === "=" ? result === check : | |
operator === "!=" ? result !== check : | |
operator === "^=" ? check && result.indexOf( check ) === 0 : | |
operator === "*=" ? check && result.indexOf( check ) > -1 : | |
operator === "$=" ? check && result.slice( -check.length ) === check : | |
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : | |
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : | |
false; | |
}; | |
}, | |
"CHILD": function( type, what, argument, first, last ) { | |
var simple = type.slice( 0, 3 ) !== "nth", | |
forward = type.slice( -4 ) !== "last", | |
ofType = what === "of-type"; | |
return first === 1 && last === 0 ? | |
// Shortcut for :nth-*(n) | |
function( elem ) { | |
return !!elem.parentNode; | |
} : | |
function( elem, context, xml ) { | |
var cache, outerCache, node, diff, nodeIndex, start, | |
dir = simple !== forward ? "nextSibling" : "previousSibling", | |
parent = elem.parentNode, | |
name = ofType && elem.nodeName.toLowerCase(), | |
useCache = !xml && !ofType; | |
if ( parent ) { | |
// :(first|last|only)-(child|of-type) | |
if ( simple ) { | |
while ( dir ) { | |
node = elem; | |
while ( (node = node[ dir ]) ) { | |
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { | |
return false; | |
} | |
} | |
// Reverse direction for :only-* (if we haven't yet done so) | |
start = dir = type === "only" && !start && "nextSibling"; | |
} | |
return true; | |
} | |
start = [ forward ? parent.firstChild : parent.lastChild ]; | |
// non-xml :nth-child(...) stores cache data on `parent` | |
if ( forward && useCache ) { | |
// Seek `elem` from a previously-cached index | |
outerCache = parent[ expando ] || (parent[ expando ] = {}); | |
cache = outerCache[ type ] || []; | |
nodeIndex = cache[0] === dirruns && cache[1]; | |
diff = cache[0] === dirruns && cache[2]; | |
node = nodeIndex && parent.childNodes[ nodeIndex ]; | |
while ( (node = ++nodeIndex && node && node[ dir ] || | |
// Fallback to seeking `elem` from the start | |
(diff = nodeIndex = 0) || start.pop()) ) { | |
// When found, cache indexes on `parent` and break | |
if ( node.nodeType === 1 && ++diff && node === elem ) { | |
outerCache[ type ] = [ dirruns, nodeIndex, diff ]; | |
break; | |
} | |
} | |
// Use previously-cached element index if available | |
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { | |
diff = cache[1]; | |
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) | |
} else { | |
// Use the same loop as above to seek `elem` from the start | |
while ( (node = ++nodeIndex && node && node[ dir ] || | |
(diff = nodeIndex = 0) || start.pop()) ) { | |
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { | |
// Cache the index of each encountered element | |
if ( useCache ) { | |
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; | |
} | |
if ( node === elem ) { | |
break; | |
} | |
} | |
} | |
} | |
// Incorporate the offset, then check against cycle size | |
diff -= last; | |
return diff === first || ( diff % first === 0 && diff / first >= 0 ); | |
} | |
}; | |
}, | |
"PSEUDO": function( pseudo, argument ) { | |
// pseudo-class names are case-insensitive | |
// http://www.w3.org/TR/selectors/#pseudo-classes | |
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters | |
// Remember that setFilters inherits from pseudos | |
var args, | |
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || | |
Sizzle.error( "unsupported pseudo: " + pseudo ); | |
// The user may use createPseudo to indicate that | |
// arguments are needed to create the filter function | |
// just as Sizzle does | |
if ( fn[ expando ] ) { | |
return fn( argument ); | |
} | |
// But maintain support for old signatures | |
if ( fn.length > 1 ) { | |
args = [ pseudo, pseudo, "", argument ]; | |
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? | |
markFunction(function( seed, matches ) { | |
var idx, | |
matched = fn( seed, argument ), | |
i = matched.length; | |
while ( i-- ) { | |
idx = indexOf.call( seed, matched[i] ); | |
seed[ idx ] = !( matches[ idx ] = matched[i] ); | |
} | |
}) : | |
function( elem ) { | |
return fn( elem, 0, args ); | |
}; | |
} | |
return fn; | |
} | |
}, | |
pseudos: { | |
// Potentially complex pseudos | |
"not": markFunction(function( selector ) { | |
// Trim the selector passed to compile | |
// to avoid treating leading and trailing | |
// spaces as combinators | |
var input = [], | |
results = [], | |
matcher = compile( selector.replace( rtrim, "$1" ) ); | |
return matcher[ expando ] ? | |
markFunction(function( seed, matches, context, xml ) { | |
var elem, | |
unmatched = matcher( seed, null, xml, [] ), | |
i = seed.length; | |
// Match elements unmatched by `matcher` | |
while ( i-- ) { | |
if ( (elem = unmatched[i]) ) { | |
seed[i] = !(matches[i] = elem); | |
} | |
} | |
}) : | |
function( elem, context, xml ) { | |
input[0] = elem; | |
matcher( input, null, xml, results ); | |
return !results.pop(); | |
}; | |
}), | |
"has": markFunction(function( selector ) { | |
return function( elem ) { | |
return Sizzle( selector, elem ).length > 0; | |
}; | |
}), | |
"contains": markFunction(function( text ) { | |
return function( elem ) { | |
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; | |
}; | |
}), | |
// "Whether an element is represented by a :lang() selector | |
// is based solely on the element's language value | |
// being equal to the identifier C, | |
// or beginning with the identifier C immediately followed by "-". | |
// The matching of C against the element's language value is performed case-insensitively. | |
// The identifier C does not have to be a valid language name." | |
// http://www.w3.org/TR/selectors/#lang-pseudo | |
"lang": markFunction( function( lang ) { | |
// lang value must be a valid identifier | |
if ( !ridentifier.test(lang || "") ) { | |
Sizzle.error( "unsupported lang: " + lang ); | |
} | |
lang = lang.replace( runescape, funescape ).toLowerCase(); | |
return function( elem ) { | |
var elemLang; | |
do { | |
if ( (elemLang = documentIsHTML ? | |
elem.lang : | |
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { | |
elemLang = elemLang.toLowerCase(); | |
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; | |
} | |
} while ( (elem = elem.parentNode) && elem.nodeType === 1 ); | |
return false; | |
}; | |
}), | |
// Miscellaneous | |
"target": function( elem ) { | |
var hash = window.location && window.location.hash; | |
return hash && hash.slice( 1 ) === elem.id; | |
}, | |
"root": function( elem ) { | |
return elem === docElem; | |
}, | |
"focus": function( elem ) { | |
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); | |
}, | |
// Boolean properties | |
"enabled": function( elem ) { | |
return elem.disabled === false; | |
}, | |
"disabled": function( elem ) { | |
return elem.disabled === true; | |
}, | |
"checked": function( elem ) { | |
// In CSS3, :checked should return both checked and selected elements | |
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked | |
var nodeName = elem.nodeName.toLowerCase(); | |
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); | |
}, | |
"selected": function( elem ) { | |
// Accessing this property makes selected-by-default | |
// options in Safari work properly | |
if ( elem.parentNode ) { | |
elem.parentNode.selectedIndex; | |
} | |
return elem.selected === true; | |
}, | |
// Contents | |
"empty": function( elem ) { | |
// http://www.w3.org/TR/selectors/#empty-pseudo | |
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), | |
// but not by others (comment: 8; processing instruction: 7; etc.) | |
// nodeType < 6 works because attributes (2) do not appear as children | |
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { | |
if ( elem.nodeType < 6 ) { | |
return false; | |
} | |
} | |
return true; | |
}, | |
"parent": function( elem ) { | |
return !Expr.pseudos["empty"]( elem ); | |
}, | |
// Element/input types | |
"header": function( elem ) { | |
return rheader.test( elem.nodeName ); | |
}, | |
"input": function( elem ) { | |
return rinputs.test( elem.nodeName ); | |
}, | |
"button": function( elem ) { | |
var name = elem.nodeName.toLowerCase(); | |
return name === "input" && elem.type === "button" || name === "button"; | |
}, | |
"text": function( elem ) { | |
var attr; | |
return elem.nodeName.toLowerCase() === "input" && | |
elem.type === "text" && | |
// Support: IE<8 | |
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text" | |
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); | |
}, | |
// Position-in-collection | |
"first": createPositionalPseudo(function() { | |
return [ 0 ]; | |
}), | |
"last": createPositionalPseudo(function( matchIndexes, length ) { | |
return [ length - 1 ]; | |
}), | |
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) { | |
return [ argument < 0 ? argument + length : argument ]; | |
}), | |
"even": createPositionalPseudo(function( matchIndexes, length ) { | |
var i = 0; | |
for ( ; i < length; i += 2 ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}), | |
"odd": createPositionalPseudo(function( matchIndexes, length ) { | |
var i = 1; | |
for ( ; i < length; i += 2 ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}), | |
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) { | |
var i = argument < 0 ? argument + length : argument; | |
for ( ; --i >= 0; ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}), | |
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) { | |
var i = argument < 0 ? argument + length : argument; | |
for ( ; ++i < length; ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}) | |
} | |
}; | |
Expr.pseudos["nth"] = Expr.pseudos["eq"]; | |
// Add button/input type pseudos | |
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { | |
Expr.pseudos[ i ] = createInputPseudo( i ); | |
} | |
for ( i in { submit: true, reset: true } ) { | |
Expr.pseudos[ i ] = createButtonPseudo( i ); | |
} | |
// Easy API for creating new setFilters | |
function setFilters() {} | |
setFilters.prototype = Expr.filters = Expr.pseudos; | |
Expr.setFilters = new setFilters(); | |
tokenize = Sizzle.tokenize = function( selector, parseOnly ) { | |
var matched, match, tokens, type, | |
soFar, groups, preFilters, | |
cached = tokenCache[ selector + " " ]; | |
if ( cached ) { | |
return parseOnly ? 0 : cached.slice( 0 ); | |
} | |
soFar = selector; | |
groups = []; | |
preFilters = Expr.preFilter; | |
while ( soFar ) { | |
// Comma and first run | |
if ( !matched || (match = rcomma.exec( soFar )) ) { | |
if ( match ) { | |
// Don't consume trailing commas as valid | |
soFar = soFar.slice( match[0].length ) || soFar; | |
} | |
groups.push( (tokens = []) ); | |
} | |
matched = false; | |
// Combinators | |
if ( (match = rcombinators.exec( soFar )) ) { | |
matched = match.shift(); | |
tokens.push({ | |
value: matched, | |
// Cast descendant combinators to space | |
type: match[0].replace( rtrim, " " ) | |
}); | |
soFar = soFar.slice( matched.length ); | |
} | |
// Filters | |
for ( type in Expr.filter ) { | |
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || | |
(match = preFilters[ type ]( match ))) ) { | |
matched = match.shift(); | |
tokens.push({ | |
value: matched, | |
type: type, | |
matches: match | |
}); | |
soFar = soFar.slice( matched.length ); | |
} | |
} | |
if ( !matched ) { | |
break; | |
} | |
} | |
// Return the length of the invalid excess | |
// if we're just parsing | |
// Otherwise, throw an error or return tokens | |
return parseOnly ? | |
soFar.length : | |
soFar ? | |
Sizzle.error( selector ) : | |
// Cache the tokens | |
tokenCache( selector, groups ).slice( 0 ); | |
}; | |
function toSelector( tokens ) { | |
var i = 0, | |
len = tokens.length, | |
selector = ""; | |
for ( ; i < len; i++ ) { | |
selector += tokens[i].value; | |
} | |
return selector; | |
} | |
function addCombinator( matcher, combinator, base ) { | |
var dir = combinator.dir, | |
checkNonElements = base && dir === "parentNode", | |
doneName = done++; | |
return combinator.first ? | |
// Check against closest ancestor/preceding element | |
function( elem, context, xml ) { | |
while ( (elem = elem[ dir ]) ) { | |
if ( elem.nodeType === 1 || checkNonElements ) { | |
return matcher( elem, context, xml ); | |
} | |
} | |
} : | |
// Check against all ancestor/preceding elements | |
function( elem, context, xml ) { | |
var oldCache, outerCache, | |
newCache = [ dirruns, doneName ]; | |
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching | |
if ( xml ) { | |
while ( (elem = elem[ dir ]) ) { | |
if ( elem.nodeType === 1 || checkNonElements ) { | |
if ( matcher( elem, context, xml ) ) { | |
return true; | |
} | |
} | |
} | |
} else { | |
while ( (elem = elem[ dir ]) ) { | |
if ( elem.nodeType === 1 || checkNonElements ) { | |
outerCache = elem[ expando ] || (elem[ expando ] = {}); | |
if ( (oldCache = outerCache[ dir ]) && | |
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { | |
// Assign to newCache so results back-propagate to previous elements | |
return (newCache[ 2 ] = oldCache[ 2 ]); | |
} else { | |
// Reuse newcache so results back-propagate to previous elements | |
outerCache[ dir ] = newCache; | |
// A match means we're done; a fail means we have to keep checking | |
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { | |
return true; | |
} | |
} | |
} | |
} | |
} | |
}; | |
} | |
function elementMatcher( matchers ) { | |
return matchers.length > 1 ? | |
function( elem, context, xml ) { | |
var i = matchers.length; | |
while ( i-- ) { | |
if ( !matchers[i]( elem, context, xml ) ) { | |
return false; | |
} | |
} | |
return true; | |
} : | |
matchers[0]; | |
} | |
function multipleContexts( selector, contexts, results ) { | |
var i = 0, | |
len = contexts.length; | |
for ( ; i < len; i++ ) { | |
Sizzle( selector, contexts[i], results ); | |
} | |
return results; | |
} | |
function condense( unmatched, map, filter, context, xml ) { | |
var elem, | |
newUnmatched = [], | |
i = 0, | |
len = unmatched.length, | |
mapped = map != null; | |
for ( ; i < len; i++ ) { | |
if ( (elem = unmatched[i]) ) { | |
if ( !filter || filter( elem, context, xml ) ) { | |
newUnmatched.push( elem ); | |
if ( mapped ) { | |
map.push( i ); | |
} | |
} | |
} | |
} | |
return newUnmatched; | |
} | |
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { | |
if ( postFilter && !postFilter[ expando ] ) { | |
postFilter = setMatcher( postFilter ); | |
} | |
if ( postFinder && !postFinder[ expando ] ) { | |
postFinder = setMatcher( postFinder, postSelector ); | |
} | |
return markFunction(function( seed, results, context, xml ) { | |
var temp, i, elem, | |
preMap = [], | |
postMap = [], | |
preexisting = results.length, | |
// Get initial elements from seed or context | |
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), | |
// Prefilter to get matcher input, preserving a map for seed-results synchronization | |
matcherIn = preFilter && ( seed || !selector ) ? | |
condense( elems, preMap, preFilter, context, xml ) : | |
elems, | |
matcherOut = matcher ? | |
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, | |
postFinder || ( seed ? preFilter : preexisting || postFilter ) ? | |
// ...intermediate processing is necessary | |
[] : | |
// ...otherwise use results directly | |
results : | |
matcherIn; | |
// Find primary matches | |
if ( matcher ) { | |
matcher( matcherIn, matcherOut, context, xml ); | |
} | |
// Apply postFilter | |
if ( postFilter ) { | |
temp = condense( matcherOut, postMap ); | |
postFilter( temp, [], context, xml ); | |
// Un-match failing elements by moving them back to matcherIn | |
i = temp.length; | |
while ( i-- ) { | |
if ( (elem = temp[i]) ) { | |
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); | |
} | |
} | |
} | |
if ( seed ) { | |
if ( postFinder || preFilter ) { | |
if ( postFinder ) { | |
// Get the final matcherOut by condensing this intermediate into postFinder contexts | |
temp = []; | |
i = matcherOut.length; | |
while ( i-- ) { | |
if ( (elem = matcherOut[i]) ) { | |
// Restore matcherIn since elem is not yet a final match | |
temp.push( (matcherIn[i] = elem) ); | |
} | |
} | |
postFinder( null, (matcherOut = []), temp, xml ); | |
} | |
// Move matched elements from seed to results to keep them synchronized | |
i = matcherOut.length; | |
while ( i-- ) { | |
if ( (elem = matcherOut[i]) && | |
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { | |
seed[temp] = !(results[temp] = elem); | |
} | |
} | |
} | |
// Add elements to results, through postFinder if defined | |
} else { | |
matcherOut = condense( | |
matcherOut === results ? | |
matcherOut.splice( preexisting, matcherOut.length ) : | |
matcherOut | |
); | |
if ( postFinder ) { | |
postFinder( null, results, matcherOut, xml ); | |
} else { | |
push.apply( results, matcherOut ); | |
} | |
} | |
}); | |
} | |
function matcherFromTokens( tokens ) { | |
var checkContext, matcher, j, | |
len = tokens.length, | |
leadingRelative = Expr.relative[ tokens[0].type ], | |
implicitRelative = leadingRelative || Expr.relative[" "], | |
i = leadingRelative ? 1 : 0, | |
// The foundational matcher ensures that elements are reachable from top-level context(s) | |
matchContext = addCombinator( function( elem ) { | |
return elem === checkContext; | |
}, implicitRelative, true ), | |
matchAnyContext = addCombinator( function( elem ) { | |
return indexOf.call( checkContext, elem ) > -1; | |
}, implicitRelative, true ), | |
matchers = [ function( elem, context, xml ) { | |
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( | |
(checkContext = context).nodeType ? | |
matchContext( elem, context, xml ) : | |
matchAnyContext( elem, context, xml ) ); | |
} ]; | |
for ( ; i < len; i++ ) { | |
if ( (matcher = Expr.relative[ tokens[i].type ]) ) { | |
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; | |
} else { | |
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); | |
// Return special upon seeing a positional matcher | |
if ( matcher[ expando ] ) { | |
// Find the next relative operator (if any) for proper handling | |
j = ++i; | |
for ( ; j < len; j++ ) { | |
if ( Expr.relative[ tokens[j].type ] ) { | |
break; | |
} | |
} | |
return setMatcher( | |
i > 1 && elementMatcher( matchers ), | |
i > 1 && toSelector( | |
// If the preceding token was a descendant combinator, insert an implicit any-element `*` | |
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) | |
).replace( rtrim, "$1" ), | |
matcher, | |
i < j && matcherFromTokens( tokens.slice( i, j ) ), | |
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), | |
j < len && toSelector( tokens ) | |
); | |
} | |
matchers.push( matcher ); | |
} | |
} | |
return elementMatcher( matchers ); | |
} | |
function matcherFromGroupMatchers( elementMatchers, setMatchers ) { | |
var bySet = setMatchers.length > 0, | |
byElement = elementMatchers.length > 0, | |
superMatcher = function( seed, context, xml, results, outermost ) { | |
var elem, j, matcher, | |
matchedCount = 0, | |
i = "0", | |
unmatched = seed && [], | |
setMatched = [], | |
contextBackup = outermostContext, | |
// We must always have either seed elements or outermost context | |
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), | |
// Use integer dirruns iff this is the outermost matcher | |
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), | |
len = elems.length; | |
if ( outermost ) { | |
outermostContext = context !== document && context; | |
} | |
// Add elements passing elementMatchers directly to results | |
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below | |
// Support: IE<9, Safari | |
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id | |
for ( ; i !== len && (elem = elems[i]) != null; i++ ) { | |
if ( byElement && elem ) { | |
j = 0; | |
while ( (matcher = elementMatchers[j++]) ) { | |
if ( matcher( elem, context, xml ) ) { | |
results.push( elem ); | |
break; | |
} | |
} | |
if ( outermost ) { | |
dirruns = dirrunsUnique; | |
} | |
} | |
// Track unmatched elements for set filters | |
if ( bySet ) { | |
// They will have gone through all possible matchers | |
if ( (elem = !matcher && elem) ) { | |
matchedCount--; | |
} | |
// Lengthen the array for every element, matched or not | |
if ( seed ) { | |
unmatched.push( elem ); | |
} | |
} | |
} | |
// Apply set filters to unmatched elements | |
matchedCount += i; | |
if ( bySet && i !== matchedCount ) { | |
j = 0; | |
while ( (matcher = setMatchers[j++]) ) { | |
matcher( unmatched, setMatched, context, xml ); | |
} | |
if ( seed ) { | |
// Reintegrate element matches to eliminate the need for sorting | |
if ( matchedCount > 0 ) { | |
while ( i-- ) { | |
if ( !(unmatched[i] || setMatched[i]) ) { | |
setMatched[i] = pop.call( results ); | |
} | |
} | |
} | |
// Discard index placeholder values to get only actual matches | |
setMatched = condense( setMatched ); | |
} | |
// Add matches to results | |
push.apply( results, setMatched ); | |
// Seedless set matches succeeding multiple successful matchers stipulate sorting | |
if ( outermost && !seed && setMatched.length > 0 && | |
( matchedCount + setMatchers.length ) > 1 ) { | |
Sizzle.uniqueSort( results ); | |
} | |
} | |
// Override manipulation of globals by nested matchers | |
if ( outermost ) { | |
dirruns = dirrunsUnique; | |
outermostContext = contextBackup; | |
} | |
return unmatched; | |
}; | |
return bySet ? | |
markFunction( superMatcher ) : | |
superMatcher; | |
} | |
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { | |
var i, | |
setMatchers = [], | |
elementMatchers = [], | |
cached = compilerCache[ selector + " " ]; | |
if ( !cached ) { | |
// Generate a function of recursive functions that can be used to check each element | |
if ( !match ) { | |
match = tokenize( selector ); | |
} | |
i = match.length; | |
while ( i-- ) { | |
cached = matcherFromTokens( match[i] ); | |
if ( cached[ expando ] ) { | |
setMatchers.push( cached ); | |
} else { | |
elementMatchers.push( cached ); | |
} | |
} | |
// Cache the compiled function | |
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); | |
// Save selector and tokenization | |
cached.selector = selector; | |
} | |
return cached; | |
}; | |
/** | |
* A low-level selection function that works with Sizzle's compiled | |
* selector functions | |
* @param {String|Function} selector A selector or a pre-compiled | |
* selector function built with Sizzle.compile | |
* @param {Element} context | |
* @param {Array} [results] | |
* @param {Array} [seed] A set of elements to match against | |
*/ | |
select = Sizzle.select = function( selector, context, results, seed ) { | |
var i, tokens, token, type, find, | |
compiled = typeof selector === "function" && selector, | |
match = !seed && tokenize( (selector = compiled.selector || selector) ); | |
results = results || []; | |
// Try to minimize operations if there is no seed and only one group | |
if ( match.length === 1 ) { | |
// Take a shortcut and set the context if the root selector is an ID | |
tokens = match[0] = match[0].slice( 0 ); | |
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && | |
support.getById && context.nodeType === 9 && documentIsHTML && | |
Expr.relative[ tokens[1].type ] ) { | |
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; | |
if ( !context ) { | |
return results; | |
// Precompiled matchers will still verify ancestry, so step up a level | |
} else if ( compiled ) { | |
context = context.parentNode; | |
} | |
selector = selector.slice( tokens.shift().value.length ); | |
} | |
// Fetch a seed set for right-to-left matching | |
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; | |
while ( i-- ) { | |
token = tokens[i]; | |
// Abort if we hit a combinator | |
if ( Expr.relative[ (type = token.type) ] ) { | |
break; | |
} | |
if ( (find = Expr.find[ type ]) ) { | |
// Search, expanding context for leading sibling combinators | |
if ( (seed = find( | |
token.matches[0].replace( runescape, funescape ), | |
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context | |
)) ) { | |
// If seed is empty or no tokens remain, we can return early | |
tokens.splice( i, 1 ); | |
selector = seed.length && toSelector( tokens ); | |
if ( !selector ) { | |
push.apply( results, seed ); | |
return results; | |
} | |
break; | |
} | |
} | |
} | |
} | |
// Compile and execute a filtering function if one is not provided | |
// Provide `match` to avoid retokenization if we modified the selector above | |
( compiled || compile( selector, match ) )( | |
seed, | |
context, | |
!documentIsHTML, | |
results, | |
rsibling.test( selector ) && testContext( context.parentNode ) || context | |
); | |
return results; | |
}; | |
// One-time assignments | |
// Sort stability | |
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; | |
// Support: Chrome<14 | |
// Always assume duplicates if they aren't passed to the comparison function | |
support.detectDuplicates = !!hasDuplicate; | |
// Initialize against the default document | |
setDocument(); | |
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) | |
// Detached nodes confoundingly follow *each other* | |
support.sortDetached = assert(function( div1 ) { | |
// Should return 1, but returns 4 (following) | |
return div1.compareDocumentPosition( document.createElement("div") ) & 1; | |
}); | |
// Support: IE<8 | |
// Prevent attribute/property "interpolation" | |
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx | |
if ( !assert(function( div ) { | |
div.innerHTML = "<a href='#'></a>"; | |
return div.firstChild.getAttribute("href") === "#" ; | |
}) ) { | |
addHandle( "type|href|height|width", function( elem, name, isXML ) { | |
if ( !isXML ) { | |
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); | |
} | |
}); | |
} | |
// Support: IE<9 | |
// Use defaultValue in place of getAttribute("value") | |
if ( !support.attributes || !assert(function( div ) { | |
div.innerHTML = "<input/>"; | |
div.firstChild.setAttribute( "value", "" ); | |
return div.firstChild.getAttribute( "value" ) === ""; | |
}) ) { | |
addHandle( "value", function( elem, name, isXML ) { | |
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { | |
return elem.defaultValue; | |
} | |
}); | |
} | |
// Support: IE<9 | |
// Use getAttributeNode to fetch booleans when getAttribute lies | |
if ( !assert(function( div ) { | |
return div.getAttribute("disabled") == null; | |
}) ) { | |
addHandle( booleans, function( elem, name, isXML ) { | |
var val; | |
if ( !isXML ) { | |
return elem[ name ] === true ? name.toLowerCase() : | |
(val = elem.getAttributeNode( name )) && val.specified ? | |
val.value : | |
null; | |
} | |
}); | |
} | |
return Sizzle; | |
})( window ); | |
jQuery.find = Sizzle; | |
jQuery.expr = Sizzle.selectors; | |
jQuery.expr[":"] = jQuery.expr.pseudos; | |
jQuery.unique = Sizzle.uniqueSort; | |
jQuery.text = Sizzle.getText; | |
jQuery.isXMLDoc = Sizzle.isXML; | |
jQuery.contains = Sizzle.contains; | |
var rneedsContext = jQuery.expr.match.needsContext; | |
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); | |
var risSimple = /^.[^:#\[\.,]*$/; | |
// Implement the identical functionality for filter and not | |
function winnow( elements, qualifier, not ) { | |
if ( jQuery.isFunction( qualifier ) ) { | |
return jQuery.grep( elements, function( elem, i ) { | |
/* jshint -W018 */ | |
return !!qualifier.call( elem, i, elem ) !== not; | |
}); | |
} | |
if ( qualifier.nodeType ) { | |
return jQuery.grep( elements, function( elem ) { | |
return ( elem === qualifier ) !== not; | |
}); | |
} | |
if ( typeof qualifier === "string" ) { | |
if ( risSimple.test( qualifier ) ) { | |
return jQuery.filter( qualifier, elements, not ); | |
} | |
qualifier = jQuery.filter( qualifier, elements ); | |
} | |
return jQuery.grep( elements, function( elem ) { | |
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; | |
}); | |
} | |
jQuery.filter = function( expr, elems, not ) { | |
var elem = elems[ 0 ]; | |
if ( not ) { | |
expr = ":not(" + expr + ")"; | |
} | |
return elems.length === 1 && elem.nodeType === 1 ? | |
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : | |
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { | |
return elem.nodeType === 1; | |
})); | |
}; | |
jQuery.fn.extend({ | |
find: function( selector ) { | |
var i, | |
len = this.length, | |
ret = [], | |
self = this; | |
if ( typeof selector !== "string" ) { | |
return this.pushStack( jQuery( selector ).filter(function() { | |
for ( i = 0; i < len; i++ ) { | |
if ( jQuery.contains( self[ i ], this ) ) { | |
return true; | |
} | |
} | |
}) ); | |
} | |
for ( i = 0; i < len; i++ ) { | |
jQuery.find( selector, self[ i ], ret ); | |
} | |
// Needed because $( selector, context ) becomes $( context ).find( selector ) | |
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); | |
ret.selector = this.selector ? this.selector + " " + selector : selector; | |
return ret; | |
}, | |
filter: function( selector ) { | |
return this.pushStack( winnow(this, selector || [], false) ); | |
}, | |
not: function( selector ) { | |
return this.pushStack( winnow(this, selector || [], true) ); | |
}, | |
is: function( selector ) { | |
return !!winnow( | |
this, | |
// If this is a positional/relative selector, check membership in the returned set | |
// so $("p:first").is("p:last") won't return true for a doc with two "p". | |
typeof selector === "string" && rneedsContext.test( selector ) ? | |
jQuery( selector ) : | |
selector || [], | |
false | |
).length; | |
} | |
}); | |
// Initialize a jQuery object | |
// A central reference to the root jQuery(document) | |
var rootjQuery, | |
// A simple way to check for HTML strings | |
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521) | |
// Strict HTML recognition (#11290: must start with <) | |
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, | |
init = jQuery.fn.init = function( selector, context ) { | |
var match, elem; | |
// HANDLE: $(""), $(null), $(undefined), $(false) | |
if ( !selector ) { | |
return this; | |
} | |
// Handle HTML strings | |
if ( typeof selector === "string" ) { | |
if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { | |
// Assume that strings that start and end with <> are HTML and skip the regex check | |
match = [ null, selector, null ]; | |
} else { | |
match = rquickExpr.exec( selector ); | |
} | |
// Match html or make sure no context is specified for #id | |
if ( match && (match[1] || !context) ) { | |
// HANDLE: $(html) -> $(array) | |
if ( match[1] ) { | |
context = context instanceof jQuery ? context[0] : context; | |
// scripts is true for back-compat | |
// Intentionally let the error be thrown if parseHTML is not present | |
jQuery.merge( this, jQuery.parseHTML( | |
match[1], | |
context && context.nodeType ? context.ownerDocument || context : document, | |
true | |
) ); | |
// HANDLE: $(html, props) | |
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { | |
for ( match in context ) { | |
// Properties of context are called as methods if possible | |
if ( jQuery.isFunction( this[ match ] ) ) { | |
this[ match ]( context[ match ] ); | |
// ...and otherwise set as attributes | |
} else { | |
this.attr( match, context[ match ] ); | |
} | |
} | |
} | |
return this; | |
// HANDLE: $(#id) | |
} else { | |
elem = document.getElementById( match[2] ); | |
// Check parentNode to catch when Blackberry 4.6 returns | |
// nodes that are no longer in the document #6963 | |
if ( elem && elem.parentNode ) { | |
// Inject the element directly into the jQuery object | |
this.length = 1; | |
this[0] = elem; | |
} | |
this.context = document; | |
this.selector = selector; | |
return this; | |
} | |
// HANDLE: $(expr, $(...)) | |
} else if ( !context || context.jquery ) { | |
return ( context || rootjQuery ).find( selector ); | |
// HANDLE: $(expr, context) | |
// (which is just equivalent to: $(context).find(expr) | |
} else { | |
return this.constructor( context ).find( selector ); | |
} | |
// HANDLE: $(DOMElement) | |
} else if ( selector.nodeType ) { | |
this.context = this[0] = selector; | |
this.length = 1; | |
return this; | |
// HANDLE: $(function) | |
// Shortcut for document ready | |
} else if ( jQuery.isFunction( selector ) ) { | |
return typeof rootjQuery.ready !== "undefined" ? | |
rootjQuery.ready( selector ) : | |
// Execute immediately if ready is not present | |
selector( jQuery ); | |
} | |
if ( selector.selector !== undefined ) { | |
this.selector = selector.selector; | |
this.context = selector.context; | |
} | |
return jQuery.makeArray( selector, this ); | |
}; | |
// Give the init function the jQuery prototype for later instantiation | |
init.prototype = jQuery.fn; | |
// Initialize central reference | |
rootjQuery = jQuery( document ); | |
var rparentsprev = /^(?:parents|prev(?:Until|All))/, | |
// methods guaranteed to produce a unique set when starting from a unique set | |
guaranteedUnique = { | |
children: true, | |
contents: true, | |
next: true, | |
prev: true | |
}; | |
jQuery.extend({ | |
dir: function( elem, dir, until ) { | |
var matched = [], | |
truncate = until !== undefined; | |
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { | |
if ( elem.nodeType === 1 ) { | |
if ( truncate && jQuery( elem ).is( until ) ) { | |
break; | |
} | |
matched.push( elem ); | |
} | |
} | |
return matched; | |
}, | |
sibling: function( n, elem ) { | |
var matched = []; | |
for ( ; n; n = n.nextSibling ) { | |
if ( n.nodeType === 1 && n !== elem ) { | |
matched.push( n ); | |
} | |
} | |
return matched; | |
} | |
}); | |
jQuery.fn.extend({ | |
has: function( target ) { | |
var targets = jQuery( target, this ), | |
l = targets.length; | |
return this.filter(function() { | |
var i = 0; | |
for ( ; i < l; i++ ) { | |
if ( jQuery.contains( this, targets[i] ) ) { | |
return true; | |
} | |
} | |
}); | |
}, | |
closest: function( selectors, context ) { | |
var cur, | |
i = 0, | |
l = this.length, | |
matched = [], | |
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? | |
jQuery( selectors, context || this.context ) : | |
0; | |
for ( ; i < l; i++ ) { | |
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { | |
// Always skip document fragments | |
if ( cur.nodeType < 11 && (pos ? | |
pos.index(cur) > -1 : | |
// Don't pass non-elements to Sizzle | |
cur.nodeType === 1 && | |
jQuery.find.matchesSelector(cur, selectors)) ) { | |
matched.push( cur ); | |
break; | |
} | |
} | |
} | |
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); | |
}, | |
// Determine the position of an element within | |
// the matched set of elements | |
index: function( elem ) { | |
// No argument, return index in parent | |
if ( !elem ) { | |
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; | |
} | |
// index in selector | |
if ( typeof elem === "string" ) { | |
return indexOf.call( jQuery( elem ), this[ 0 ] ); | |
} | |
// Locate the position of the desired element | |
return indexOf.call( this, | |
// If it receives a jQuery object, the first element is used | |
elem.jquery ? elem[ 0 ] : elem | |
); | |
}, | |
add: function( selector, context ) { | |
return this.pushStack( | |
jQuery.unique( | |
jQuery.merge( this.get(), jQuery( selector, context ) ) | |
) | |
); | |
}, | |
addBack: function( selector ) { | |
return this.add( selector == null ? | |
this.prevObject : this.prevObject.filter(selector) | |
); | |
} | |
}); | |
function sibling( cur, dir ) { | |
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} | |
return cur; | |
} | |
jQuery.each({ | |
parent: function( elem ) { | |
var parent = elem.parentNode; | |
return parent && parent.nodeType !== 11 ? parent : null; | |
}, | |
parents: function( elem ) { | |
return jQuery.dir( elem, "parentNode" ); | |
}, | |
parentsUntil: function( elem, i, until ) { | |
return jQuery.dir( elem, "parentNode", until ); | |
}, | |
next: function( elem ) { | |
return sibling( elem, "nextSibling" ); | |
}, | |
prev: function( elem ) { | |
return sibling( elem, "previousSibling" ); | |
}, | |
nextAll: function( elem ) { | |
return jQuery.dir( elem, "nextSibling" ); | |
}, | |
prevAll: function( elem ) { | |
return jQuery.dir( elem, "previousSibling" ); | |
}, | |
nextUntil: function( elem, i, until ) { | |
return jQuery.dir( elem, "nextSibling", until ); | |
}, | |
prevUntil: function( elem, i, until ) { | |
return jQuery.dir( elem, "previousSibling", until ); | |
}, | |
siblings: function( elem ) { | |
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); | |
}, | |
children: function( elem ) { | |
return jQuery.sibling( elem.firstChild ); | |
}, | |
contents: function( elem ) { | |
return elem.contentDocument || jQuery.merge( [], elem.childNodes ); | |
} | |
}, function( name, fn ) { | |
jQuery.fn[ name ] = function( until, selector ) { | |
var matched = jQuery.map( this, fn, until ); | |
if ( name.slice( -5 ) !== "Until" ) { | |
selector = until; | |
} | |
if ( selector && typeof selector === "string" ) { | |
matched = jQuery.filter( selector, matched ); | |
} | |
if ( this.length > 1 ) { | |
// Remove duplicates | |
if ( !guaranteedUnique[ name ] ) { | |
jQuery.unique( matched ); | |
} | |
// Reverse order for parents* and prev-derivatives | |
if ( rparentsprev.test( name ) ) { | |
matched.reverse(); | |
} | |
} | |
return this.pushStack( matched ); | |
}; | |
}); | |
var rnotwhite = (/\S+/g); | |
// String to Object options format cache | |
var optionsCache = {}; | |
// Convert String-formatted options into Object-formatted ones and store in cache | |
function createOptions( options ) { | |
var object = optionsCache[ options ] = {}; | |
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { | |
object[ flag ] = true; | |
}); | |
return object; | |
} | |
/* | |
* Create a callback list using the following parameters: | |
* | |
* options: an optional list of space-separated options that will change how | |
* the callback list behaves or a more traditional option object | |
* | |
* By default a callback list will act like an event callback list and can be | |
* "fired" multiple times. | |
* | |
* Possible options: | |
* | |
* once: will ensure the callback list can only be fired once (like a Deferred) | |
* | |
* memory: will keep track of previous values and will call any callback added | |
* after the list has been fired right away with the latest "memorized" | |
* values (like a Deferred) | |
* | |
* unique: will ensure a callback can only be added once (no duplicate in the list) | |
* | |
* stopOnFalse: interrupt callings when a callback returns false | |
* | |
*/ | |
jQuery.Callbacks = function( options ) { | |
// Convert options from String-formatted to Object-formatted if needed | |
// (we check in cache first) | |
options = typeof options === "string" ? | |
( optionsCache[ options ] || createOptions( options ) ) : | |
jQuery.extend( {}, options ); | |
var // Last fire value (for non-forgettable lists) | |
memory, | |
// Flag to know if list was already fired | |
fired, | |
// Flag to know if list is currently firing | |
firing, | |
// First callback to fire (used internally by add and fireWith) | |
firingStart, | |
// End of the loop when firing | |
firingLength, | |
// Index of currently firing callback (modified by remove if needed) | |
firingIndex, | |
// Actual callback list | |
list = [], | |
// Stack of fire calls for repeatable lists | |
stack = !options.once && [], | |
// Fire callbacks | |
fire = function( data ) { | |
memory = options.memory && data; | |
fired = true; | |
firingIndex = firingStart || 0; | |
firingStart = 0; | |
firingLength = list.length; | |
firing = true; | |
for ( ; list && firingIndex < firingLength; firingIndex++ ) { | |
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { | |
memory = false; // To prevent further calls using add | |
break; | |
} | |
} | |
firing = false; | |
if ( list ) { | |
if ( stack ) { | |
if ( stack.length ) { | |
fire( stack.shift() ); | |
} | |
} else if ( memory ) { | |
list = []; | |
} else { | |
self.disable(); | |
} | |
} | |
}, | |
// Actual Callbacks object | |
self = { | |
// Add a callback or a collection of callbacks to the list | |
add: function() { | |
if ( list ) { | |
// First, we save the current length | |
var start = list.length; | |
(function add( args ) { | |
jQuery.each( args, function( _, arg ) { | |
var type = jQuery.type( arg ); | |
if ( type === "function" ) { | |
if ( !options.unique || !self.has( arg ) ) { | |
list.push( arg ); | |
} | |
} else if ( arg && arg.length && type !== "string" ) { | |
// Inspect recursively | |
add( arg ); | |
} | |
}); | |
})( arguments ); | |
// Do we need to add the callbacks to the | |
// current firing batch? | |
if ( firing ) { | |
firingLength = list.length; | |
// With memory, if we're not firing then | |
// we should call right away | |
} else if ( memory ) { | |
firingStart = start; | |
fire( memory ); | |
} | |
} | |
return this; | |
}, | |
// Remove a callback from the list | |
remove: function() { | |
if ( list ) { | |
jQuery.each( arguments, function( _, arg ) { | |
var index; | |
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { | |
list.splice( index, 1 ); | |
// Handle firing indexes | |
if ( firing ) { | |
if ( index <= firingLength ) { | |
firingLength--; | |
} | |
if ( index <= firingIndex ) { | |
firingIndex--; | |
} | |
} | |
} | |
}); | |
} | |
return this; | |
}, | |
// Check if a given callback is in the list. | |
// If no argument is given, return whether or not list has callbacks attached. | |
has: function( fn ) { | |
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); | |
}, | |
// Remove all callbacks from the list | |
empty: function() { | |
list = []; | |
firingLength = 0; | |
return this; | |
}, | |
// Have the list do nothing anymore | |
disable: function() { | |
list = stack = memory = undefined; | |
return this; | |
}, | |
// Is it disabled? | |
disabled: function() { | |
return !list; | |
}, | |
// Lock the list in its current state | |
lock: function() { | |
stack = undefined; | |
if ( !memory ) { | |
self.disable(); | |
} | |
return this; | |
}, | |
// Is it locked? | |
locked: function() { | |
return !stack; | |
}, | |
// Call all callbacks with the given context and arguments | |
fireWith: function( context, args ) { | |
if ( list && ( !fired || stack ) ) { | |
args = args || []; | |
args = [ context, args.slice ? args.slice() : args ]; | |
if ( firing ) { | |
stack.push( args ); | |
} else { | |
fire( args ); | |
} | |
} | |
return this; | |
}, | |
// Call all the callbacks with the given arguments | |
fire: function() { | |
self.fireWith( this, arguments ); | |
return this; | |
}, | |
// To know if the callbacks have already been called at least once | |
fired: function() { | |
return !!fired; | |
} | |
}; | |
return self; | |
}; | |
jQuery.extend({ | |
Deferred: function( func ) { | |
var tuples = [ | |
// action, add listener, listener list, final state | |
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], | |
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], | |
[ "notify", "progress", jQuery.Callbacks("memory") ] | |
], | |
state = "pending", | |
promise = { | |
state: function() { | |
return state; | |
}, | |
always: function() { | |
deferred.done( arguments ).fail( arguments ); | |
return this; | |
}, | |
then: function( /* fnDone, fnFail, fnProgress */ ) { | |
var fns = arguments; | |
return jQuery.Deferred(function( newDefer ) { | |
jQuery.each( tuples, function( i, tuple ) { | |
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; | |
// deferred[ done | fail | progress ] for forwarding actions to newDefer | |
deferred[ tuple[1] ](function() { | |
var returned = fn && fn.apply( this, arguments ); | |
if ( returned && jQuery.isFunction( returned.promise ) ) { | |
returned.promise() | |
.done( newDefer.resolve ) | |
.fail( newDefer.reject ) | |
.progress( newDefer.notify ); | |
} else { | |
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); | |
} | |
}); | |
}); | |
fns = null; | |
}).promise(); | |
}, | |
// Get a promise for this deferred | |
// If obj is provided, the promise aspect is added to the object | |
promise: function( obj ) { | |
return obj != null ? jQuery.extend( obj, promise ) : promise; | |
} | |
}, | |
deferred = {}; | |
// Keep pipe for back-compat | |
promise.pipe = promise.then; | |
// Add list-specific methods | |
jQuery.each( tuples, function( i, tuple ) { | |
var list = tuple[ 2 ], | |
stateString = tuple[ 3 ]; | |
// promise[ done | fail | progress ] = list.add | |
promise[ tuple[1] ] = list.add; | |
// Handle state | |
if ( stateString ) { | |
list.add(function() { | |
// state = [ resolved | rejected ] | |
state = stateString; | |
// [ reject_list | resolve_list ].disable; progress_list.lock | |
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); | |
} | |
// deferred[ resolve | reject | notify ] | |
deferred[ tuple[0] ] = function() { | |
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); | |
return this; | |
}; | |
deferred[ tuple[0] + "With" ] = list.fireWith; | |
}); | |
// Make the deferred a promise | |
promise.promise( deferred ); | |
// Call given func if any | |
if ( func ) { | |
func.call( deferred, deferred ); | |
} | |
// All done! | |
return deferred; | |
}, | |
// Deferred helper | |
when: function( subordinate /* , ..., subordinateN */ ) { | |
var i = 0, | |
resolveValues = slice.call( arguments ), | |
length = resolveValues.length, | |
// the count of uncompleted subordinates | |
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, | |
// the master Deferred. If resolveValues consist of only a single Deferred, just use that. | |
deferred = remaining === 1 ? subordinate : jQuery.Deferred(), | |
// Update function for both resolve and progress values | |
updateFunc = function( i, contexts, values ) { | |
return function( value ) { | |
contexts[ i ] = this; | |
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; | |
if ( values === progressValues ) { | |
deferred.notifyWith( contexts, values ); | |
} else if ( !( --remaining ) ) { | |
deferred.resolveWith( contexts, values ); | |
} | |
}; | |
}, | |
progressValues, progressContexts, resolveContexts; | |
// add listeners to Deferred subordinates; treat others as resolved | |
if ( length > 1 ) { | |
progressValues = new Array( length ); | |
progressContexts = new Array( length ); | |
resolveContexts = new Array( length ); | |
for ( ; i < length; i++ ) { | |
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { | |
resolveValues[ i ].promise() | |
.done( updateFunc( i, resolveContexts, resolveValues ) ) | |
.fail( deferred.reject ) | |
.progress( updateFunc( i, progressContexts, progressValues ) ); | |
} else { | |
--remaining; | |
} | |
} | |
} | |
// if we're not waiting on anything, resolve the master | |
if ( !remaining ) { | |
deferred.resolveWith( resolveContexts, resolveValues ); | |
} | |
return deferred.promise(); | |
} | |
}); | |
// The deferred used on DOM ready | |
var readyList; | |
jQuery.fn.ready = function( fn ) { | |
// Add the callback | |
jQuery.ready.promise().done( fn ); | |
return this; | |
}; | |
jQuery.extend({ | |
// Is the DOM ready to be used? Set to true once it occurs. | |
isReady: false, | |
// A counter to track how many items to wait for before | |
// the ready event fires. See #6781 | |
readyWait: 1, | |
// Hold (or release) the ready event | |
holdReady: function( hold ) { | |
if ( hold ) { | |
jQuery.readyWait++; | |
} else { | |
jQuery.ready( true ); | |
} | |
}, | |
// Handle when the DOM is ready | |
ready: function( wait ) { | |
// Abort if there are pending holds or we're already ready | |
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { | |
return; | |
} | |
// Remember that the DOM is ready | |
jQuery.isReady = true; | |
// If a normal DOM Ready event fired, decrement, and wait if need be | |
if ( wait !== true && --jQuery.readyWait > 0 ) { | |
return; | |
} | |
// If there are functions bound, to execute | |
readyList.resolveWith( document, [ jQuery ] ); | |
// Trigger any bound ready events | |
if ( jQuery.fn.triggerHandler ) { | |
jQuery( document ).triggerHandler( "ready" ); | |
jQuery( document ).off( "ready" ); | |
} | |
} | |
}); | |
/** | |
* The ready event handler and self cleanup method | |
*/ | |
function completed() { | |
document.removeEventListener( "DOMContentLoaded", completed, false ); | |
window.removeEventListener( "load", completed, false ); | |
jQuery.ready(); | |
} | |
jQuery.ready.promise = function( obj ) { | |
if ( !readyList ) { | |
readyList = jQuery.Deferred(); | |
// Catch cases where $(document).ready() is called after the browser event has already occurred. | |
// we once tried to use readyState "interactive" here, but it caused issues like the one | |
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 | |
if ( document.readyState === "complete" ) { | |
// Handle it asynchronously to allow scripts the opportunity to delay ready | |
setTimeout( jQuery.ready ); | |
} else { | |
// Use the handy event callback | |
document.addEventListener( "DOMContentLoaded", completed, false ); | |
// A fallback to window.onload, that will always work | |
window.addEventListener( "load", completed, false ); | |
} | |
} | |
return readyList.promise( obj ); | |
}; | |
// Kick off the DOM ready check even if the user does not | |
jQuery.ready.promise(); | |
// Multifunctional method to get and set values of a collection | |
// The value/s can optionally be executed if it's a function | |
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { | |
var i = 0, | |
len = elems.length, | |
bulk = key == null; | |
// Sets many values | |
if ( jQuery.type( key ) === "object" ) { | |
chainable = true; | |
for ( i in key ) { | |
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); | |
} | |
// Sets one value | |
} else if ( value !== undefined ) { | |
chainable = true; | |
if ( !jQuery.isFunction( value ) ) { | |
raw = true; | |
} | |
if ( bulk ) { | |
// Bulk operations run against the entire set | |
if ( raw ) { | |
fn.call( elems, value ); | |
fn = null; | |
// ...except when executing function values | |
} else { | |
bulk = fn; | |
fn = function( elem, key, value ) { | |
return bulk.call( jQuery( elem ), value ); | |
}; | |
} | |
} | |
if ( fn ) { | |
for ( ; i < len; i++ ) { | |
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); | |
} | |
} | |
} | |
return chainable ? | |
elems : | |
// Gets | |
bulk ? | |
fn.call( elems ) : | |
len ? fn( elems[0], key ) : emptyGet; | |
}; | |
/** | |
* Determines whether an object can have data | |
*/ | |
jQuery.acceptData = function( owner ) { | |
// Accepts only: | |
// - Node | |
// - Node.ELEMENT_NODE | |
// - Node.DOCUMENT_NODE | |
// - Object | |
// - Any | |
/* jshint -W018 */ | |
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); | |
}; | |
function Data() { | |
// Support: Android < 4, | |
// Old WebKit does not have Object.preventExtensions/freeze method, | |
// return new empty object instead with no [[set]] accessor | |
Object.defineProperty( this.cache = {}, 0, { | |
get: function() { | |
return {}; | |
} | |
}); | |
this.expando = jQuery.expando + Math.random(); | |
} | |
Data.uid = 1; | |
Data.accepts = jQuery.acceptData; | |
Data.prototype = { | |
key: function( owner ) { | |
// We can accept data for non-element nodes in modern browsers, | |
// but we should not, see #8335. | |
// Always return the key for a frozen object. | |
if ( !Data.accepts( owner ) ) { | |
return 0; | |
} | |
var descriptor = {}, | |
// Check if the owner object already has a cache key | |
unlock = owner[ this.expando ]; | |
// If not, create one | |
if ( !unlock ) { | |
unlock = Data.uid++; | |
// Secure it in a non-enumerable, non-writable property | |
try { | |
descriptor[ this.expando ] = { value: unlock }; | |
Object.defineProperties( owner, descriptor ); | |
// Support: Android < 4 | |
// Fallback to a less secure definition | |
} catch ( e ) { | |
descriptor[ this.expando ] = unlock; | |
jQuery.extend( owner, descriptor ); | |
} | |
} | |
// Ensure the cache object | |
if ( !this.cache[ unlock ] ) { | |
this.cache[ unlock ] = {}; | |
} | |
return unlock; | |
}, | |
set: function( owner, data, value ) { | |
var prop, | |
// There may be an unlock assigned to this node, | |
// if there is no entry for this "owner", create one inline | |
// and set the unlock as though an owner entry had always existed | |
unlock = this.key( owner ), | |
cache = this.cache[ unlock ]; | |
// Handle: [ owner, key, value ] args | |
if ( typeof data === "string" ) { | |
cache[ data ] = value; | |
// Handle: [ owner, { properties } ] args | |
} else { | |
// Fresh assignments by object are shallow copied | |
if ( jQuery.isEmptyObject( cache ) ) { | |
jQuery.extend( this.cache[ unlock ], data ); | |
// Otherwise, copy the properties one-by-one to the cache object | |
} else { | |
for ( prop in data ) { | |
cache[ prop ] = data[ prop ]; | |
} | |
} | |
} | |
return cache; | |
}, | |
get: function( owner, key ) { | |
// Either a valid cache is found, or will be created. | |
// New caches will be created and the unlock returned, | |
// allowing direct access to the newly created | |
// empty data object. A valid owner object must be provided. | |
var cache = this.cache[ this.key( owner ) ]; | |
return key === undefined ? | |
cache : cache[ key ]; | |
}, | |
access: function( owner, key, value ) { | |
var stored; | |
// In cases where either: | |
// | |
// 1. No key was specified | |
// 2. A string key was specified, but no value provided | |
// | |
// Take the "read" path and allow the get method to determine | |
// which value to return, respectively either: | |
// | |
// 1. The entire cache object | |
// 2. The data stored at the key | |
// | |
if ( key === undefined || | |
((key && typeof key === "string") && value === undefined) ) { | |
stored = this.get( owner, key ); | |
return stored !== undefined ? | |
stored : this.get( owner, jQuery.camelCase(key) ); | |
} | |
// [*]When the key is not a string, or both a key and value | |
// are specified, set or extend (existing objects) with either: | |
// | |
// 1. An object of properties | |
// 2. A key and value | |
// | |
this.set( owner, key, value ); | |
// Since the "set" path can have two possible entry points | |
// return the expected data based on which path was taken[*] | |
return value !== undefined ? value : key; | |
}, | |
remove: function( owner, key ) { | |
var i, name, camel, | |
unlock = this.key( owner ), | |
cache = this.cache[ unlock ]; | |
if ( key === undefined ) { | |
this.cache[ unlock ] = {}; | |
} else { | |
// Support array or space separated string of keys | |
if ( jQuery.isArray( key ) ) { | |
// If "name" is an array of keys... | |
// When data is initially created, via ("key", "val") signature, | |
// keys will be converted to camelCase. | |
// Since there is no way to tell _how_ a key was added, remove | |
// both plain key and camelCase key. #12786 | |
// This will only penalize the array argument path. | |
name = key.concat( key.map( jQuery.camelCase ) ); | |
} else { | |
camel = jQuery.camelCase( key ); | |
// Try the string as a key before any manipulation | |
if ( key in cache ) { | |
name = [ key, camel ]; | |
} else { | |
// If a key with the spaces exists, use it. | |
// Otherwise, create an array by matching non-whitespace | |
name = camel; | |
name = name in cache ? | |
[ name ] : ( name.match( rnotwhite ) || [] ); | |
} | |
} | |
i = name.length; | |
while ( i-- ) { | |
delete cache[ name[ i ] ]; | |
} | |
} | |
}, | |
hasData: function( owner ) { | |
return !jQuery.isEmptyObject( | |
this.cache[ owner[ this.expando ] ] || {} | |
); | |
}, | |
discard: function( owner ) { | |
if ( owner[ this.expando ] ) { | |
delete this.cache[ owner[ this.expando ] ]; | |
} | |
} | |
}; | |
var data_priv = new Data(); | |
var data_user = new Data(); | |
/* | |
Implementation Summary | |
1. Enforce API surface and semantic compatibility with 1.9.x branch | |
2. Improve the module's maintainability by reducing the storage | |
paths to a single mechanism. | |
3. Use the same single mechanism to support "private" and "user" data. | |
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) | |
5. Avoid exposing implementation details on user objects (eg. expando properties) | |
6. Provide a clear path for implementation upgrade to WeakMap in 2014 | |
*/ | |
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, | |
rmultiDash = /([A-Z])/g; | |
function dataAttr( elem, key, data ) { | |
var name; | |
// If nothing was found internally, try to fetch any | |
// data from the HTML5 data-* attribute | |
if ( data === undefined && elem.nodeType === 1 ) { | |
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); | |
data = elem.getAttribute( name ); | |
if ( typeof data === "string" ) { | |
try { | |
data = data === "true" ? true : | |
data === "false" ? false : | |
data === "null" ? null : | |
// Only convert to a number if it doesn't change the string | |
+data + "" === data ? +data : | |
rbrace.test( data ) ? jQuery.parseJSON( data ) : | |
data; | |
} catch( e ) {} | |
// Make sure we set the data so it isn't changed later | |
data_user.set( elem, key, data ); | |
} else { | |
data = undefined; | |
} | |
} | |
return data; | |
} | |
jQuery.extend({ | |
hasData: function( elem ) { | |
return data_user.hasData( elem ) || data_priv.hasData( elem ); | |
}, | |
data: function( elem, name, data ) { | |
return data_user.access( elem, name, data ); | |
}, | |
removeData: function( elem, name ) { | |
data_user.remove( elem, name ); | |
}, | |
// TODO: Now that all calls to _data and _removeData have been replaced | |
// with direct calls to data_priv methods, these can be deprecated. | |
_data: function( elem, name, data ) { | |
return data_priv.access( elem, name, data ); | |
}, | |
_removeData: function( elem, name ) { | |
data_priv.remove( elem, name ); | |
} | |
}); | |
jQuery.fn.extend({ | |
data: function( key, value ) { | |
var i, name, data, | |
elem = this[ 0 ], | |
attrs = elem && elem.attributes; | |
// Gets all values | |
if ( key === undefined ) { | |
if ( this.length ) { | |
data = data_user.get( elem ); | |
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { | |
i = attrs.length; | |
while ( i-- ) { | |
// Support: IE11+ | |
// The attrs elements can be null (#14894) | |
if ( attrs[ i ] ) { | |
name = attrs[ i ].name; | |
if ( name.indexOf( "data-" ) === 0 ) { | |
name = jQuery.camelCase( name.slice(5) ); | |
dataAttr( elem, name, data[ name ] ); | |
} | |
} | |
} | |
data_priv.set( elem, "hasDataAttrs", true ); | |
} | |
} | |
return data; | |
} | |
// Sets multiple values | |
if ( typeof key === "object" ) { | |
return this.each(function() { | |
data_user.set( this, key ); | |
}); | |
} | |
return access( this, function( value ) { | |
var data, | |
camelKey = jQuery.camelCase( key ); | |
// The calling jQuery object (element matches) is not empty | |
// (and therefore has an element appears at this[ 0 ]) and the | |
// `value` parameter was not undefined. An empty jQuery object | |
// will result in `undefined` for elem = this[ 0 ] which will | |
// throw an exception if an attempt to read a data cache is made. | |
if ( elem && value === undefined ) { | |
// Attempt to get data from the cache | |
// with the key as-is | |
data = data_user.get( elem, key ); | |
if ( data !== undefined ) { | |
return data; | |
} | |
// Attempt to get data from the cache | |
// with the key camelized | |
data = data_user.get( elem, camelKey ); | |
if ( data !== undefined ) { | |
return data; | |
} | |
// Attempt to "discover" the data in | |
// HTML5 custom data-* attrs | |
data = dataAttr( elem, camelKey, undefined ); | |
if ( data !== undefined ) { | |
return data; | |
} | |
// We tried really hard, but the data doesn't exist. | |
return; | |
} | |
// Set the data... | |
this.each(function() { | |
// First, attempt to store a copy or reference of any | |
// data that might've been store with a camelCased key. | |
var data = data_user.get( this, camelKey ); | |
// For HTML5 data-* attribute interop, we have to | |
// store property names with dashes in a camelCase form. | |
// This might not apply to all properties...* | |
data_user.set( this, camelKey, value ); | |
// *... In the case of properties that might _actually_ | |
// have dashes, we need to also store a copy of that | |
// unchanged property. | |
if ( key.indexOf("-") !== -1 && data !== undefined ) { | |
data_user.set( this, key, value ); | |
} | |
}); | |
}, null, value, arguments.length > 1, null, true ); | |
}, | |
removeData: function( key ) { | |
return this.each(function() { | |
data_user.remove( this, key ); | |
}); | |
} | |
}); | |
jQuery.extend({ | |
queue: function( elem, type, data ) { | |
var queue; | |
if ( elem ) { | |
type = ( type || "fx" ) + "queue"; | |
queue = data_priv.get( elem, type ); | |
// Speed up dequeue by getting out quickly if this is just a lookup | |
if ( data ) { | |
if ( !queue || jQuery.isArray( data ) ) { | |
queue = data_priv.access( elem, type, jQuery.makeArray(data) ); | |
} else { | |
queue.push( data ); | |
} | |
} | |
return queue || []; | |
} | |
}, | |
dequeue: function( elem, type ) { | |
type = type || "fx"; | |
var queue = jQuery.queue( elem, type ), | |
startLength = queue.length, | |
fn = queue.shift(), | |
hooks = jQuery._queueHooks( elem, type ), | |
next = function() { | |
jQuery.dequeue( elem, type ); | |
}; | |
// If the fx queue is dequeued, always remove the progress sentinel | |
if ( fn === "inprogress" ) { | |
fn = queue.shift(); | |
startLength--; | |
} | |
if ( fn ) { | |
// Add a progress sentinel to prevent the fx queue from being | |
// automatically dequeued | |
if ( type === "fx" ) { | |
queue.unshift( "inprogress" ); | |
} | |
// clear up the last queue stop function | |
delete hooks.stop; | |
fn.call( elem, next, hooks ); | |
} | |
if ( !startLength && hooks ) { | |
hooks.empty.fire(); | |
} | |
}, | |
// not intended for public consumption - generates a queueHooks object, or returns the current one | |
_queueHooks: function( elem, type ) { | |
var key = type + "queueHooks"; | |
return data_priv.get( elem, key ) || data_priv.access( elem, key, { | |
empty: jQuery.Callbacks("once memory").add(function() { | |
data_priv.remove( elem, [ type + "queue", key ] ); | |
}) | |
}); | |
} | |
}); | |
jQuery.fn.extend({ | |
queue: function( type, data ) { | |
var setter = 2; | |
if ( typeof type !== "string" ) { | |
data = type; | |
type = "fx"; | |
setter--; | |
} | |
if ( arguments.length < setter ) { | |
return jQuery.queue( this[0], type ); | |
} | |
return data === undefined ? | |
this : | |
this.each(function() { | |
var queue = jQuery.queue( this, type, data ); | |
// ensure a hooks for this queue | |
jQuery._queueHooks( this, type ); | |
if ( type === "fx" && queue[0] !== "inprogress" ) { | |
jQuery.dequeue( this, type ); | |
} | |
}); | |
}, | |
dequeue: function( type ) { | |
return this.each(function() { | |
jQuery.dequeue( this, type ); | |
}); | |
}, | |
clearQueue: function( type ) { | |
return this.queue( type || "fx", [] ); | |
}, | |
// Get a promise resolved when queues of a certain type | |
// are emptied (fx is the type by default) | |
promise: function( type, obj ) { | |
var tmp, | |
count = 1, | |
defer = jQuery.Deferred(), | |
elements = this, | |
i = this.length, | |
resolve = function() { | |
if ( !( --count ) ) { | |
defer.resolveWith( elements, [ elements ] ); | |
} | |
}; | |
if ( typeof type !== "string" ) { | |
obj = type; | |
type = undefined; | |
} | |
type = type || "fx"; | |
while ( i-- ) { | |
tmp = data_priv.get( elements[ i ], type + "queueHooks" ); | |
if ( tmp && tmp.empty ) { | |
count++; | |
tmp.empty.add( resolve ); | |
} | |
} | |
resolve(); | |
return defer.promise( obj ); | |
} | |
}); | |
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; | |
var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; | |
var isHidden = function( elem, el ) { | |
// isHidden might be called from jQuery#filter function; | |
// in that case, element will be second argument | |
elem = el || elem; | |
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); | |
}; | |
var rcheckableType = (/^(?:checkbox|radio)$/i); | |
(function() { | |
var fragment = document.createDocumentFragment(), | |
div = fragment.appendChild( document.createElement( "div" ) ), | |
input = document.createElement( "input" ); | |
// #11217 - WebKit loses check when the name is after the checked attribute | |
// Support: Windows Web Apps (WWA) | |
// `name` and `type` need .setAttribute for WWA | |
input.setAttribute( "type", "radio" ); | |
input.setAttribute( "checked", "checked" ); | |
input.setAttribute( "name", "t" ); | |
div.appendChild( input ); | |
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 | |
// old WebKit doesn't clone checked state correctly in fragments | |
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; | |
// Make sure textarea (and checkbox) defaultValue is properly cloned | |
// Support: IE9-IE11+ | |
div.innerHTML = "<textarea>x</textarea>"; | |
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; | |
})(); | |
var strundefined = typeof undefined; | |
support.focusinBubbles = "onfocusin" in window; | |
var | |
rkeyEvent = /^key/, | |
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, | |
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, | |
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; | |
function returnTrue() { | |
return true; | |
} | |
function returnFalse() { | |
return false; | |
} | |
function safeActiveElement() { | |
try { | |
return document.activeElement; | |
} catch ( err ) { } | |
} | |
/* | |
* Helper functions for managing events -- not part of the public interface. | |
* Props to Dean Edwards' addEvent library for many of the ideas. | |
*/ | |
jQuery.event = { | |
global: {}, | |
add: function( elem, types, handler, data, selector ) { | |
var handleObjIn, eventHandle, tmp, | |
events, t, handleObj, | |
special, handlers, type, namespaces, origType, | |
elemData = data_priv.get( elem ); | |
// Don't attach events to noData or text/comment nodes (but allow plain objects) | |
if ( !elemData ) { | |
return; | |
} | |
// Caller can pass in an object of custom data in lieu of the handler | |
if ( handler.handler ) { | |
handleObjIn = handler; | |
handler = handleObjIn.handler; | |
selector = handleObjIn.selector; | |
} | |
// Make sure that the handler has a unique ID, used to find/remove it later | |
if ( !handler.guid ) { | |
handler.guid = jQuery.guid++; | |
} | |
// Init the element's event structure and main handler, if this is the first | |
if ( !(events = elemData.events) ) { | |
events = elemData.events = {}; | |
} | |
if ( !(eventHandle = elemData.handle) ) { | |
eventHandle = elemData.handle = function( e ) { | |
// Discard the second event of a jQuery.event.trigger() and | |
// when an event is called after a page has unloaded | |
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? | |
jQuery.event.dispatch.apply( elem, arguments ) : undefined; | |
}; | |
} | |
// Handle multiple events separated by a space | |
types = ( types || "" ).match( rnotwhite ) || [ "" ]; | |
t = types.length; | |
while ( t-- ) { | |
tmp = rtypenamespace.exec( types[t] ) || []; | |
type = origType = tmp[1]; | |
namespaces = ( tmp[2] || "" ).split( "." ).sort(); | |
// There *must* be a type, no attaching namespace-only handlers | |
if ( !type ) { | |
continue; | |
} | |
// If event changes its type, use the special event handlers for the changed type | |
special = jQuery.event.special[ type ] || {}; | |
// If selector defined, determine special event api type, otherwise given type | |
type = ( selector ? special.delegateType : special.bindType ) || type; | |
// Update special based on newly reset type | |
special = jQuery.event.special[ type ] || {}; | |
// handleObj is passed to all event handlers | |
handleObj = jQuery.extend({ | |
type: type, | |
origType: origType, | |
data: data, | |
handler: handler, | |
guid: handler.guid, | |
selector: selector, | |
needsContext: selector && jQuery.expr.match.needsContext.test( selector ), | |
namespace: namespaces.join(".") | |
}, handleObjIn ); | |
// Init the event handler queue if we're the first | |
if ( !(handlers = events[ type ]) ) { | |
handlers = events[ type ] = []; | |
handlers.delegateCount = 0; | |
// Only use addEventListener if the special events handler returns false | |
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { | |
if ( elem.addEventListener ) { | |
elem.addEventListener( type, eventHandle, false ); | |
} | |
} | |
} | |
if ( special.add ) { | |
special.add.call( elem, handleObj ); | |
if ( !handleObj.handler.guid ) { | |
handleObj.handler.guid = handler.guid; | |
} | |
} | |
// Add to the element's handler list, delegates in front | |
if ( selector ) { | |
handlers.splice( handlers.delegateCount++, 0, handleObj ); | |
} else { | |
handlers.push( handleObj ); | |
} | |
// Keep track of which events have ever been used, for event optimization | |
jQuery.event.global[ type ] = true; | |
} | |
}, | |
// Detach an event or set of events from an element | |
remove: function( elem, types, handler, selector, mappedTypes ) { | |
var j, origCount, tmp, | |
events, t, handleObj, | |
special, handlers, type, namespaces, origType, | |
elemData = data_priv.hasData( elem ) && data_priv.get( elem ); | |
if ( !elemData || !(events = elemData.events) ) { | |
return; | |
} | |
// Once for each type.namespace in types; type may be omitted | |
types = ( types || "" ).match( rnotwhite ) || [ "" ]; | |
t = types.length; | |
while ( t-- ) { | |
tmp = rtypenamespace.exec( types[t] ) || []; | |
type = origType = tmp[1]; | |
namespaces = ( tmp[2] || "" ).split( "." ).sort(); | |
// Unbind all events (on this namespace, if provided) for the element | |
if ( !type ) { | |
for ( type in events ) { | |
jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); | |
} | |
continue; | |
} | |
special = jQuery.event.special[ type ] || {}; | |
type = ( selector ? special.delegateType : special.bindType ) || type; | |
handlers = events[ type ] || []; | |
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); | |
// Remove matching events | |
origCount = j = handlers.length; | |
while ( j-- ) { | |
handleObj = handlers[ j ]; | |
if ( ( mappedTypes || origType === handleObj.origType ) && | |
( !handler || handler.guid === handleObj.guid ) && | |
( !tmp || tmp.test( handleObj.namespace ) ) && | |
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { | |
handlers.splice( j, 1 ); | |
if ( handleObj.selector ) { | |
handlers.delegateCount--; | |
} | |
if ( special.remove ) { | |
special.remove.call( elem, handleObj ); | |
} | |
} | |
} | |
// Remove generic event handler if we removed something and no more handlers exist | |
// (avoids potential for endless recursion during removal of special event handlers) | |
if ( origCount && !handlers.length ) { | |
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { | |
jQuery.removeEvent( elem, type, elemData.handle ); | |
} | |
delete events[ type ]; | |
} | |
} | |
// Remove the expando if it's no longer used | |
if ( jQuery.isEmptyObject( events ) ) { | |
delete elemData.handle; | |
data_priv.remove( elem, "events" ); | |
} | |
}, | |
trigger: function( event, data, elem, onlyHandlers ) { | |
var i, cur, tmp, bubbleType, ontype, handle, special, | |
eventPath = [ elem || document ], | |
type = hasOwn.call( event, "type" ) ? event.type : event, | |
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; | |
cur = tmp = elem = elem || document; | |
// Don't do events on text and comment nodes | |
if ( elem.nodeType === 3 || elem.nodeType === 8 ) { | |
return; | |
} | |
// focus/blur morphs to focusin/out; ensure we're not firing them right now | |
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { | |
return; | |
} | |
if ( type.indexOf(".") >= 0 ) { | |
// Namespaced trigger; create a regexp to match event type in handle() | |
namespaces = type.split("."); | |
type = namespaces.shift(); | |
namespaces.sort(); | |
} | |
ontype = type.indexOf(":") < 0 && "on" + type; | |
// Caller can pass in a jQuery.Event object, Object, or just an event type string | |
event = event[ jQuery.expando ] ? | |
event : | |
new jQuery.Event( type, typeof event === "object" && event ); | |
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) | |
event.isTrigger = onlyHandlers ? 2 : 3; | |
event.namespace = namespaces.join("."); | |
event.namespace_re = event.namespace ? | |
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : | |
null; | |
// Clean up the event in case it is being reused | |
event.result = undefined; | |
if ( !event.target ) { | |
event.target = elem; | |
} | |
// Clone any incoming data and prepend the event, creating the handler arg list | |
data = data == null ? | |
[ event ] : | |
jQuery.makeArray( data, [ event ] ); | |
// Allow special events to draw outside the lines | |
special = jQuery.event.special[ type ] || {}; | |
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { | |
return; | |
} | |
// Determine event propagation path in advance, per W3C events spec (#9951) | |
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724) | |
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { | |
bubbleType = special.delegateType || type; | |
if ( !rfocusMorph.test( bubbleType + type ) ) { | |
cur = cur.parentNode; | |
} | |
for ( ; cur; cur = cur.parentNode ) { | |
eventPath.push( cur ); | |
tmp = cur; | |
} | |
// Only add window if we got to document (e.g., not plain obj or detached DOM) | |
if ( tmp === (elem.ownerDocument || document) ) { | |
eventPath.push( tmp.defaultView || tmp.parentWindow || window ); | |
} | |
} | |
// Fire handlers on the event path | |
i = 0; | |
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { | |
event.type = i > 1 ? | |
bubbleType : | |
special.bindType || type; | |
// jQuery handler | |
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); | |
if ( handle ) { | |
handle.apply( cur, data ); | |
} | |
// Native handler | |
handle = ontype && cur[ ontype ]; | |
if ( handle && handle.apply && jQuery.acceptData( cur ) ) { | |
event.result = handle.apply( cur, data ); | |
if ( event.result === false ) { | |
event.preventDefault(); | |
} | |
} | |
} | |
event.type = type; | |
// If nobody prevented the default action, do it now | |
if ( !onlyHandlers && !event.isDefaultPrevented() ) { | |
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && | |
jQuery.acceptData( elem ) ) { | |
// Call a native DOM method on the target with the same name name as the event. | |
// Don't do default actions on window, that's where global variables be (#6170) | |
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { | |
// Don't re-trigger an onFOO event when we call its FOO() method | |
tmp = elem[ ontype ]; | |
if ( tmp ) { | |
elem[ ontype ] = null; | |
} | |
// Prevent re-triggering of the same event, since we already bubbled it above | |
jQuery.event.triggered = type; | |
elem[ type ](); | |
jQuery.event.triggered = undefined; | |
if ( tmp ) { | |
elem[ ontype ] = tmp; | |
} | |
} | |
} | |
} | |
return event.result; | |
}, | |
dispatch: function( event ) { | |
// Make a writable jQuery.Event from the native event object | |
event = jQuery.event.fix( event ); | |
var i, j, ret, matched, handleObj, | |
handlerQueue = [], | |
args = slice.call( arguments ), | |
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], | |
special = jQuery.event.special[ event.type ] || {}; | |
// Use the fix-ed jQuery.Event rather than the (read-only) native event | |
args[0] = event; | |
event.delegateTarget = this; | |
// Call the preDispatch hook for the mapped type, and let it bail if desired | |
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { | |
return; | |
} | |
// Determine handlers | |
handlerQueue = jQuery.event.handlers.call( this, event, handlers ); | |
// Run delegates first; they may want to stop propagation beneath us | |
i = 0; | |
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { | |
event.currentTarget = matched.elem; | |
j = 0; | |
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { | |
// Triggered event must either 1) have no namespace, or | |
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). | |
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { | |
event.handleObj = handleObj; | |
event.data = handleObj.data; | |
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) | |
.apply( matched.elem, args ); | |
if ( ret !== undefined ) { | |
if ( (event.result = ret) === false ) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
} | |
} | |
} | |
} | |
} | |
// Call the postDispatch hook for the mapped type | |
if ( special.postDispatch ) { | |
special.postDispatch.call( this, event ); | |
} | |
return event.result; | |
}, | |
handlers: function( event, handlers ) { | |
var i, matches, sel, handleObj, | |
handlerQueue = [], | |
delegateCount = handlers.delegateCount, | |
cur = event.target; | |
// Find delegate handlers | |
// Black-hole SVG <use> instance trees (#13180) | |
// Avoid non-left-click bubbling in Firefox (#3861) | |
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { | |
for ( ; cur !== this; cur = cur.parentNode || this ) { | |
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) | |
if ( cur.disabled !== true || event.type !== "click" ) { | |
matches = []; | |
for ( i = 0; i < delegateCount; i++ ) { | |
handleObj = handlers[ i ]; | |
// Don't conflict with Object.prototype properties (#13203) | |
sel = handleObj.selector + " "; | |
if ( matches[ sel ] === undefined ) { | |
matches[ sel ] = handleObj.needsContext ? | |
jQuery( sel, this ).index( cur ) >= 0 : | |
jQuery.find( sel, this, null, [ cur ] ).length; | |
} | |
if ( matches[ sel ] ) { | |
matches.push( handleObj ); | |
} | |
} | |
if ( matches.length ) { | |
handlerQueue.push({ elem: cur, handlers: matches }); | |
} | |
} | |
} | |
} | |
// Add the remaining (directly-bound) handlers | |
if ( delegateCount < handlers.length ) { | |
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); | |
} | |
return handlerQueue; | |
}, | |
// Includes some event props shared by KeyEvent and MouseEvent | |
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), | |
fixHooks: {}, | |
keyHooks: { | |
props: "char charCode key keyCode".split(" "), | |
filter: function( event, original ) { | |
// Add which for key events | |
if ( event.which == null ) { | |
event.which = original.charCode != null ? original.charCode : original.keyCode; | |
} | |
return event; | |
} | |
}, | |
mouseHooks: { | |
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), | |
filter: function( event, original ) { | |
var eventDoc, doc, body, | |
button = original.button; | |
// Calculate pageX/Y if missing and clientX/Y available | |
if ( event.pageX == null && original.clientX != null ) { | |
eventDoc = event.target.ownerDocument || document; | |
doc = eventDoc.documentElement; | |
body = eventDoc.body; | |
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); | |
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); | |
} | |
// Add which for click: 1 === left; 2 === middle; 3 === right | |
// Note: button is not normalized, so don't use it | |
if ( !event.which && button !== undefined ) { | |
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); | |
} | |
return event; | |
} | |
}, | |
fix: function( event ) { | |
if ( event[ jQuery.expando ] ) { | |
return event; | |
} | |
// Create a writable copy of the event object and normalize some properties | |
var i, prop, copy, | |
type = event.type, | |
originalEvent = event, | |
fixHook = this.fixHooks[ type ]; | |
if ( !fixHook ) { | |
this.fixHooks[ type ] = fixHook = | |
rmouseEvent.test( type ) ? this.mouseHooks : | |
rkeyEvent.test( type ) ? this.keyHooks : | |
{}; | |
} | |
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; | |
event = new jQuery.Event( originalEvent ); | |
i = copy.length; | |
while ( i-- ) { | |
prop = copy[ i ]; | |
event[ prop ] = originalEvent[ prop ]; | |
} | |
// Support: Cordova 2.5 (WebKit) (#13255) | |
// All events should have a target; Cordova deviceready doesn't | |
if ( !event.target ) { | |
event.target = document; | |
} | |
// Support: Safari 6.0+, Chrome < 28 | |
// Target should not be a text node (#504, #13143) | |
if ( event.target.nodeType === 3 ) { | |
event.target = event.target.parentNode; | |
} | |
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; | |
}, | |
special: { | |
load: { | |
// Prevent triggered image.load events from bubbling to window.load | |
noBubble: true | |
}, | |
focus: { | |
// Fire native event if possible so blur/focus sequence is correct | |
trigger: function() { | |
if ( this !== safeActiveElement() && this.focus ) { | |
this.focus(); | |
return false; | |
} | |
}, | |
delegateType: "focusin" | |
}, | |
blur: { | |
trigger: function() { | |
if ( this === safeActiveElement() && this.blur ) { | |
this.blur(); | |
return false; | |
} | |
}, | |
delegateType: "focusout" | |
}, | |
click: { | |
// For checkbox, fire native event so checked state will be right | |
trigger: function() { | |
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { | |
this.click(); | |
return false; | |
} | |
}, | |
// For cross-browser consistency, don't fire native .click() on links | |
_default: function( event ) { | |
return jQuery.nodeName( event.target, "a" ); | |
} | |
}, | |
beforeunload: { | |
postDispatch: function( event ) { | |
// Support: Firefox 20+ | |
// Firefox doesn't alert if the returnValue field is not set. | |
if ( event.result !== undefined && event.originalEvent ) { | |
event.originalEvent.returnValue = event.result; | |
} | |
} | |
} | |
}, | |
simulate: function( type, elem, event, bubble ) { | |
// Piggyback on a donor event to simulate a different one. | |
// Fake originalEvent to avoid donor's stopPropagation, but if the | |
// simulated event prevents default then we do the same on the donor. | |
var e = jQuery.extend( | |
new jQuery.Event(), | |
event, | |
{ | |
type: type, | |
isSimulated: true, | |
originalEvent: {} | |
} | |
); | |
if ( bubble ) { | |
jQuery.event.trigger( e, null, elem ); | |
} else { | |
jQuery.event.dispatch.call( elem, e ); | |
} | |
if ( e.isDefaultPrevented() ) { | |
event.preventDefault(); | |
} | |
} | |
}; | |
jQuery.removeEvent = function( elem, type, handle ) { | |
if ( elem.removeEventListener ) { | |
elem.removeEventListener( type, handle, false ); | |
} | |
}; | |
jQuery.Event = function( src, props ) { | |
// Allow instantiation without the 'new' keyword | |
if ( !(this instanceof jQuery.Event) ) { | |
return new jQuery.Event( src, props ); | |
} | |
// Event object | |
if ( src && src.type ) { | |
this.originalEvent = src; | |
this.type = src.type; | |
// Events bubbling up the document may have been marked as prevented | |
// by a handler lower down the tree; reflect the correct value. | |
this.isDefaultPrevented = src.defaultPrevented || | |
src.defaultPrevented === undefined && | |
// Support: Android < 4.0 | |
src.returnValue === false ? | |
returnTrue : | |
returnFalse; | |
// Event type | |
} else { | |
this.type = src; | |
} | |
// Put explicitly provided properties onto the event object | |
if ( props ) { | |
jQuery.extend( this, props ); | |
} | |
// Create a timestamp if incoming event doesn't have one | |
this.timeStamp = src && src.timeStamp || jQuery.now(); | |
// Mark it as fixed | |
this[ jQuery.expando ] = true; | |
}; | |
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding | |
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html | |
jQuery.Event.prototype = { | |
isDefaultPrevented: returnFalse, | |
isPropagationStopped: returnFalse, | |
isImmediatePropagationStopped: returnFalse, | |
preventDefault: function() { | |
var e = this.originalEvent; | |
this.isDefaultPrevented = returnTrue; | |
if ( e && e.preventDefault ) { | |
e.preventDefault(); | |
} | |
}, | |
stopPropagation: function() { | |
var e = this.originalEvent; | |
this.isPropagationStopped = returnTrue; | |
if ( e && e.stopPropagation ) { | |
e.stopPropagation(); | |
} | |
}, | |
stopImmediatePropagation: function() { | |
var e = this.originalEvent; | |
this.isImmediatePropagationStopped = returnTrue; | |
if ( e && e.stopImmediatePropagation ) { | |
e.stopImmediatePropagation(); | |
} | |
this.stopPropagation(); | |
} | |
}; | |
// Create mouseenter/leave events using mouseover/out and event-time checks | |
// Support: Chrome 15+ | |
jQuery.each({ | |
mouseenter: "mouseover", | |
mouseleave: "mouseout", | |
pointerenter: "pointerover", | |
pointerleave: "pointerout" | |
}, function( orig, fix ) { | |
jQuery.event.special[ orig ] = { | |
delegateType: fix, | |
bindType: fix, | |
handle: function( event ) { | |
var ret, | |
target = this, | |
related = event.relatedTarget, | |
handleObj = event.handleObj; | |
// For mousenter/leave call the handler if related is outside the target. | |
// NB: No relatedTarget if the mouse left/entered the browser window | |
if ( !related || (related !== target && !jQuery.contains( target, related )) ) { | |
event.type = handleObj.origType; | |
ret = handleObj.handler.apply( this, arguments ); | |
event.type = fix; | |
} | |
return ret; | |
} | |
}; | |
}); | |
// Create "bubbling" focus and blur events | |
// Support: Firefox, Chrome, Safari | |
if ( !support.focusinBubbles ) { | |
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { | |
// Attach a single capturing handler on the document while someone wants focusin/focusout | |
var handler = function( event ) { | |
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); | |
}; | |
jQuery.event.special[ fix ] = { | |
setup: function() { | |
var doc = this.ownerDocument || this, | |
attaches = data_priv.access( doc, fix ); | |
if ( !attaches ) { | |
doc.addEventListener( orig, handler, true ); | |
} | |
data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); | |
}, | |
teardown: function() { | |
var doc = this.ownerDocument || this, | |
attaches = data_priv.access( doc, fix ) - 1; | |
if ( !attaches ) { | |
doc.removeEventListener( orig, handler, true ); | |
data_priv.remove( doc, fix ); | |
} else { | |
data_priv.access( doc, fix, attaches ); | |
} | |
} | |
}; | |
}); | |
} | |
jQuery.fn.extend({ | |
on: function( types, selector, data, fn, /*INTERNAL*/ one ) { | |
var origFn, type; | |
// Types can be a map of types/handlers | |
if ( typeof types === "object" ) { | |
// ( types-Object, selector, data ) | |
if ( typeof selector !== "string" ) { | |
// ( types-Object, data ) | |
data = data || selector; | |
selector = undefined; | |
} | |
for ( type in types ) { | |
this.on( type, selector, data, types[ type ], one ); | |
} | |
return this; | |
} | |
if ( data == null && fn == null ) { | |
// ( types, fn ) | |
fn = selector; | |
data = selector = undefined; | |
} else if ( fn == null ) { | |
if ( typeof selector === "string" ) { | |
// ( types, selector, fn ) | |
fn = data; | |
data = undefined; | |
} else { | |
// ( types, data, fn ) | |
fn = data; | |
data = selector; | |
selector = undefined; | |
} | |
} | |
if ( fn === false ) { | |
fn = returnFalse; | |
} else if ( !fn ) { | |
return this; | |
} | |
if ( one === 1 ) { | |
origFn = fn; | |
fn = function( event ) { | |
// Can use an empty set, since event contains the info | |
jQuery().off( event ); | |
return origFn.apply( this, arguments ); | |
}; | |
// Use same guid so caller can remove using origFn | |
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); | |
} | |
return this.each( function() { | |
jQuery.event.add( this, types, fn, data, selector ); | |
}); | |
}, | |
one: function( types, selector, data, fn ) { | |
return this.on( types, selector, data, fn, 1 ); | |
}, | |
off: function( types, selector, fn ) { | |
var handleObj, type; | |
if ( types && types.preventDefault && types.handleObj ) { | |
// ( event ) dispatched jQuery.Event | |
handleObj = types.handleObj; | |
jQuery( types.delegateTarget ).off( | |
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, | |
handleObj.selector, | |
handleObj.handler | |
); | |
return this; | |
} | |
if ( typeof types === "object" ) { | |
// ( types-object [, selector] ) | |
for ( type in types ) { | |
this.off( type, selector, types[ type ] ); | |
} | |
return this; | |
} | |
if ( selector === false || typeof selector === "function" ) { | |
// ( types [, fn] ) | |
fn = selector; | |
selector = undefined; | |
} | |
if ( fn === false ) { | |
fn = returnFalse; | |
} | |
return this.each(function() { | |
jQuery.event.remove( this, types, fn, selector ); | |
}); | |
}, | |
trigger: function( type, data ) { | |
return this.each(function() { | |
jQuery.event.trigger( type, data, this ); | |
}); | |
}, | |
triggerHandler: function( type, data ) { | |
var elem = this[0]; | |
if ( elem ) { | |
return jQuery.event.trigger( type, data, elem, true ); | |
} | |
} | |
}); | |
var | |
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, | |
rtagName = /<([\w:]+)/, | |
rhtml = /<|&#?\w+;/, | |
rnoInnerhtml = /<(?:script|style|link)/i, | |
// checked="checked" or checked | |
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, | |
rscriptType = /^$|\/(?:java|ecma)script/i, | |
rscriptTypeMasked = /^true\/(.*)/, | |
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, | |
// We have to close these tags to support XHTML (#13200) | |
wrapMap = { | |
// Support: IE 9 | |
option: [ 1, "<select multiple='multiple'>", "</select>" ], | |
thead: [ 1, "<table>", "</table>" ], | |
col: [ 2, "<table><colgroup>", "</colgroup></table>" ], | |
tr: [ 2, "<table><tbody>", "</tbody></table>" ], | |
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], | |
_default: [ 0, "", "" ] | |
}; | |
// Support: IE 9 | |
wrapMap.optgroup = wrapMap.option; | |
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; | |
wrapMap.th = wrapMap.td; | |
// Support: 1.x compatibility | |
// Manipulating tables requires a tbody | |
function manipulationTarget( elem, content ) { | |
return jQuery.nodeName( elem, "table" ) && | |
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? | |
elem.getElementsByTagName("tbody")[0] || | |
elem.appendChild( elem.ownerDocument.createElement("tbody") ) : | |
elem; | |
} | |
// Replace/restore the type attribute of script elements for safe DOM manipulation | |
function disableScript( elem ) { | |
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; | |
return elem; | |
} | |
function restoreScript( elem ) { | |
var match = rscriptTypeMasked.exec( elem.type ); | |
if ( match ) { | |
elem.type = match[ 1 ]; | |
} else { | |
elem.removeAttribute("type"); | |
} | |
return elem; | |
} | |
// Mark scripts as having already been evaluated | |
function setGlobalEval( elems, refElements ) { | |
var i = 0, | |
l = elems.length; | |
for ( ; i < l; i++ ) { | |
data_priv.set( | |
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) | |
); | |
} | |
} | |
function cloneCopyEvent( src, dest ) { | |
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; | |
if ( dest.nodeType !== 1 ) { | |
return; | |
} | |
// 1. Copy private data: events, handlers, etc. | |
if ( data_priv.hasData( src ) ) { | |
pdataOld = data_priv.access( src ); | |
pdataCur = data_priv.set( dest, pdataOld ); | |
events = pdataOld.events; | |
if ( events ) { | |
delete pdataCur.handle; | |
pdataCur.events = {}; | |
for ( type in events ) { | |
for ( i = 0, l = events[ type ].length; i < l; i++ ) { | |
jQuery.event.add( dest, type, events[ type ][ i ] ); | |
} | |
} | |
} | |
} | |
// 2. Copy user data | |
if ( data_user.hasData( src ) ) { | |
udataOld = data_user.access( src ); | |
udataCur = jQuery.extend( {}, udataOld ); | |
data_user.set( dest, udataCur ); | |
} | |
} | |
function getAll( context, tag ) { | |
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : | |
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : | |
[]; | |
return tag === undefined || tag && jQuery.nodeName( context, tag ) ? | |
jQuery.merge( [ context ], ret ) : | |
ret; | |
} | |
// Support: IE >= 9 | |
function fixInput( src, dest ) { | |
var nodeName = dest.nodeName.toLowerCase(); | |
// Fails to persist the checked state of a cloned checkbox or radio button. | |
if ( nodeName === "input" && rcheckableType.test( src.type ) ) { | |
dest.checked = src.checked; | |
// Fails to return the selected option to the default selected state when cloning options | |
} else if ( nodeName === "input" || nodeName === "textarea" ) { | |
dest.defaultValue = src.defaultValue; | |
} | |
} | |
jQuery.extend({ | |
clone: function( elem, dataAndEvents, deepDataAndEvents ) { | |
var i, l, srcElements, destElements, | |
clone = elem.cloneNode( true ), | |
inPage = jQuery.contains( elem.ownerDocument, elem ); | |
// Support: IE >= 9 | |
// Fix Cloning issues | |
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && | |
!jQuery.isXMLDoc( elem ) ) { | |
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 | |
destElements = getAll( clone ); | |
srcElements = getAll( elem ); | |
for ( i = 0, l = srcElements.length; i < l; i++ ) { | |
fixInput( srcElements[ i ], destElements[ i ] ); | |
} | |
} | |
// Copy the events from the original to the clone | |
if ( dataAndEvents ) { | |
if ( deepDataAndEvents ) { | |
srcElements = srcElements || getAll( elem ); | |
destElements = destElements || getAll( clone ); | |
for ( i = 0, l = srcElements.length; i < l; i++ ) { | |
cloneCopyEvent( srcElements[ i ], destElements[ i ] ); | |
} | |
} else { | |
cloneCopyEvent( elem, clone ); | |
} | |
} | |
// Preserve script evaluation history | |
destElements = getAll( clone, "script" ); | |
if ( destElements.length > 0 ) { | |
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); | |
} | |
// Return the cloned set | |
return clone; | |
}, | |
buildFragment: function( elems, context, scripts, selection ) { | |
var elem, tmp, tag, wrap, contains, j, | |
fragment = context.createDocumentFragment(), | |
nodes = [], | |
i = 0, | |
l = elems.length; | |
for ( ; i < l; i++ ) { | |
elem = elems[ i ]; | |
if ( elem || elem === 0 ) { | |
// Add nodes directly | |
if ( jQuery.type( elem ) === "object" ) { | |
// Support: QtWebKit | |
// jQuery.merge because push.apply(_, arraylike) throws | |
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); | |
// Convert non-html into a text node | |
} else if ( !rhtml.test( elem ) ) { | |
nodes.push( context.createTextNode( elem ) ); | |
// Convert html into DOM nodes | |
} else { | |
tmp = tmp || fragment.appendChild( context.createElement("div") ); | |
// Deserialize a standard representation | |
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); | |
wrap = wrapMap[ tag ] || wrapMap._default; | |
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; | |
// Descend through wrappers to the right content | |
j = wrap[ 0 ]; | |
while ( j-- ) { | |
tmp = tmp.lastChild; | |
} | |
// Support: QtWebKit | |
// jQuery.merge because push.apply(_, arraylike) throws | |
jQuery.merge( nodes, tmp.childNodes ); | |
// Remember the top-level container | |
tmp = fragment.firstChild; | |
// Fixes #12346 | |
// Support: Webkit, IE | |
tmp.textContent = ""; | |
} | |
} | |
} | |
// Remove wrapper from fragment | |
fragment.textContent = ""; | |
i = 0; | |
while ( (elem = nodes[ i++ ]) ) { | |
// #4087 - If origin and destination elements are the same, and this is | |
// that element, do not do anything | |
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { | |
continue; | |
} | |
contains = jQuery.contains( elem.ownerDocument, elem ); | |
// Append to fragment | |
tmp = getAll( fragment.appendChild( elem ), "script" ); | |
// Preserve script evaluation history | |
if ( contains ) { | |
setGlobalEval( tmp ); | |
} | |
// Capture executables | |
if ( scripts ) { | |
j = 0; | |
while ( (elem = tmp[ j++ ]) ) { | |
if ( rscriptType.test( elem.type || "" ) ) { | |
scripts.push( elem ); | |
} | |
} | |
} | |
} | |
return fragment; | |
}, | |
cleanData: function( elems ) { | |
var data, elem, type, key, | |
special = jQuery.event.special, | |
i = 0; | |
for ( ; (elem = elems[ i ]) !== undefined; i++ ) { | |
if ( jQuery.acceptData( elem ) ) { | |
key = elem[ data_priv.expando ]; | |
if ( key && (data = data_priv.cache[ key ]) ) { | |
if ( data.events ) { | |
for ( type in data.events ) { | |
if ( special[ type ] ) { | |
jQuery.event.remove( elem, type ); | |
// This is a shortcut to avoid jQuery.event.remove's overhead | |
} else { | |
jQuery.removeEvent( elem, type, data.handle ); | |
} | |
} | |
} | |
if ( data_priv.cache[ key ] ) { | |
// Discard any remaining `private` data | |
delete data_priv.cache[ key ]; | |
} | |
} | |
} | |
// Discard any remaining `user` data | |
delete data_user.cache[ elem[ data_user.expando ] ]; | |
} | |
} | |
}); | |
jQuery.fn.extend({ | |
text: function( value ) { | |
return access( this, function( value ) { | |
return value === undefined ? | |
jQuery.text( this ) : | |
this.empty().each(function() { | |
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { | |
this.textContent = value; | |
} | |
}); | |
}, null, value, arguments.length ); | |
}, | |
append: function() { | |
return this.domManip( arguments, function( elem ) { | |
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { | |
var target = manipulationTarget( this, elem ); | |
target.appendChild( elem ); | |
} | |
}); | |
}, | |
prepend: function() { | |
return this.domManip( arguments, function( elem ) { | |
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { | |
var target = manipulationTarget( this, elem ); | |
target.insertBefore( elem, target.firstChild ); | |
} | |
}); | |
}, | |
before: function() { | |
return this.domManip( arguments, function( elem ) { | |
if ( this.parentNode ) { | |
this.parentNode.insertBefore( elem, this ); | |
} | |
}); | |
}, | |
after: function() { | |
return this.domManip( arguments, function( elem ) { | |
if ( this.parentNode ) { | |
this.parentNode.insertBefore( elem, this.nextSibling ); | |
} | |
}); | |
}, | |
remove: function( selector, keepData /* Internal Use Only */ ) { | |
var elem, | |
elems = selector ? jQuery.filter( selector, this ) : this, | |
i = 0; | |
for ( ; (elem = elems[i]) != null; i++ ) { | |
if ( !keepData && elem.nodeType === 1 ) { | |
jQuery.cleanData( getAll( elem ) ); | |
} | |
if ( elem.parentNode ) { | |
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { | |
setGlobalEval( getAll( elem, "script" ) ); | |
} | |
elem.parentNode.removeChild( elem ); | |
} | |
} | |
return this; | |
}, | |
empty: function() { | |
var elem, | |
i = 0; | |
for ( ; (elem = this[i]) != null; i++ ) { | |
if ( elem.nodeType === 1 ) { | |
// Prevent memory leaks | |
jQuery.cleanData( getAll( elem, false ) ); | |
// Remove any remaining nodes | |
elem.textContent = ""; | |
} | |
} | |
return this; | |
}, | |
clone: function( dataAndEvents, deepDataAndEvents ) { | |
dataAndEvents = dataAndEvents == null ? false : dataAndEvents; | |
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; | |
return this.map(function() { | |
return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); | |
}); | |
}, | |
html: function( value ) { | |
return access( this, function( value ) { | |
var elem = this[ 0 ] || {}, | |
i = 0, | |
l = this.length; | |
if ( value === undefined && elem.nodeType === 1 ) { | |
return elem.innerHTML; | |
} | |
// See if we can take a shortcut and just use innerHTML | |
if ( typeof value === "string" && !rnoInnerhtml.test( value ) && | |
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { | |
value = value.replace( rxhtmlTag, "<$1></$2>" ); | |
try { | |
for ( ; i < l; i++ ) { | |
elem = this[ i ] || {}; | |
// Remove element nodes and prevent memory leaks | |
if ( elem.nodeType === 1 ) { | |
jQuery.cleanData( getAll( elem, false ) ); | |
elem.innerHTML = value; | |
} | |
} | |
elem = 0; | |
// If using innerHTML throws an exception, use the fallback method | |
} catch( e ) {} | |
} | |
if ( elem ) { | |
this.empty().append( value ); | |
} | |
}, null, value, arguments.length ); | |
}, | |
replaceWith: function() { | |
var arg = arguments[ 0 ]; | |
// Make the changes, replacing each context element with the new content | |
this.domManip( arguments, function( elem ) { | |
arg = this.parentNode; | |
jQuery.cleanData( getAll( this ) ); | |
if ( arg ) { | |
arg.replaceChild( elem, this ); | |
} | |
}); | |
// Force removal if there was no new content (e.g., from empty arguments) | |
return arg && (arg.length || arg.nodeType) ? this : this.remove(); | |
}, | |
detach: function( selector ) { | |
return this.remove( selector, true ); | |
}, | |
domManip: function( args, callback ) { | |
// Flatten any nested arrays | |
args = concat.apply( [], args ); | |
var fragment, first, scripts, hasScripts, node, doc, | |
i = 0, | |
l = this.length, | |
set = this, | |
iNoClone = l - 1, | |
value = args[ 0 ], | |
isFunction = jQuery.isFunction( value ); | |
// We can't cloneNode fragments that contain checked, in WebKit | |
if ( isFunction || | |
( l > 1 && typeof value === "string" && | |
!support.checkClone && rchecked.test( value ) ) ) { | |
return this.each(function( index ) { | |
var self = set.eq( index ); | |
if ( isFunction ) { | |
args[ 0 ] = value.call( this, index, self.html() ); | |
} | |
self.domManip( args, callback ); | |
}); | |
} | |
if ( l ) { | |
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); | |
first = fragment.firstChild; | |
if ( fragment.childNodes.length === 1 ) { | |
fragment = first; | |
} | |
if ( first ) { | |
scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); | |
hasScripts = scripts.length; | |
// Use the original fragment for the last item instead of the first because it can end up | |
// being emptied incorrectly in certain situations (#8070). | |
for ( ; i < l; i++ ) { | |
node = fragment; | |
if ( i !== iNoClone ) { | |
node = jQuery.clone( node, true, true ); | |
// Keep references to cloned scripts for later restoration | |
if ( hasScripts ) { | |
// Support: QtWebKit | |
// jQuery.merge because push.apply(_, arraylike) throws | |
jQuery.merge( scripts, getAll( node, "script" ) ); | |
} | |
} | |
callback.call( this[ i ], node, i ); | |
} | |
if ( hasScripts ) { | |
doc = scripts[ scripts.length - 1 ].ownerDocument; | |
// Reenable scripts | |
jQuery.map( scripts, restoreScript ); | |
// Evaluate executable scripts on first document insertion | |
for ( i = 0; i < hasScripts; i++ ) { | |
node = scripts[ i ]; | |
if ( rscriptType.test( node.type || "" ) && | |
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { | |
if ( node.src ) { | |
// Optional AJAX dependency, but won't run scripts if not present | |
if ( jQuery._evalUrl ) { | |
jQuery._evalUrl( node.src ); | |
} | |
} else { | |
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); | |
} | |
} | |
} | |
} | |
} | |
} | |
return this; | |
} | |
}); | |
jQuery.each({ | |
appendTo: "append", | |
prependTo: "prepend", | |
insertBefore: "before", | |
insertAfter: "after", | |
replaceAll: "replaceWith" | |
}, function( name, original ) { | |
jQuery.fn[ name ] = function( selector ) { | |
var elems, | |
ret = [], | |
insert = jQuery( selector ), | |
last = insert.length - 1, | |
i = 0; | |
for ( ; i <= last; i++ ) { | |
elems = i === last ? this : this.clone( true ); | |
jQuery( insert[ i ] )[ original ]( elems ); | |
// Support: QtWebKit | |
// .get() because push.apply(_, arraylike) throws | |
push.apply( ret, elems.get() ); | |
} | |
return this.pushStack( ret ); | |
}; | |
}); | |
var iframe, | |
elemdisplay = {}; | |
/** | |
* Retrieve the actual display of a element | |
* @param {String} name nodeName of the element | |
* @param {Object} doc Document object | |
*/ | |
// Called only from within defaultDisplay | |
function actualDisplay( name, doc ) { | |
var style, | |
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), | |
// getDefaultComputedStyle might be reliably used only on attached element | |
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? | |
// Use of this method is a temporary fix (more like optmization) until something better comes along, | |
// since it was removed from specification and supported only in FF | |
style.display : jQuery.css( elem[ 0 ], "display" ); | |
// We don't have any data stored on the element, | |
// so use "detach" method as fast way to get rid of the element | |
elem.detach(); | |
return display; | |
} | |
/** | |
* Try to determine the default display value of an element | |
* @param {String} nodeName | |
*/ | |
function defaultDisplay( nodeName ) { | |
var doc = document, | |
display = elemdisplay[ nodeName ]; | |
if ( !display ) { | |
display = actualDisplay( nodeName, doc ); | |
// If the simple way fails, read from inside an iframe | |
if ( display === "none" || !display ) { | |
// Use the already-created iframe if possible | |
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); | |
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse | |
doc = iframe[ 0 ].contentDocument; | |
// Support: IE | |
doc.write(); | |
doc.close(); | |
display = actualDisplay( nodeName, doc ); | |
iframe.detach(); | |
} | |
// Store the correct default display | |
elemdisplay[ nodeName ] = display; | |
} | |
return display; | |
} | |
var rmargin = (/^margin/); | |
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); | |
var getStyles = function( elem ) { | |
return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); | |
}; | |
function curCSS( elem, name, computed ) { | |
var width, minWidth, maxWidth, ret, | |
style = elem.style; | |
computed = computed || getStyles( elem ); | |
// Support: IE9 | |
// getPropertyValue is only needed for .css('filter') in IE9, see #12537 | |
if ( computed ) { | |
ret = computed.getPropertyValue( name ) || computed[ name ]; | |
} | |
if ( computed ) { | |
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { | |
ret = jQuery.style( elem, name ); | |
} | |
// Support: iOS < 6 | |
// A tribute to the "awesome hack by Dean Edwards" | |
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels | |
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values | |
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { | |
// Remember the original values | |
width = style.width; | |
minWidth = style.minWidth; | |
maxWidth = style.maxWidth; | |
// Put in the new values to get a computed value out | |
style.minWidth = style.maxWidth = style.width = ret; | |
ret = computed.width; | |
// Revert the changed values | |
style.width = width; | |
style.minWidth = minWidth; | |
style.maxWidth = maxWidth; | |
} | |
} | |
return ret !== undefined ? | |
// Support: IE | |
// IE returns zIndex value as an integer. | |
ret + "" : | |
ret; | |
} | |
function addGetHookIf( conditionFn, hookFn ) { | |
// Define the hook, we'll check on the first run if it's really needed. | |
return { | |
get: function() { | |
if ( conditionFn() ) { | |
// Hook not needed (or it's not possible to use it due to missing dependency), | |
// remove it. | |
// Since there are no other hooks for marginRight, remove the whole object. | |
delete this.get; | |
return; | |
} | |
// Hook needed; redefine it so that the support test is not executed again. | |
return (this.get = hookFn).apply( this, arguments ); | |
} | |
}; | |
} | |
(function() { | |
var pixelPositionVal, boxSizingReliableVal, | |
docElem = document.documentElement, | |
container = document.createElement( "div" ), | |
div = document.createElement( "div" ); | |
if ( !div.style ) { | |
return; | |
} | |
div.style.backgroundClip = "content-box"; | |
div.cloneNode( true ).style.backgroundClip = ""; | |
support.clearCloneStyle = div.style.backgroundClip === "content-box"; | |
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + | |
"position:absolute"; | |
container.appendChild( div ); | |
// Executing both pixelPosition & boxSizingReliable tests require only one layout | |
// so they're executed at the same time to save the second computation. | |
function computePixelPositionAndBoxSizingReliable() { | |
div.style.cssText = | |
// Support: Firefox<29, Android 2.3 | |
// Vendor-prefix box-sizing | |
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + | |
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" + | |
"border:1px;padding:1px;width:4px;position:absolute"; | |
div.innerHTML = ""; | |
docElem.appendChild( container ); | |
var divStyle = window.getComputedStyle( div, null ); | |
pixelPositionVal = divStyle.top !== "1%"; | |
boxSizingReliableVal = divStyle.width === "4px"; | |
docElem.removeChild( container ); | |
} | |
// Support: node.js jsdom | |
// Don't assume that getComputedStyle is a property of the global object | |
if ( window.getComputedStyle ) { | |
jQuery.extend( support, { | |
pixelPosition: function() { | |
// This test is executed only once but we still do memoizing | |
// since we can use the boxSizingReliable pre-computing. | |
// No need to check if the test was already performed, though. | |
computePixelPositionAndBoxSizingReliable(); | |
return pixelPositionVal; | |
}, | |
boxSizingReliable: function() { | |
if ( boxSizingReliableVal == null ) { | |
computePixelPositionAndBoxSizingReliable(); | |
} | |
return boxSizingReliableVal; | |
}, | |
reliableMarginRight: function() { | |
// Support: Android 2.3 | |
// Check if div with explicit width and no margin-right incorrectly | |
// gets computed margin-right based on width of container. (#3333) | |
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right | |
// This support function is only executed once so no memoizing is needed. | |
var ret, | |
marginDiv = div.appendChild( document.createElement( "div" ) ); | |
// Reset CSS: box-sizing; display; margin; border; padding | |
marginDiv.style.cssText = div.style.cssText = | |
// Support: Firefox<29, Android 2.3 | |
// Vendor-prefix box-sizing | |
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + | |
"box-sizing:content-box;display:block;margin:0;border:0;padding:0"; | |
marginDiv.style.marginRight = marginDiv.style.width = "0"; | |
div.style.width = "1px"; | |
docElem.appendChild( container ); | |
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); | |
docElem.removeChild( container ); | |
return ret; | |
} | |
}); | |
} | |
})(); | |
// A method for quickly swapping in/out CSS properties to get correct calculations. | |
jQuery.swap = function( elem, options, callback, args ) { | |
var ret, name, | |
old = {}; | |
// Remember the old values, and insert the new ones | |
for ( name in options ) { | |
old[ name ] = elem.style[ name ]; | |
elem.style[ name ] = options[ name ]; | |
} | |
ret = callback.apply( elem, args || [] ); | |
// Revert the old values | |
for ( name in options ) { | |
elem.style[ name ] = old[ name ]; | |
} | |
return ret; | |
}; | |
var | |
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption" | |
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display | |
rdisplayswap = /^(none|table(?!-c[ea]).+)/, | |
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), | |
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), | |
cssShow = { position: "absolute", visibility: "hidden", display: "block" }, | |
cssNormalTransform = { | |
letterSpacing: "0", | |
fontWeight: "400" | |
}, | |
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; | |
// return a css property mapped to a potentially vendor prefixed property | |
function vendorPropName( style, name ) { | |
// shortcut for names that are not vendor prefixed | |
if ( name in style ) { | |
return name; | |
} | |
// check for vendor prefixed names | |
var capName = name[0].toUpperCase() + name.slice(1), | |
origName = name, | |
i = cssPrefixes.length; | |
while ( i-- ) { | |
name = cssPrefixes[ i ] + capName; | |
if ( name in style ) { | |
return name; | |
} | |
} | |
return origName; | |
} | |
function setPositiveNumber( elem, value, subtract ) { | |
var matches = rnumsplit.exec( value ); | |
return matches ? | |
// Guard against undefined "subtract", e.g., when used as in cssHooks | |
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : | |
value; | |
} | |
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { | |
var i = extra === ( isBorderBox ? "border" : "content" ) ? | |
// If we already have the right measurement, avoid augmentation | |
4 : | |
// Otherwise initialize for horizontal or vertical properties | |
name === "width" ? 1 : 0, | |
val = 0; | |
for ( ; i < 4; i += 2 ) { | |
// both box models exclude margin, so add it if we want it | |
if ( extra === "margin" ) { | |
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); | |
} | |
if ( isBorderBox ) { | |
// border-box includes padding, so remove it if we want content | |
if ( extra === "content" ) { | |
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); | |
} | |
// at this point, extra isn't border nor margin, so remove border | |
if ( extra !== "margin" ) { | |
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); | |
} | |
} else { | |
// at this point, extra isn't content, so add padding | |
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); | |
// at this point, extra isn't content nor padding, so add border | |
if ( extra !== "padding" ) { | |
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); | |
} | |
} | |
} | |
return val; | |
} | |
function getWidthOrHeight( elem, name, extra ) { | |
// Start with offset property, which is equivalent to the border-box value | |
var valueIsBorderBox = true, | |
val = name === "width" ? elem.offsetWidth : elem.offsetHeight, | |
styles = getStyles( elem ), | |
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; | |
// some non-html elements return undefined for offsetWidth, so check for null/undefined | |
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 | |
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 | |
if ( val <= 0 || val == null ) { | |
// Fall back to computed then uncomputed css if necessary | |
val = curCSS( elem, name, styles ); | |
if ( val < 0 || val == null ) { | |
val = elem.style[ name ]; | |
} | |
// Computed unit is not pixels. Stop here and return. | |
if ( rnumnonpx.test(val) ) { | |
return val; | |
} | |
// we need the check for style in case a browser which returns unreliable values | |
// for getComputedStyle silently falls back to the reliable elem.style | |
valueIsBorderBox = isBorderBox && | |
( support.boxSizingReliable() || val === elem.style[ name ] ); | |
// Normalize "", auto, and prepare for extra | |
val = parseFloat( val ) || 0; | |
} | |
// use the active box-sizing model to add/subtract irrelevant styles | |
return ( val + | |
augmentWidthOrHeight( | |
elem, | |
name, | |
extra || ( isBorderBox ? "border" : "content" ), | |
valueIsBorderBox, | |
styles | |
) | |
) + "px"; | |
} | |
function showHide( elements, show ) { | |
var display, elem, hidden, | |
values = [], | |
index = 0, | |
length = elements.length; | |
for ( ; index < length; index++ ) { | |
elem = elements[ index ]; | |
if ( !elem.style ) { | |
continue; | |
} | |
values[ index ] = data_priv.get( elem, "olddisplay" ); | |
display = elem.style.display; | |
if ( show ) { | |
// Reset the inline display of this element to learn if it is | |
// being hidden by cascaded rules or not | |
if ( !values[ index ] && display === "none" ) { | |
elem.style.display = ""; | |
} | |
// Set elements which have been overridden with display: none | |
// in a stylesheet to whatever the default browser style is | |
// for such an element | |
if ( elem.style.display === "" && isHidden( elem ) ) { | |
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); | |
} | |
} else { | |
hidden = isHidden( elem ); | |
if ( display !== "none" || !hidden ) { | |
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); | |
} | |
} | |
} | |
// Set the display of most of the elements in a second loop | |
// to avoid the constant reflow | |
for ( index = 0; index < length; index++ ) { | |
elem = elements[ index ]; | |
if ( !elem.style ) { | |
continue; | |
} | |
if ( !show || elem.style.display === "none" || elem.style.display === "" ) { | |
elem.style.display = show ? values[ index ] || "" : "none"; | |
} | |
} | |
return elements; | |
} | |
jQuery.extend({ | |
// Add in style property hooks for overriding the default | |
// behavior of getting and setting a style property | |
cssHooks: { | |
opacity: { | |
get: function( elem, computed ) { | |
if ( computed ) { | |
// We should always get a number back from opacity | |
var ret = curCSS( elem, "opacity" ); | |
return ret === "" ? "1" : ret; | |
} | |
} | |
} | |
}, | |
// Don't automatically add "px" to these possibly-unitless properties | |
cssNumber: { | |
"columnCount": true, | |
"fillOpacity": true, | |
"flexGrow": true, | |
"flexShrink": true, | |
"fontWeight": true, | |
"lineHeight": true, | |
"opacity": true, | |
"order": true, | |
"orphans": true, | |
"widows": true, | |
"zIndex": true, | |
"zoom": true | |
}, | |
// Add in properties whose names you wish to fix before | |
// setting or getting the value | |
cssProps: { | |
// normalize float css property | |
"float": "cssFloat" | |
}, | |
// Get and set the style property on a DOM Node | |
style: function( elem, name, value, extra ) { | |
// Don't set styles on text and comment nodes | |
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { | |
return; | |
} | |
// Make sure that we're working with the right name | |
var ret, type, hooks, | |
origName = jQuery.camelCase( name ), | |
style = elem.style; | |
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); | |
// gets hook for the prefixed version | |
// followed by the unprefixed version | |
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; | |
// Check if we're setting a value | |
if ( value !== undefined ) { | |
type = typeof value; | |
// convert relative number strings (+= or -=) to relative numbers. #7345 | |
if ( type === "string" && (ret = rrelNum.exec( value )) ) { | |
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); | |
// Fixes bug #9237 | |
type = "number"; | |
} | |
// Make sure that null and NaN values aren't set. See: #7116 | |
if ( value == null || value !== value ) { | |
return; | |
} | |
// If a number was passed in, add 'px' to the (except for certain CSS properties) | |
if ( type === "number" && !jQuery.cssNumber[ origName ] ) { | |
value += "px"; | |
} | |
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks, | |
// but it would mean to define eight (for every problematic property) identical functions | |
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { | |
style[ name ] = "inherit"; | |
} | |
// If a hook was provided, use that value, otherwise just set the specified value | |
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { | |
style[ name ] = value; | |
} | |
} else { | |
// If a hook was provided get the non-computed value from there | |
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { | |
return ret; | |
} | |
// Otherwise just get the value from the style object | |
return style[ name ]; | |
} | |
}, | |
css: function( elem, name, extra, styles ) { | |
var val, num, hooks, | |
origName = jQuery.camelCase( name ); | |
// Make sure that we're working with the right name | |
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); | |
// gets hook for the prefixed version | |
// followed by the unprefixed version | |
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; | |
// If a hook was provided get the computed value from there | |
if ( hooks && "get" in hooks ) { | |
val = hooks.get( elem, true, extra ); | |
} | |
// Otherwise, if a way to get the computed value exists, use that | |
if ( val === undefined ) { | |
val = curCSS( elem, name, styles ); | |
} | |
//convert "normal" to computed value | |
if ( val === "normal" && name in cssNormalTransform ) { | |
val = cssNormalTransform[ name ]; | |
} | |
// Return, converting to number if forced or a qualifier was provided and val looks numeric | |
if ( extra === "" || extra ) { | |
num = parseFloat( val ); | |
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; | |
} | |
return val; | |
} | |
}); | |
jQuery.each([ "height", "width" ], function( i, name ) { | |
jQuery.cssHooks[ name ] = { | |
get: function( elem, computed, extra ) { | |
if ( computed ) { | |
// certain elements can have dimension info if we invisibly show them | |
// however, it must have a current display style that would benefit from this | |
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? | |
jQuery.swap( elem, cssShow, function() { | |
return getWidthOrHeight( elem, name, extra ); | |
}) : | |
getWidthOrHeight( elem, name, extra ); | |
} | |
}, | |
set: function( elem, value, extra ) { | |
var styles = extra && getStyles( elem ); | |
return setPositiveNumber( elem, value, extra ? | |
augmentWidthOrHeight( | |
elem, | |
name, | |
extra, | |
jQuery.css( elem, "boxSizing", false, styles ) === "border-box", | |
styles | |
) : 0 | |
); | |
} | |
}; | |
}); | |
// Support: Android 2.3 | |
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, | |
function( elem, computed ) { | |
if ( computed ) { | |
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right | |
// Work around by temporarily setting element display to inline-block | |
return jQuery.swap( elem, { "display": "inline-block" }, | |
curCSS, [ elem, "marginRight" ] ); | |
} | |
} | |
); | |
// These hooks are used by animate to expand properties | |
jQuery.each({ | |
margin: "", | |
padding: "", | |
border: "Width" | |
}, function( prefix, suffix ) { | |
jQuery.cssHooks[ prefix + suffix ] = { | |
expand: function( value ) { | |
var i = 0, | |
expanded = {}, | |
// assumes a single number if not a string | |
parts = typeof value === "string" ? value.split(" ") : [ value ]; | |
for ( ; i < 4; i++ ) { | |
expanded[ prefix + cssExpand[ i ] + suffix ] = | |
parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; | |
} | |
return expanded; | |
} | |
}; | |
if ( !rmargin.test( prefix ) ) { | |
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; | |
} | |
}); | |
jQuery.fn.extend({ | |
css: function( name, value ) { | |
return access( this, function( elem, name, value ) { | |
var styles, len, | |
map = {}, | |
i = 0; | |
if ( jQuery.isArray( name ) ) { | |
styles = getStyles( elem ); | |
len = name.length; | |
for ( ; i < len; i++ ) { | |
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); | |
} | |
return map; | |
} | |
return value !== undefined ? | |
jQuery.style( elem, name, value ) : | |
jQuery.css( elem, name ); | |
}, name, value, arguments.length > 1 ); | |
}, | |
show: function() { | |
return showHide( this, true ); | |
}, | |
hide: function() { | |
return showHide( this ); | |
}, | |
toggle: function( state ) { | |
if ( typeof state === "boolean" ) { | |
return state ? this.show() : this.hide(); | |
} | |
return this.each(function() { | |
if ( isHidden( this ) ) { | |
jQuery( this ).show(); | |
} else { | |
jQuery( this ).hide(); | |
} | |
}); | |
} | |
}); | |
function Tween( elem, options, prop, end, easing ) { | |
return new Tween.prototype.init( elem, options, prop, end, easing ); | |
} | |
jQuery.Tween = Tween; | |
Tween.prototype = { | |
constructor: Tween, | |
init: function( elem, options, prop, end, easing, unit ) { | |
this.elem = elem; | |
this.prop = prop; | |
this.easing = easing || "swing"; | |
this.options = options; | |
this.start = this.now = this.cur(); | |
this.end = end; | |
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); | |
}, | |
cur: function() { | |
var hooks = Tween.propHooks[ this.prop ]; | |
return hooks && hooks.get ? | |
hooks.get( this ) : | |
Tween.propHooks._default.get( this ); | |
}, | |
run: function( percent ) { | |
var eased, | |
hooks = Tween.propHooks[ this.prop ]; | |
if ( this.options.duration ) { | |
this.pos = eased = jQuery.easing[ this.easing ]( | |
percent, this.options.duration * percent, 0, 1, this.options.duration | |
); | |
} else { | |
this.pos = eased = percent; | |
} | |
this.now = ( this.end - this.start ) * eased + this.start; | |
if ( this.options.step ) { | |
this.options.step.call( this.elem, this.now, this ); | |
} | |
if ( hooks && hooks.set ) { | |
hooks.set( this ); | |
} else { | |
Tween.propHooks._default.set( this ); | |
} | |
return this; | |
} | |
}; | |
Tween.prototype.init.prototype = Tween.prototype; | |
Tween.propHooks = { | |
_default: { | |
get: function( tween ) { | |
var result; | |
if ( tween.elem[ tween.prop ] != null && | |
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { | |
return tween.elem[ tween.prop ]; | |
} | |
// passing an empty string as a 3rd parameter to .css will automatically | |
// attempt a parseFloat and fallback to a string if the parse fails | |
// so, simple values such as "10px" are parsed to Float. | |
// complex values such as "rotate(1rad)" are returned as is. | |
result = jQuery.css( tween.elem, tween.prop, "" ); | |
// Empty strings, null, undefined and "auto" are converted to 0. | |
return !result || result === "auto" ? 0 : result; | |
}, | |
set: function( tween ) { | |
// use step hook for back compat - use cssHook if its there - use .style if its | |
// available and use plain properties where available | |
if ( jQuery.fx.step[ tween.prop ] ) { | |
jQuery.fx.step[ tween.prop ]( tween ); | |
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { | |
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); | |
} else { | |
tween.elem[ tween.prop ] = tween.now; | |
} | |
} | |
} | |
}; | |
// Support: IE9 | |
// Panic based approach to setting things on disconnected nodes | |
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { | |
set: function( tween ) { | |
if ( tween.elem.nodeType && tween.elem.parentNode ) { | |
tween.elem[ tween.prop ] = tween.now; | |
} | |
} | |
}; | |
jQuery.easing = { | |
linear: function( p ) { | |
return p; | |
}, | |
swing: function( p ) { | |
return 0.5 - Math.cos( p * Math.PI ) / 2; | |
} | |
}; | |
jQuery.fx = Tween.prototype.init; | |
// Back Compat <1.8 extension point | |
jQuery.fx.step = {}; | |
var | |
fxNow, timerId, | |
rfxtypes = /^(?:toggle|show|hide)$/, | |
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), | |
rrun = /queueHooks$/, | |
animationPrefilters = [ defaultPrefilter ], | |
tweeners = { | |
"*": [ function( prop, value ) { | |
var tween = this.createTween( prop, value ), | |
target = tween.cur(), | |
parts = rfxnum.exec( value ), | |
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), | |
// Starting value computation is required for potential unit mismatches | |
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && | |
rfxnum.exec( jQuery.css( tween.elem, prop ) ), | |
scale = 1, | |
maxIterations = 20; | |
if ( start && start[ 3 ] !== unit ) { | |
// Trust units reported by jQuery.css | |
unit = unit || start[ 3 ]; | |
// Make sure we update the tween properties later on | |
parts = parts || []; | |
// Iteratively approximate from a nonzero starting point | |
start = +target || 1; | |
do { | |
// If previous iteration zeroed out, double until we get *something* | |
// Use a string for doubling factor so we don't accidentally see scale as unchanged below | |
scale = scale || ".5"; | |
// Adjust and apply | |
start = start / scale; | |
jQuery.style( tween.elem, prop, start + unit ); | |
// Update scale, tolerating zero or NaN from tween.cur() | |
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough | |
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); | |
} | |
// Update tween properties | |
if ( parts ) { | |
start = tween.start = +start || +target || 0; | |
tween.unit = unit; | |
// If a +=/-= token was provided, we're doing a relative animation | |
tween.end = parts[ 1 ] ? | |
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : | |
+parts[ 2 ]; | |
} | |
return tween; | |
} ] | |
}; | |
// Animations created synchronously will run synchronously | |
function createFxNow() { | |
setTimeout(function() { | |
fxNow = undefined; | |
}); | |
return ( fxNow = jQuery.now() ); | |
} | |
// Generate parameters to create a standard animation | |
function genFx( type, includeWidth ) { | |
var which, | |
i = 0, | |
attrs = { height: type }; | |
// if we include width, step value is 1 to do all cssExpand values, | |
// if we don't include width, step value is 2 to skip over Left and Right | |
includeWidth = includeWidth ? 1 : 0; | |
for ( ; i < 4 ; i += 2 - includeWidth ) { | |
which = cssExpand[ i ]; | |
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; | |
} | |
if ( includeWidth ) { | |
attrs.opacity = attrs.width = type; | |
} | |
return attrs; | |
} | |
function createTween( value, prop, animation ) { | |
var tween, | |
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), | |
index = 0, | |
length = collection.length; | |
for ( ; index < length; index++ ) { | |
if ( (tween = collection[ index ].call( animation, prop, value )) ) { | |
// we're done with this property | |
return tween; | |
} | |
} | |
} | |
function defaultPrefilter( elem, props, opts ) { | |
/* jshint validthis: true */ | |
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, | |
anim = this, | |
orig = {}, | |
style = elem.style, | |
hidden = elem.nodeType && isHidden( elem ), | |
dataShow = data_priv.get( elem, "fxshow" ); | |
// handle queue: false promises | |
if ( !opts.queue ) { | |
hooks = jQuery._queueHooks( elem, "fx" ); | |
if ( hooks.unqueued == null ) { | |
hooks.unqueued = 0; | |
oldfire = hooks.empty.fire; | |
hooks.empty.fire = function() { | |
if ( !hooks.unqueued ) { | |
oldfire(); | |
} | |
}; | |
} | |
hooks.unqueued++; | |
anim.always(function() { | |
// doing this makes sure that the complete handler will be called | |
// before this completes | |
anim.always(function() { | |
hooks.unqueued--; | |
if ( !jQuery.queue( elem, "fx" ).length ) { | |
hooks.empty.fire(); | |
} | |
}); | |
}); | |
} | |
// height/width overflow pass | |
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { | |
// Make sure that nothing sneaks out | |
// Record all 3 overflow attributes because IE9-10 do not | |
// change the overflow attribute when overflowX and | |
// overflowY are set to the same value | |
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; | |
// Set display property to inline-block for height/width | |
// animations on inline elements that are having width/height animated | |
display = jQuery.css( elem, "display" ); | |
// Test default display if display is currently "none" | |
checkDisplay = display === "none" ? | |
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; | |
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { | |
style.display = "inline-block"; | |
} | |
} | |
if ( opts.overflow ) { | |
style.overflow = "hidden"; | |
anim.always(function() { | |
style.overflow = opts.overflow[ 0 ]; | |
style.overflowX = opts.overflow[ 1 ]; | |
style.overflowY = opts.overflow[ 2 ]; | |
}); | |
} | |
// show/hide pass | |
for ( prop in props ) { | |
value = props[ prop ]; | |
if ( rfxtypes.exec( value ) ) { | |
delete props[ prop ]; | |
toggle = toggle || value === "toggle"; | |
if ( value === ( hidden ? "hide" : "show" ) ) { | |
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden | |
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { | |
hidden = true; | |
} else { | |
continue; | |
} | |
} | |
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); | |
// Any non-fx value stops us from restoring the original display value | |
} else { | |
display = undefined; | |
} | |
} | |
if ( !jQuery.isEmptyObject( orig ) ) { | |
if ( dataShow ) { | |
if ( "hidden" in dataShow ) { | |
hidden = dataShow.hidden; | |
} | |
} else { | |
dataShow = data_priv.access( elem, "fxshow", {} ); | |
} | |
// store state if its toggle - enables .stop().toggle() to "reverse" | |
if ( toggle ) { | |
dataShow.hidden = !hidden; | |
} | |
if ( hidden ) { | |
jQuery( elem ).show(); | |
} else { | |
anim.done(function() { | |
jQuery( elem ).hide(); | |
}); | |
} | |
anim.done(function() { | |
var prop; | |
data_priv.remove( elem, "fxshow" ); | |
for ( prop in orig ) { | |
jQuery.style( elem, prop, orig[ prop ] ); | |
} | |
}); | |
for ( prop in orig ) { | |
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); | |
if ( !( prop in dataShow ) ) { | |
dataShow[ prop ] = tween.start; | |
if ( hidden ) { | |
tween.end = tween.start; | |
tween.start = prop === "width" || prop === "height" ? 1 : 0; | |
} | |
} | |
} | |
// If this is a noop like .hide().hide(), restore an overwritten display value | |
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { | |
style.display = display; | |
} | |
} | |
function propFilter( props, specialEasing ) { | |
var index, name, easing, value, hooks; | |
// camelCase, specialEasing and expand cssHook pass | |
for ( index in props ) { | |
name = jQuery.camelCase( index ); | |
easing = specialEasing[ name ]; | |
value = props[ index ]; | |
if ( jQuery.isArray( value ) ) { | |
easing = value[ 1 ]; | |
value = props[ index ] = value[ 0 ]; | |
} | |
if ( index !== name ) { | |
props[ name ] = value; | |
delete props[ index ]; | |
} | |
hooks = jQuery.cssHooks[ name ]; | |
if ( hooks && "expand" in hooks ) { | |
value = hooks.expand( value ); | |
delete props[ name ]; | |
// not quite $.extend, this wont overwrite keys already present. | |
// also - reusing 'index' from above because we have the correct "name" | |
for ( index in value ) { | |
if ( !( index in props ) ) { | |
props[ index ] = value[ index ]; | |
specialEasing[ index ] = easing; | |
} | |
} | |
} else { | |
specialEasing[ name ] = easing; | |
} | |
} | |
} | |
function Animation( elem, properties, options ) { | |
var result, | |
stopped, | |
index = 0, | |
length = animationPrefilters.length, | |
deferred = jQuery.Deferred().always( function() { | |
// don't match elem in the :animated selector | |
delete tick.elem; | |
}), | |
tick = function() { | |
if ( stopped ) { | |
return false; | |
} | |
var currentTime = fxNow || createFxNow(), | |
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), | |
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) | |
temp = remaining / animation.duration || 0, | |
percent = 1 - temp, | |
index = 0, | |
length = animation.tweens.length; | |
for ( ; index < length ; index++ ) { | |
animation.tweens[ index ].run( percent ); | |
} | |
deferred.notifyWith( elem, [ animation, percent, remaining ]); | |
if ( percent < 1 && length ) { | |
return remaining; | |
} else { | |
deferred.resolveWith( elem, [ animation ] ); | |
return false; | |
} | |
}, | |
animation = deferred.promise({ | |
elem: elem, | |
props: jQuery.extend( {}, properties ), | |
opts: jQuery.extend( true, { specialEasing: {} }, options ), | |
originalProperties: properties, | |
originalOptions: options, | |
startTime: fxNow || createFxNow(), | |
duration: options.duration, | |
tweens: [], | |
createTween: function( prop, end ) { | |
var tween = jQuery.Tween( elem, animation.opts, prop, end, | |
animation.opts.specialEasing[ prop ] || animation.opts.easing ); | |
animation.tweens.push( tween ); | |
return tween; | |
}, | |
stop: function( gotoEnd ) { | |
var index = 0, | |
// if we are going to the end, we want to run all the tweens | |
// otherwise we skip this part | |
length = gotoEnd ? animation.tweens.length : 0; | |
if ( stopped ) { | |
return this; | |
} | |
stopped = true; | |
for ( ; index < length ; index++ ) { | |
animation.tweens[ index ].run( 1 ); | |
} | |
// resolve when we played the last frame | |
// otherwise, reject | |
if ( gotoEnd ) { | |
deferred.resolveWith( elem, [ animation, gotoEnd ] ); | |
} else { | |
deferred.rejectWith( elem, [ animation, gotoEnd ] ); | |
} | |
return this; | |
} | |
}), | |
props = animation.props; | |
propFilter( props, animation.opts.specialEasing ); | |
for ( ; index < length ; index++ ) { | |
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); | |
if ( result ) { | |
return result; | |
} | |
} | |
jQuery.map( props, createTween, animation ); | |
if ( jQuery.isFunction( animation.opts.start ) ) { | |
animation.opts.start.call( elem, animation ); | |
} | |
jQuery.fx.timer( | |
jQuery.extend( tick, { | |
elem: elem, | |
anim: animation, | |
queue: animation.opts.queue | |
}) | |
); | |
// attach callbacks from options | |
return animation.progress( animation.opts.progress ) | |
.done( animation.opts.done, animation.opts.complete ) | |
.fail( animation.opts.fail ) | |
.always( animation.opts.always ); | |
} | |
jQuery.Animation = jQuery.extend( Animation, { | |
tweener: function( props, callback ) { | |
if ( jQuery.isFunction( props ) ) { | |
callback = props; | |
props = [ "*" ]; | |
} else { | |
props = props.split(" "); | |
} | |
var prop, | |
index = 0, | |
length = props.length; | |
for ( ; index < length ; index++ ) { | |
prop = props[ index ]; | |
tweeners[ prop ] = tweeners[ prop ] || []; | |
tweeners[ prop ].unshift( callback ); | |
} | |
}, | |
prefilter: function( callback, prepend ) { | |
if ( prepend ) { | |
animationPrefilters.unshift( callback ); | |
} else { | |
animationPrefilters.push( callback ); | |
} | |
} | |
}); | |
jQuery.speed = function( speed, easing, fn ) { | |
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { | |
complete: fn || !fn && easing || | |
jQuery.isFunction( speed ) && speed, | |
duration: speed, | |
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing | |
}; | |
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : | |
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; | |
// normalize opt.queue - true/undefined/null -> "fx" | |
if ( opt.queue == null || opt.queue === true ) { | |
opt.queue = "fx"; | |
} | |
// Queueing | |
opt.old = opt.complete; | |
opt.complete = function() { | |
if ( jQuery.isFunction( opt.old ) ) { | |
opt.old.call( this ); | |
} | |
if ( opt.queue ) { | |
jQuery.dequeue( this, opt.queue ); | |
} | |
}; | |
return opt; | |
}; | |
jQuery.fn.extend({ | |
fadeTo: function( speed, to, easing, callback ) { | |
// show any hidden elements after setting opacity to 0 | |
return this.filter( isHidden ).css( "opacity", 0 ).show() | |
// animate to the value specified | |
.end().animate({ opacity: to }, speed, easing, callback ); | |
}, | |
animate: function( prop, speed, easing, callback ) { | |
var empty = jQuery.isEmptyObject( prop ), | |
optall = jQuery.speed( speed, easing, callback ), | |
doAnimation = function() { | |
// Operate on a copy of prop so per-property easing won't be lost | |
var anim = Animation( this, jQuery.extend( {}, prop ), optall ); | |
// Empty animations, or finishing resolves immediately | |
if ( empty || data_priv.get( this, "finish" ) ) { | |
anim.stop( true ); | |
} | |
}; | |
doAnimation.finish = doAnimation; | |
return empty || optall.queue === false ? | |
this.each( doAnimation ) : | |
this.queue( optall.queue, doAnimation ); | |
}, | |
stop: function( type, clearQueue, gotoEnd ) { | |
var stopQueue = function( hooks ) { | |
var stop = hooks.stop; | |
delete hooks.stop; | |
stop( gotoEnd ); | |
}; | |
if ( typeof type !== "string" ) { | |
gotoEnd = clearQueue; | |
clearQueue = type; | |
type = undefined; | |
} | |
if ( clearQueue && type !== false ) { | |
this.queue( type || "fx", [] ); | |
} | |
return this.each(function() { | |
var dequeue = true, | |
index = type != null && type + "queueHooks", | |
timers = jQuery.timers, | |
data = data_priv.get( this ); | |
if ( index ) { | |
if ( data[ index ] && data[ index ].stop ) { | |
stopQueue( data[ index ] ); | |
} | |
} else { | |
for ( index in data ) { | |
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { | |
stopQueue( data[ index ] ); | |
} | |
} | |
} | |
for ( index = timers.length; index--; ) { | |
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { | |
timers[ index ].anim.stop( gotoEnd ); | |
dequeue = false; | |
timers.splice( index, 1 ); | |
} | |
} | |
// start the next in the queue if the last step wasn't forced | |
// timers currently will call their complete callbacks, which will dequeue | |
// but only if they were gotoEnd | |
if ( dequeue || !gotoEnd ) { | |
jQuery.dequeue( this, type ); | |
} | |
}); | |
}, | |
finish: function( type ) { | |
if ( type !== false ) { | |
type = type || "fx"; | |
} | |
return this.each(function() { | |
var index, | |
data = data_priv.get( this ), | |
queue = data[ type + "queue" ], | |
hooks = data[ type + "queueHooks" ], | |
timers = jQuery.timers, | |
length = queue ? queue.length : 0; | |
// enable finishing flag on private data | |
data.finish = true; | |
// empty the queue first | |
jQuery.queue( this, type, [] ); | |
if ( hooks && hooks.stop ) { | |
hooks.stop.call( this, true ); | |
} | |
// look for any active animations, and finish them | |
for ( index = timers.length; index--; ) { | |
if ( timers[ index ].elem === this && timers[ index ].queue === type ) { | |
timers[ index ].anim.stop( true ); | |
timers.splice( index, 1 ); | |
} | |
} | |
// look for any animations in the old queue and finish them | |
for ( index = 0; index < length; index++ ) { | |
if ( queue[ index ] && queue[ index ].finish ) { | |
queue[ index ].finish.call( this ); | |
} | |
} | |
// turn off finishing flag | |
delete data.finish; | |
}); | |
} | |
}); | |
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { | |
var cssFn = jQuery.fn[ name ]; | |
jQuery.fn[ name ] = function( speed, easing, callback ) { | |
return speed == null || typeof speed === "boolean" ? | |
cssFn.apply( this, arguments ) : | |
this.animate( genFx( name, true ), speed, easing, callback ); | |
}; | |
}); | |
// Generate shortcuts for custom animations | |
jQuery.each({ | |
slideDown: genFx("show"), | |
slideUp: genFx("hide"), | |
slideToggle: genFx("toggle"), | |
fadeIn: { opacity: "show" }, | |
fadeOut: { opacity: "hide" }, | |
fadeToggle: { opacity: "toggle" } | |
}, function( name, props ) { | |
jQuery.fn[ name ] = function( speed, easing, callback ) { | |
return this.animate( props, speed, easing, callback ); | |
}; | |
}); | |
jQuery.timers = []; | |
jQuery.fx.tick = function() { | |
var timer, | |
i = 0, | |
timers = jQuery.timers; | |
fxNow = jQuery.now(); | |
for ( ; i < timers.length; i++ ) { | |
timer = timers[ i ]; | |
// Checks the timer has not already been removed | |
if ( !timer() && timers[ i ] === timer ) { | |
timers.splice( i--, 1 ); | |
} | |
} | |
if ( !timers.length ) { | |
jQuery.fx.stop(); | |
} | |
fxNow = undefined; | |
}; | |
jQuery.fx.timer = function( timer ) { | |
jQuery.timers.push( timer ); | |
if ( timer() ) { | |
jQuery.fx.start(); | |
} else { | |
jQuery.timers.pop(); | |
} | |
}; | |
jQuery.fx.interval = 13; | |
jQuery.fx.start = function() { | |
if ( !timerId ) { | |
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); | |
} | |
}; | |
jQuery.fx.stop = function() { | |
clearInterval( timerId ); | |
timerId = null; | |
}; | |
jQuery.fx.speeds = { | |
slow: 600, | |
fast: 200, | |
// Default speed | |
_default: 400 | |
}; | |
// Based off of the plugin by Clint Helfers, with permission. | |
// http://blindsignals.com/index.php/2009/07/jquery-delay/ | |
jQuery.fn.delay = function( time, type ) { | |
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; | |
type = type || "fx"; | |
return this.queue( type, function( next, hooks ) { | |
var timeout = setTimeout( next, time ); | |
hooks.stop = function() { | |
clearTimeout( timeout ); | |
}; | |
}); | |
}; | |
(function() { | |
var input = document.createElement( "input" ), | |
select = document.createElement( "select" ), | |
opt = select.appendChild( document.createElement( "option" ) ); | |
input.type = "checkbox"; | |
// Support: iOS 5.1, Android 4.x, Android 2.3 | |
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) | |
support.checkOn = input.value !== ""; | |
// Must access the parent to make an option select properly | |
// Support: IE9, IE10 | |
support.optSelected = opt.selected; | |
// Make sure that the options inside disabled selects aren't marked as disabled | |
// (WebKit marks them as disabled) | |
select.disabled = true; | |
support.optDisabled = !opt.disabled; | |
// Check if an input maintains its value after becoming a radio | |
// Support: IE9, IE10 | |
input = document.createElement( "input" ); | |
input.value = "t"; | |
input.type = "radio"; | |
support.radioValue = input.value === "t"; | |
})(); | |
var nodeHook, boolHook, | |
attrHandle = jQuery.expr.attrHandle; | |
jQuery.fn.extend({ | |
attr: function( name, value ) { | |
return access( this, jQuery.attr, name, value, arguments.length > 1 ); | |
}, | |
removeAttr: function( name ) { | |
return this.each(function() { | |
jQuery.removeAttr( this, name ); | |
}); | |
} | |
}); | |
jQuery.extend({ | |
attr: function( elem, name, value ) { | |
var hooks, ret, | |
nType = elem.nodeType; | |
// don't get/set attributes on text, comment and attribute nodes | |
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { | |
return; | |
} | |
// Fallback to prop when attributes are not supported | |
if ( typeof elem.getAttribute === strundefined ) { | |
return jQuery.prop( elem, name, value ); | |
} | |
// All attributes are lowercase | |
// Grab necessary hook if one is defined | |
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { | |
name = name.toLowerCase(); | |
hooks = jQuery.attrHooks[ name ] || | |
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); | |
} | |
if ( value !== undefined ) { | |
if ( value === null ) { | |
jQuery.removeAttr( elem, name ); | |
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { | |
return ret; | |
} else { | |
elem.setAttribute( name, value + "" ); | |
return value; | |
} | |
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { | |
return ret; | |
} else { | |
ret = jQuery.find.attr( elem, name ); | |
// Non-existent attributes return null, we normalize to undefined | |
return ret == null ? | |
undefined : | |
ret; | |
} | |
}, | |
removeAttr: function( elem, value ) { | |
var name, propName, | |
i = 0, | |
attrNames = value && value.match( rnotwhite ); | |
if ( attrNames && elem.nodeType === 1 ) { | |
while ( (name = attrNames[i++]) ) { | |
propName = jQuery.propFix[ name ] || name; | |
// Boolean attributes get special treatment (#10870) | |
if ( jQuery.expr.match.bool.test( name ) ) { | |
// Set corresponding property to false | |
elem[ propName ] = false; | |
} | |
elem.removeAttribute( name ); | |
} | |
} | |
}, | |
attrHooks: { | |
type: { | |
set: function( elem, value ) { | |
if ( !support.radioValue && value === "radio" && | |
jQuery.nodeName( elem, "input" ) ) { | |
// Setting the type on a radio button after the value resets the value in IE6-9 | |
// Reset value to default in case type is set after value during creation | |
var val = elem.value; | |
elem.setAttribute( "type", value ); | |
if ( val ) { | |
elem.value = val; | |
} | |
return value; | |
} | |
} | |
} | |
} | |
}); | |
// Hooks for boolean attributes | |
boolHook = { | |
set: function( elem, value, name ) { | |
if ( value === false ) { | |
// Remove boolean attributes when set to false | |
jQuery.removeAttr( elem, name ); | |
} else { | |
elem.setAttribute( name, name ); | |
} | |
return name; | |
} | |
}; | |
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { | |
var getter = attrHandle[ name ] || jQuery.find.attr; | |
attrHandle[ name ] = function( elem, name, isXML ) { | |
var ret, handle; | |
if ( !isXML ) { | |
// Avoid an infinite loop by temporarily removing this function from the getter | |
handle = attrHandle[ name ]; | |
attrHandle[ name ] = ret; | |
ret = getter( elem, name, isXML ) != null ? | |
name.toLowerCase() : | |
null; | |
attrHandle[ name ] = handle; | |
} | |
return ret; | |
}; | |
}); | |
var rfocusable = /^(?:input|select|textarea|button)$/i; | |
jQuery.fn.extend({ | |
prop: function( name, value ) { | |
return access( this, jQuery.prop, name, value, arguments.length > 1 ); | |
}, | |
removeProp: function( name ) { | |
return this.each(function() { | |
delete this[ jQuery.propFix[ name ] || name ]; | |
}); | |
} | |
}); | |
jQuery.extend({ | |
propFix: { | |
"for": "htmlFor", | |
"class": "className" | |
}, | |
prop: function( elem, name, value ) { | |
var ret, hooks, notxml, | |
nType = elem.nodeType; | |
// don't get/set properties on text, comment and attribute nodes | |
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { | |
return; | |
} | |
notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); | |
if ( notxml ) { | |
// Fix name and attach hooks | |
name = jQuery.propFix[ name ] || name; | |
hooks = jQuery.propHooks[ name ]; | |
} | |
if ( value !== undefined ) { | |
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? | |
ret : | |
( elem[ name ] = value ); | |
} else { | |
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? | |
ret : | |
elem[ name ]; | |
} | |
}, | |
propHooks: { | |
tabIndex: { | |
get: function( elem ) { | |
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? | |
elem.tabIndex : | |
-1; | |
} | |
} | |
} | |
}); | |
// Support: IE9+ | |
// Selectedness for an option in an optgroup can be inaccurate | |
if ( !support.optSelected ) { | |
jQuery.propHooks.selected = { | |
get: function( elem ) { | |
var parent = elem.parentNode; | |
if ( parent && parent.parentNode ) { | |
parent.parentNode.selectedIndex; | |
} | |
return null; | |
} | |
}; | |
} | |
jQuery.each([ | |
"tabIndex", | |
"readOnly", | |
"maxLength", | |
"cellSpacing", | |
"cellPadding", | |
"rowSpan", | |
"colSpan", | |
"useMap", | |
"frameBorder", | |
"contentEditable" | |
], function() { | |
jQuery.propFix[ this.toLowerCase() ] = this; | |
}); | |
var rclass = /[\t\r\n\f]/g; | |
jQuery.fn.extend({ | |
addClass: function( value ) { | |
var classes, elem, cur, clazz, j, finalValue, | |
proceed = typeof value === "string" && value, | |
i = 0, | |
len = this.length; | |
if ( jQuery.isFunction( value ) ) { | |
return this.each(function( j ) { | |
jQuery( this ).addClass( value.call( this, j, this.className ) ); | |
}); | |
} | |
if ( proceed ) { | |
// The disjunction here is for better compressibility (see removeClass) | |
classes = ( value || "" ).match( rnotwhite ) || []; | |
for ( ; i < len; i++ ) { | |
elem = this[ i ]; | |
cur = elem.nodeType === 1 && ( elem.className ? | |
( " " + elem.className + " " ).replace( rclass, " " ) : | |
" " | |
); | |
if ( cur ) { | |
j = 0; | |
while ( (clazz = classes[j++]) ) { | |
if ( cur.indexOf( " " + clazz + " " ) < 0 ) { | |
cur += clazz + " "; | |
} | |
} | |
// only assign if different to avoid unneeded rendering. | |
finalValue = jQuery.trim( cur ); | |
if ( elem.className !== finalValue ) { | |
elem.className = finalValue; | |
} | |
} | |
} | |
} | |
return this; | |
}, | |
removeClass: function( value ) { | |
var classes, elem, cur, clazz, j, finalValue, | |
proceed = arguments.length === 0 || typeof value === "string" && value, | |
i = 0, | |
len = this.length; | |
if ( jQuery.isFunction( value ) ) { | |
return this.each(function( j ) { | |
jQuery( this ).removeClass( value.call( this, j, this.className ) ); | |
}); | |
} | |
if ( proceed ) { | |
classes = ( value || "" ).match( rnotwhite ) || []; | |
for ( ; i < len; i++ ) { | |
elem = this[ i ]; | |
// This expression is here for better compressibility (see addClass) | |
cur = elem.nodeType === 1 && ( elem.className ? | |
( " " + elem.className + " " ).replace( rclass, " " ) : | |
"" | |
); | |
if ( cur ) { | |
j = 0; | |
while ( (clazz = classes[j++]) ) { | |
// Remove *all* instances | |
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { | |
cur = cur.replace( " " + clazz + " ", " " ); | |
} | |
} | |
// only assign if different to avoid unneeded rendering. | |
finalValue = value ? jQuery.trim( cur ) : ""; | |
if ( elem.className !== finalValue ) { | |
elem.className = finalValue; | |
} | |
} | |
} | |
} | |
return this; | |
}, | |
toggleClass: function( value, stateVal ) { | |
var type = typeof value; | |
if ( typeof stateVal === "boolean" && type === "string" ) { | |
return stateVal ? this.addClass( value ) : this.removeClass( value ); | |
} | |
if ( jQuery.isFunction( value ) ) { | |
return this.each(function( i ) { | |
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); | |
}); | |
} | |
return this.each(function() { | |
if ( type === "string" ) { | |
// toggle individual class names | |
var className, | |
i = 0, | |
self = jQuery( this ), | |
classNames = value.match( rnotwhite ) || []; | |
while ( (className = classNames[ i++ ]) ) { | |
// check each className given, space separated list | |
if ( self.hasClass( className ) ) { | |
self.removeClass( className ); | |
} else { | |
self.addClass( className ); | |
} | |
} | |
// Toggle whole class name | |
} else if ( type === strundefined || type === "boolean" ) { | |
if ( this.className ) { | |
// store className if set | |
data_priv.set( this, "__className__", this.className ); | |
} | |
// If the element has a class name or if we're passed "false", | |
// then remove the whole classname (if there was one, the above saved it). | |
// Otherwise bring back whatever was previously saved (if anything), | |
// falling back to the empty string if nothing was stored. | |
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; | |
} | |
}); | |
}, | |
hasClass: function( selector ) { | |
var className = " " + selector + " ", | |
i = 0, | |
l = this.length; | |
for ( ; i < l; i++ ) { | |
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { | |
return true; | |
} | |
} | |
return false; | |
} | |
}); | |
var rreturn = /\r/g; | |
jQuery.fn.extend({ | |
val: function( value ) { | |
var hooks, ret, isFunction, | |
elem = this[0]; | |
if ( !arguments.length ) { | |
if ( elem ) { | |
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; | |
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { | |
return ret; | |
} | |
ret = elem.value; | |
return typeof ret === "string" ? | |
// handle most common string cases | |
ret.replace(rreturn, "") : | |
// handle cases where value is null/undef or number | |
ret == null ? "" : ret; | |
} | |
return; | |
} | |
isFunction = jQuery.isFunction( value ); | |
return this.each(function( i ) { | |
var val; | |
if ( this.nodeType !== 1 ) { | |
return; | |
} | |
if ( isFunction ) { | |
val = value.call( this, i, jQuery( this ).val() ); | |
} else { | |
val = value; | |
} | |
// Treat null/undefined as ""; convert numbers to string | |
if ( val == null ) { | |
val = ""; | |
} else if ( typeof val === "number" ) { | |
val += ""; | |
} else if ( jQuery.isArray( val ) ) { | |
val = jQuery.map( val, function( value ) { | |
return value == null ? "" : value + ""; | |
}); | |
} | |
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; | |
// If set returns undefined, fall back to normal setting | |
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { | |
this.value = val; | |
} | |
}); | |
} | |
}); | |
jQuery.extend({ | |
valHooks: { | |
option: { | |
get: function( elem ) { | |
var val = jQuery.find.attr( elem, "value" ); | |
return val != null ? | |
val : | |
// Support: IE10-11+ | |
// option.text throws exceptions (#14686, #14858) | |
jQuery.trim( jQuery.text( elem ) ); | |
} | |
}, | |
select: { | |
get: function( elem ) { | |
var value, option, | |
options = elem.options, | |
index = elem.selectedIndex, | |
one = elem.type === "select-one" || index < 0, | |
values = one ? null : [], | |
max = one ? index + 1 : options.length, | |
i = index < 0 ? | |
max : | |
one ? index : 0; | |
// Loop through all the selected options | |
for ( ; i < max; i++ ) { | |
option = options[ i ]; | |
// IE6-9 doesn't update selected after form reset (#2551) | |
if ( ( option.selected || i === index ) && | |
// Don't return options that are disabled or in a disabled optgroup | |
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && | |
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { | |
// Get the specific value for the option | |
value = jQuery( option ).val(); | |
// We don't need an array for one selects | |
if ( one ) { | |
return value; | |
} | |
// Multi-Selects return an array | |
values.push( value ); | |
} | |
} | |
return values; | |
}, | |
set: function( elem, value ) { | |
var optionSet, option, | |
options = elem.options, | |
values = jQuery.makeArray( value ), | |
i = options.length; | |
while ( i-- ) { | |
option = options[ i ]; | |
if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { | |
optionSet = true; | |
} | |
} | |
// force browsers to behave consistently when non-matching value is set | |
if ( !optionSet ) { | |
elem.selectedIndex = -1; | |
} | |
return values; | |
} | |
} | |
} | |
}); | |
// Radios and checkboxes getter/setter | |
jQuery.each([ "radio", "checkbox" ], function() { | |
jQuery.valHooks[ this ] = { | |
set: function( elem, value ) { | |
if ( jQuery.isArray( value ) ) { | |
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); | |
} | |
} | |
}; | |
if ( !support.checkOn ) { | |
jQuery.valHooks[ this ].get = function( elem ) { | |
// Support: Webkit | |
// "" is returned instead of "on" if a value isn't specified | |
return elem.getAttribute("value") === null ? "on" : elem.value; | |
}; | |
} | |
}); | |
// Return jQuery for attributes-only inclusion | |
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + | |
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + | |
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { | |
// Handle event binding | |
jQuery.fn[ name ] = function( data, fn ) { | |
return arguments.length > 0 ? | |
this.on( name, null, data, fn ) : | |
this.trigger( name ); | |
}; | |
}); | |
jQuery.fn.extend({ | |
hover: function( fnOver, fnOut ) { | |
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); | |
}, | |
bind: function( types, data, fn ) { | |
return this.on( types, null, data, fn ); | |
}, | |
unbind: function( types, fn ) { | |
return this.off( types, null, fn ); | |
}, | |
delegate: function( selector, types, data, fn ) { | |
return this.on( types, selector, data, fn ); | |
}, | |
undelegate: function( selector, types, fn ) { | |
// ( namespace ) or ( selector, types [, fn] ) | |
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); | |
} | |
}); | |
var nonce = jQuery.now(); | |
var rquery = (/\?/); | |
// Support: Android 2.3 | |
// Workaround failure to string-cast null input | |
jQuery.parseJSON = function( data ) { | |
return JSON.parse( data + "" ); | |
}; | |
// Cross-browser xml parsing | |
jQuery.parseXML = function( data ) { | |
var xml, tmp; | |
if ( !data || typeof data !== "string" ) { | |
return null; | |
} | |
// Support: IE9 | |
try { | |
tmp = new DOMParser(); | |
xml = tmp.parseFromString( data, "text/xml" ); | |
} catch ( e ) { | |
xml = undefined; | |
} | |
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { | |
jQuery.error( "Invalid XML: " + data ); | |
} | |
return xml; | |
}; | |
var | |
// Document location | |
ajaxLocParts, | |
ajaxLocation, | |
rhash = /#.*$/, | |
rts = /([?&])_=[^&]*/, | |
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, | |
// #7653, #8125, #8152: local protocol detection | |
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, | |
rnoContent = /^(?:GET|HEAD)$/, | |
rprotocol = /^\/\//, | |
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, | |
/* Prefilters | |
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) | |
* 2) These are called: | |
* - BEFORE asking for a transport | |
* - AFTER param serialization (s.data is a string if s.processData is true) | |
* 3) key is the dataType | |
* 4) the catchall symbol "*" can be used | |
* 5) execution will start with transport dataType and THEN continue down to "*" if needed | |
*/ | |
prefilters = {}, | |
/* Transports bindings | |
* 1) key is the dataType | |
* 2) the catchall symbol "*" can be used | |
* 3) selection will start with transport dataType and THEN go to "*" if needed | |
*/ | |
transports = {}, | |
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression | |
allTypes = "*/".concat("*"); | |
// #8138, IE may throw an exception when accessing | |
// a field from window.location if document.domain has been set | |
try { | |
ajaxLocation = location.href; | |
} catch( e ) { | |
// Use the href attribute of an A element | |
// since IE will modify it given document.location | |
ajaxLocation = document.createElement( "a" ); | |
ajaxLocation.href = ""; | |
ajaxLocation = ajaxLocation.href; | |
} | |
// Segment location into parts | |
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; | |
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport | |
function addToPrefiltersOrTransports( structure ) { | |
// dataTypeExpression is optional and defaults to "*" | |
return function( dataTypeExpression, func ) { | |
if ( typeof dataTypeExpression !== "string" ) { | |
func = dataTypeExpression; | |
dataTypeExpression = "*"; | |
} | |
var dataType, | |
i = 0, | |
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; | |
if ( jQuery.isFunction( func ) ) { | |
// For each dataType in the dataTypeExpression | |
while ( (dataType = dataTypes[i++]) ) { | |
// Prepend if requested | |
if ( dataType[0] === "+" ) { | |
dataType = dataType.slice( 1 ) || "*"; | |
(structure[ dataType ] = structure[ dataType ] || []).unshift( func ); | |
// Otherwise append | |
} else { | |
(structure[ dataType ] = structure[ dataType ] || []).push( func ); | |
} | |
} | |
} | |
}; | |
} | |
// Base inspection function for prefilters and transports | |
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { | |
var inspected = {}, | |
seekingTransport = ( structure === transports ); | |
function inspect( dataType ) { | |
var selected; | |
inspected[ dataType ] = true; | |
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { | |
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); | |
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { | |
options.dataTypes.unshift( dataTypeOrTransport ); | |
inspect( dataTypeOrTransport ); | |
return false; | |
} else if ( seekingTransport ) { | |
return !( selected = dataTypeOrTransport ); | |
} | |
}); | |
return selected; | |
} | |
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); | |
} | |
// A special extend for ajax options | |
// that takes "flat" options (not to be deep extended) | |
// Fixes #9887 | |
function ajaxExtend( target, src ) { | |
var key, deep, | |
flatOptions = jQuery.ajaxSettings.flatOptions || {}; | |
for ( key in src ) { | |
if ( src[ key ] !== undefined ) { | |
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; | |
} | |
} | |
if ( deep ) { | |
jQuery.extend( true, target, deep ); | |
} | |
return target; | |
} | |
/* Handles responses to an ajax request: | |
* - finds the right dataType (mediates between content-type and expected dataType) | |
* - returns the corresponding response | |
*/ | |
function ajaxHandleResponses( s, jqXHR, responses ) { | |
var ct, type, finalDataType, firstDataType, | |
contents = s.contents, | |
dataTypes = s.dataTypes; | |
// Remove auto dataType and get content-type in the process | |
while ( dataTypes[ 0 ] === "*" ) { | |
dataTypes.shift(); | |
if ( ct === undefined ) { | |
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); | |
} | |
} | |
// Check if we're dealing with a known content-type | |
if ( ct ) { | |
for ( type in contents ) { | |
if ( contents[ type ] && contents[ type ].test( ct ) ) { | |
dataTypes.unshift( type ); | |
break; | |
} | |
} | |
} | |
// Check to see if we have a response for the expected dataType | |
if ( dataTypes[ 0 ] in responses ) { | |
finalDataType = dataTypes[ 0 ]; | |
} else { | |
// Try convertible dataTypes | |
for ( type in responses ) { | |
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { | |
finalDataType = type; | |
break; | |
} | |
if ( !firstDataType ) { | |
firstDataType = type; | |
} | |
} | |
// Or just use first one | |
finalDataType = finalDataType || firstDataType; | |
} | |
// If we found a dataType | |
// We add the dataType to the list if needed | |
// and return the corresponding response | |
if ( finalDataType ) { | |
if ( finalDataType !== dataTypes[ 0 ] ) { | |
dataTypes.unshift( finalDataType ); | |
} | |
return responses[ finalDataType ]; | |
} | |
} | |
/* Chain conversions given the request and the original response | |
* Also sets the responseXXX fields on the jqXHR instance | |
*/ | |
function ajaxConvert( s, response, jqXHR, isSuccess ) { | |
var conv2, current, conv, tmp, prev, | |
converters = {}, | |
// Work with a copy of dataTypes in case we need to modify it for conversion | |
dataTypes = s.dataTypes.slice(); | |
// Create converters map with lowercased keys | |
if ( dataTypes[ 1 ] ) { | |
for ( conv in s.converters ) { | |
converters[ conv.toLowerCase() ] = s.converters[ conv ]; | |
} | |
} | |
current = dataTypes.shift(); | |
// Convert to each sequential dataType | |
while ( current ) { | |
if ( s.responseFields[ current ] ) { | |
jqXHR[ s.responseFields[ current ] ] = response; | |
} | |
// Apply the dataFilter if provided | |
if ( !prev && isSuccess && s.dataFilter ) { | |
response = s.dataFilter( response, s.dataType ); | |
} | |
prev = current; | |
current = dataTypes.shift(); | |
if ( current ) { | |
// There's only work to do if current dataType is non-auto | |
if ( current === "*" ) { | |
current = prev; | |
// Convert response if prev dataType is non-auto and differs from current | |
} else if ( prev !== "*" && prev !== current ) { | |
// Seek a direct converter | |
conv = converters[ prev + " " + current ] || converters[ "* " + current ]; | |
// If none found, seek a pair | |
if ( !conv ) { | |
for ( conv2 in converters ) { | |
// If conv2 outputs current | |
tmp = conv2.split( " " ); | |
if ( tmp[ 1 ] === current ) { | |
// If prev can be converted to accepted input | |
conv = converters[ prev + " " + tmp[ 0 ] ] || | |
converters[ "* " + tmp[ 0 ] ]; | |
if ( conv ) { | |
// Condense equivalence converters | |
if ( conv === true ) { | |
conv = converters[ conv2 ]; | |
// Otherwise, insert the intermediate dataType | |
} else if ( converters[ conv2 ] !== true ) { | |
current = tmp[ 0 ]; | |
dataTypes.unshift( tmp[ 1 ] ); | |
} | |
break; | |
} | |
} | |
} | |
} | |
// Apply converter (if not an equivalence) | |
if ( conv !== true ) { | |
// Unless errors are allowed to bubble, catch and return them | |
if ( conv && s[ "throws" ] ) { | |
response = conv( response ); | |
} else { | |
try { | |
response = conv( response ); | |
} catch ( e ) { | |
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; | |
} | |
} | |
} | |
} | |
} | |
} | |
return { state: "success", data: response }; | |
} | |
jQuery.extend({ | |
// Counter for holding the number of active queries | |
active: 0, | |
// Last-Modified header cache for next request | |
lastModified: {}, | |
etag: {}, | |
ajaxSettings: { | |
url: ajaxLocation, | |
type: "GET", | |
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), | |
global: true, | |
processData: true, | |
async: true, | |
contentType: "application/x-www-form-urlencoded; charset=UTF-8", | |
/* | |
timeout: 0, | |
data: null, | |
dataType: null, | |
username: null, | |
password: null, | |
cache: null, | |
throws: false, | |
traditional: false, | |
headers: {}, | |
*/ | |
accepts: { | |
"*": allTypes, | |
text: "text/plain", | |
html: "text/html", | |
xml: "application/xml, text/xml", | |
json: "application/json, text/javascript" | |
}, | |
contents: { | |
xml: /xml/, | |
html: /html/, | |
json: /json/ | |
}, | |
responseFields: { | |
xml: "responseXML", | |
text: "responseText", | |
json: "responseJSON" | |
}, | |
// Data converters | |
// Keys separate source (or catchall "*") and destination types with a single space | |
converters: { | |
// Convert anything to text | |
"* text": String, | |
// Text to html (true = no transformation) | |
"text html": true, | |
// Evaluate text as a json expression | |
"text json": jQuery.parseJSON, | |
// Parse text as xml | |
"text xml": jQuery.parseXML | |
}, | |
// For options that shouldn't be deep extended: | |
// you can add your own custom options here if | |
// and when you create one that shouldn't be | |
// deep extended (see ajaxExtend) | |
flatOptions: { | |
url: true, | |
context: true | |
} | |
}, | |
// Creates a full fledged settings object into target | |
// with both ajaxSettings and settings fields. | |
// If target is omitted, writes into ajaxSettings. | |
ajaxSetup: function( target, settings ) { | |
return settings ? | |
// Building a settings object | |
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : | |
// Extending ajaxSettings | |
ajaxExtend( jQuery.ajaxSettings, target ); | |
}, | |
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), | |
ajaxTransport: addToPrefiltersOrTransports( transports ), | |
// Main method | |
ajax: function( url, options ) { | |
// If url is an object, simulate pre-1.5 signature | |
if ( typeof url === "object" ) { | |
options = url; | |
url = undefined; | |
} | |
// Force options to be an object | |
options = options || {}; | |
var transport, | |
// URL without anti-cache param | |
cacheURL, | |
// Response headers | |
responseHeadersString, | |
responseHeaders, | |
// timeout handle | |
timeoutTimer, | |
// Cross-domain detection vars | |
parts, | |
// To know if global events are to be dispatched | |
fireGlobals, | |
// Loop variable | |
i, | |
// Create the final options object | |
s = jQuery.ajaxSetup( {}, options ), | |
// Callbacks context | |
callbackContext = s.context || s, | |
// Context for global events is callbackContext if it is a DOM node or jQuery collection | |
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? | |
jQuery( callbackContext ) : | |
jQuery.event, | |
// Deferreds | |
deferred = jQuery.Deferred(), | |
completeDeferred = jQuery.Callbacks("once memory"), | |
// Status-dependent callbacks | |
statusCode = s.statusCode || {}, | |
// Headers (they are sent all at once) | |
requestHeaders = {}, | |
requestHeadersNames = {}, | |
// The jqXHR state | |
state = 0, | |
// Default abort message | |
strAbort = "canceled", | |
// Fake xhr | |
jqXHR = { | |
readyState: 0, | |
// Builds headers hashtable if needed | |
getResponseHeader: function( key ) { | |
var match; | |
if ( state === 2 ) { | |
if ( !responseHeaders ) { | |
responseHeaders = {}; | |
while ( (match = rheaders.exec( responseHeadersString )) ) { | |
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; | |
} | |
} | |
match = responseHeaders[ key.toLowerCase() ]; | |
} | |
return match == null ? null : match; | |
}, | |
// Raw string | |
getAllResponseHeaders: function() { | |
return state === 2 ? responseHeadersString : null; | |
}, | |
// Caches the header | |
setRequestHeader: function( name, value ) { | |
var lname = name.toLowerCase(); | |
if ( !state ) { | |
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; | |
requestHeaders[ name ] = value; | |
} | |
return this; | |
}, | |
// Overrides response content-type header | |
overrideMimeType: function( type ) { | |
if ( !state ) { | |
s.mimeType = type; | |
} | |
return this; | |
}, | |
// Status-dependent callbacks | |
statusCode: function( map ) { | |
var code; | |
if ( map ) { | |
if ( state < 2 ) { | |
for ( code in map ) { | |
// Lazy-add the new callback in a way that preserves old ones | |
statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; | |
} | |
} else { | |
// Execute the appropriate callbacks | |
jqXHR.always( map[ jqXHR.status ] ); | |
} | |
} | |
return this; | |
}, | |
// Cancel the request | |
abort: function( statusText ) { | |
var finalText = statusText || strAbort; | |
if ( transport ) { | |
transport.abort( finalText ); | |
} | |
done( 0, finalText ); | |
return this; | |
} | |
}; | |
// Attach deferreds | |
deferred.promise( jqXHR ).complete = completeDeferred.add; | |
jqXHR.success = jqXHR.done; | |
jqXHR.error = jqXHR.fail; | |
// Remove hash character (#7531: and string promotion) | |
// Add protocol if not provided (prefilters might expect it) | |
// Handle falsy url in the settings object (#10093: consistency with old signature) | |
// We also use the url parameter if available | |
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) | |
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); | |
// Alias method option to type as per ticket #12004 | |
s.type = options.method || options.type || s.method || s.type; | |
// Extract dataTypes list | |
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; | |
// A cross-domain request is in order when we have a protocol:host:port mismatch | |
if ( s.crossDomain == null ) { | |
parts = rurl.exec( s.url.toLowerCase() ); | |
s.crossDomain = !!( parts && | |
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || | |
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== | |
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) | |
); | |
} | |
// Convert data if not already a string | |
if ( s.data && s.processData && typeof s.data !== "string" ) { | |
s.data = jQuery.param( s.data, s.traditional ); | |
} | |
// Apply prefilters | |
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); | |
// If request was aborted inside a prefilter, stop there | |
if ( state === 2 ) { | |
return jqXHR; | |
} | |
// We can fire global events as of now if asked to | |
fireGlobals = s.global; | |
// Watch for a new set of requests | |
if ( fireGlobals && jQuery.active++ === 0 ) { | |
jQuery.event.trigger("ajaxStart"); | |
} | |
// Uppercase the type | |
s.type = s.type.toUpperCase(); | |
// Determine if request has content | |
s.hasContent = !rnoContent.test( s.type ); | |
// Save the URL in case we're toying with the If-Modified-Since | |
// and/or If-None-Match header later on | |
cacheURL = s.url; | |
// More options handling for requests with no content | |
if ( !s.hasContent ) { | |
// If data is available, append data to url | |
if ( s.data ) { | |
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); | |
// #9682: remove data so that it's not used in an eventual retry | |
delete s.data; | |
} | |
// Add anti-cache in url if needed | |
if ( s.cache === false ) { | |
s.url = rts.test( cacheURL ) ? | |
// If there is already a '_' parameter, set its value | |
cacheURL.replace( rts, "$1_=" + nonce++ ) : | |
// Otherwise add one to the end | |
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; | |
} | |
} | |
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. | |
if ( s.ifModified ) { | |
if ( jQuery.lastModified[ cacheURL ] ) { | |
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); | |
} | |
if ( jQuery.etag[ cacheURL ] ) { | |
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); | |
} | |
} | |
// Set the correct header, if data is being sent | |
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { | |
jqXHR.setRequestHeader( "Content-Type", s.contentType ); | |
} | |
// Set the Accepts header for the server, depending on the dataType | |
jqXHR.setRequestHeader( | |
"Accept", | |
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? | |
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : | |
s.accepts[ "*" ] | |
); | |
// Check for headers option | |
for ( i in s.headers ) { | |
jqXHR.setRequestHeader( i, s.headers[ i ] ); | |
} | |
// Allow custom headers/mimetypes and early abort | |
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { | |
// Abort if not done already and return | |
return jqXHR.abort(); | |
} | |
// aborting is no longer a cancellation | |
strAbort = "abort"; | |
// Install callbacks on deferreds | |
for ( i in { success: 1, error: 1, complete: 1 } ) { | |
jqXHR[ i ]( s[ i ] ); | |
} | |
// Get transport | |
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); | |
// If no transport, we auto-abort | |
if ( !transport ) { | |
done( -1, "No Transport" ); | |
} else { | |
jqXHR.readyState = 1; | |
// Send global event | |
if ( fireGlobals ) { | |
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); | |
} | |
// Timeout | |
if ( s.async && s.timeout > 0 ) { | |
timeoutTimer = setTimeout(function() { | |
jqXHR.abort("timeout"); | |
}, s.timeout ); | |
} | |
try { | |
state = 1; | |
transport.send( requestHeaders, done ); | |
} catch ( e ) { | |
// Propagate exception as error if not done | |
if ( state < 2 ) { | |
done( -1, e ); | |
// Simply rethrow otherwise | |
} else { | |
throw e; | |
} | |
} | |
} | |
// Callback for when everything is done | |
function done( status, nativeStatusText, responses, headers ) { | |
var isSuccess, success, error, response, modified, | |
statusText = nativeStatusText; | |
// Called once | |
if ( state === 2 ) { | |
return; | |
} | |
// State is "done" now | |
state = 2; | |
// Clear timeout if it exists | |
if ( timeoutTimer ) { | |
clearTimeout( timeoutTimer ); | |
} | |
// Dereference transport for early garbage collection | |
// (no matter how long the jqXHR object will be used) | |
transport = undefined; | |
// Cache response headers | |
responseHeadersString = headers || ""; | |
// Set readyState | |
jqXHR.readyState = status > 0 ? 4 : 0; | |
// Determine if successful | |
isSuccess = status >= 200 && status < 300 || status === 304; | |
// Get response data | |
if ( responses ) { | |
response = ajaxHandleResponses( s, jqXHR, responses ); | |
} | |
// Convert no matter what (that way responseXXX fields are always set) | |
response = ajaxConvert( s, response, jqXHR, isSuccess ); | |
// If successful, handle type chaining | |
if ( isSuccess ) { | |
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. | |
if ( s.ifModified ) { | |
modified = jqXHR.getResponseHeader("Last-Modified"); | |
if ( modified ) { | |
jQuery.lastModified[ cacheURL ] = modified; | |
} | |
modified = jqXHR.getResponseHeader("etag"); | |
if ( modified ) { | |
jQuery.etag[ cacheURL ] = modified; | |
} | |
} | |
// if no content | |
if ( status === 204 || s.type === "HEAD" ) { | |
statusText = "nocontent"; | |
// if not modified | |
} else if ( status === 304 ) { | |
statusText = "notmodified"; | |
// If we have data, let's convert it | |
} else { | |
statusText = response.state; | |
success = response.data; | |
error = response.error; | |
isSuccess = !error; | |
} | |
} else { | |
// We extract error from statusText | |
// then normalize statusText and status for non-aborts | |
error = statusText; | |
if ( status || !statusText ) { | |
statusText = "error"; | |
if ( status < 0 ) { | |
status = 0; | |
} | |
} | |
} | |
// Set data for the fake xhr object | |
jqXHR.status = status; | |
jqXHR.statusText = ( nativeStatusText || statusText ) + ""; | |
// Success/Error | |
if ( isSuccess ) { | |
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); | |
} else { | |
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); | |
} | |
// Status-dependent callbacks | |
jqXHR.statusCode( statusCode ); | |
statusCode = undefined; | |
if ( fireGlobals ) { | |
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", | |
[ jqXHR, s, isSuccess ? success : error ] ); | |
} | |
// Complete | |
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); | |
if ( fireGlobals ) { | |
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); | |
// Handle the global AJAX counter | |
if ( !( --jQuery.active ) ) { | |
jQuery.event.trigger("ajaxStop"); | |
} | |
} | |
} | |
return jqXHR; | |
}, | |
getJSON: function( url, data, callback ) { | |
return jQuery.get( url, data, callback, "json" ); | |
}, | |
getScript: function( url, callback ) { | |
return jQuery.get( url, undefined, callback, "script" ); | |
} | |
}); | |
jQuery.each( [ "get", "post" ], function( i, method ) { | |
jQuery[ method ] = function( url, data, callback, type ) { | |
// shift arguments if data argument was omitted | |
if ( jQuery.isFunction( data ) ) { | |
type = type || callback; | |
callback = data; | |
data = undefined; | |
} | |
return jQuery.ajax({ | |
url: url, | |
type: method, | |
dataType: type, | |
data: data, | |
success: callback | |
}); | |
}; | |
}); | |
// Attach a bunch of functions for handling common AJAX events | |
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { | |
jQuery.fn[ type ] = function( fn ) { | |
return this.on( type, fn ); | |
}; | |
}); | |
jQuery._evalUrl = function( url ) { | |
return jQuery.ajax({ | |
url: url, | |
type: "GET", | |
dataType: "script", | |
async: false, | |
global: false, | |
"throws": true | |
}); | |
}; | |
jQuery.fn.extend({ | |
wrapAll: function( html ) { | |
var wrap; | |
if ( jQuery.isFunction( html ) ) { | |
return this.each(function( i ) { | |
jQuery( this ).wrapAll( html.call(this, i) ); | |
}); | |
} | |
if ( this[ 0 ] ) { | |
// The elements to wrap the target around | |
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); | |
if ( this[ 0 ].parentNode ) { | |
wrap.insertBefore( this[ 0 ] ); | |
} | |
wrap.map(function() { | |
var elem = this; | |
while ( elem.firstElementChild ) { | |
elem = elem.firstElementChild; | |
} | |
return elem; | |
}).append( this ); | |
} | |
return this; | |
}, | |
wrapInner: function( html ) { | |
if ( jQuery.isFunction( html ) ) { | |
return this.each(function( i ) { | |
jQuery( this ).wrapInner( html.call(this, i) ); | |
}); | |
} | |
return this.each(function() { | |
var self = jQuery( this ), | |
contents = self.contents(); | |
if ( contents.length ) { | |
contents.wrapAll( html ); | |
} else { | |
self.append( html ); | |
} | |
}); | |
}, | |
wrap: function( html ) { | |
var isFunction = jQuery.isFunction( html ); | |
return this.each(function( i ) { | |
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); | |
}); | |
}, | |
unwrap: function() { | |
return this.parent().each(function() { | |
if ( !jQuery.nodeName( this, "body" ) ) { | |
jQuery( this ).replaceWith( this.childNodes ); | |
} | |
}).end(); | |
} | |
}); | |
jQuery.expr.filters.hidden = function( elem ) { | |
// Support: Opera <= 12.12 | |
// Opera reports offsetWidths and offsetHeights less than zero on some elements | |
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; | |
}; | |
jQuery.expr.filters.visible = function( elem ) { | |
return !jQuery.expr.filters.hidden( elem ); | |
}; | |
var r20 = /%20/g, | |
rbracket = /\[\]$/, | |
rCRLF = /\r?\n/g, | |
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, | |
rsubmittable = /^(?:input|select|textarea|keygen)/i; | |
function buildParams( prefix, obj, traditional, add ) { | |
var name; | |
if ( jQuery.isArray( obj ) ) { | |
// Serialize array item. | |
jQuery.each( obj, function( i, v ) { | |
if ( traditional || rbracket.test( prefix ) ) { | |
// Treat each array item as a scalar. | |
add( prefix, v ); | |
} else { | |
// Item is non-scalar (array or object), encode its numeric index. | |
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); | |
} | |
}); | |
} else if ( !traditional && jQuery.type( obj ) === "object" ) { | |
// Serialize object item. | |
for ( name in obj ) { | |
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); | |
} | |
} else { | |
// Serialize scalar item. | |
add( prefix, obj ); | |
} | |
} | |
// Serialize an array of form elements or a set of | |
// key/values into a query string | |
jQuery.param = function( a, traditional ) { | |
var prefix, | |
s = [], | |
add = function( key, value ) { | |
// If value is a function, invoke it and return its value | |
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); | |
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); | |
}; | |
// Set traditional to true for jQuery <= 1.3.2 behavior. | |
if ( traditional === undefined ) { | |
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; | |
} | |
// If an array was passed in, assume that it is an array of form elements. | |
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { | |
// Serialize the form elements | |
jQuery.each( a, function() { | |
add( this.name, this.value ); | |
}); | |
} else { | |
// If traditional, encode the "old" way (the way 1.3.2 or older | |
// did it), otherwise encode params recursively. | |
for ( prefix in a ) { | |
buildParams( prefix, a[ prefix ], traditional, add ); | |
} | |
} | |
// Return the resulting serialization | |
return s.join( "&" ).replace( r20, "+" ); | |
}; | |
jQuery.fn.extend({ | |
serialize: function() { | |
return jQuery.param( this.serializeArray() ); | |
}, | |
serializeArray: function() { | |
return this.map(function() { | |
// Can add propHook for "elements" to filter or add form elements | |
var elements = jQuery.prop( this, "elements" ); | |
return elements ? jQuery.makeArray( elements ) : this; | |
}) | |
.filter(function() { | |
var type = this.type; | |
// Use .is( ":disabled" ) so that fieldset[disabled] works | |
return this.name && !jQuery( this ).is( ":disabled" ) && | |
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && | |
( this.checked || !rcheckableType.test( type ) ); | |
}) | |
.map(function( i, elem ) { | |
var val = jQuery( this ).val(); | |
return val == null ? | |
null : | |
jQuery.isArray( val ) ? | |
jQuery.map( val, function( val ) { | |
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; | |
}) : | |
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; | |
}).get(); | |
} | |
}); | |
jQuery.ajaxSettings.xhr = function() { | |
try { | |
return new XMLHttpRequest(); | |
} catch( e ) {} | |
}; | |
var xhrId = 0, | |
xhrCallbacks = {}, | |
xhrSuccessStatus = { | |
// file protocol always yields status code 0, assume 200 | |
0: 200, | |
// Support: IE9 | |
// #1450: sometimes IE returns 1223 when it should be 204 | |
1223: 204 | |
}, | |
xhrSupported = jQuery.ajaxSettings.xhr(); | |
// Support: IE9 | |
// Open requests must be manually aborted on unload (#5280) | |
if ( window.ActiveXObject ) { | |
jQuery( window ).on( "unload", function() { | |
for ( var key in xhrCallbacks ) { | |
xhrCallbacks[ key ](); | |
} | |
}); | |
} | |
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); | |
support.ajax = xhrSupported = !!xhrSupported; | |
jQuery.ajaxTransport(function( options ) { | |
var callback; | |
// Cross domain only allowed if supported through XMLHttpRequest | |
if ( support.cors || xhrSupported && !options.crossDomain ) { | |
return { | |
send: function( headers, complete ) { | |
var i, | |
xhr = options.xhr(), | |
id = ++xhrId; | |
xhr.open( options.type, options.url, options.async, options.username, options.password ); | |
// Apply custom fields if provided | |
if ( options.xhrFields ) { | |
for ( i in options.xhrFields ) { | |
xhr[ i ] = options.xhrFields[ i ]; | |
} | |
} | |
// Override mime type if needed | |
if ( options.mimeType && xhr.overrideMimeType ) { | |
xhr.overrideMimeType( options.mimeType ); | |
} | |
// X-Requested-With header | |
// For cross-domain requests, seeing as conditions for a preflight are | |
// akin to a jigsaw puzzle, we simply never set it to be sure. | |
// (it can always be set on a per-request basis or even using ajaxSetup) | |
// For same-domain requests, won't change header if already provided. | |
if ( !options.crossDomain && !headers["X-Requested-With"] ) { | |
headers["X-Requested-With"] = "XMLHttpRequest"; | |
} | |
// Set headers | |
for ( i in headers ) { | |
xhr.setRequestHeader( i, headers[ i ] ); | |
} | |
// Callback | |
callback = function( type ) { | |
return function() { | |
if ( callback ) { | |
delete xhrCallbacks[ id ]; | |
callback = xhr.onload = xhr.onerror = null; | |
if ( type === "abort" ) { | |
xhr.abort(); | |
} else if ( type === "error" ) { | |
complete( | |
// file: protocol always yields status 0; see #8605, #14207 | |
xhr.status, | |
xhr.statusText | |
); | |
} else { | |
complete( | |
xhrSuccessStatus[ xhr.status ] || xhr.status, | |
xhr.statusText, | |
// Support: IE9 | |
// Accessing binary-data responseText throws an exception | |
// (#11426) | |
typeof xhr.responseText === "string" ? { | |
text: xhr.responseText | |
} : undefined, | |
xhr.getAllResponseHeaders() | |
); | |
} | |
} | |
}; | |
}; | |
// Listen to events | |
xhr.onload = callback(); | |
xhr.onerror = callback("error"); | |
// Create the abort callback | |
callback = xhrCallbacks[ id ] = callback("abort"); | |
try { | |
// Do send the request (this may raise an exception) | |
xhr.send( options.hasContent && options.data || null ); | |
} catch ( e ) { | |
// #14683: Only rethrow if this hasn't been notified as an error yet | |
if ( callback ) { | |
throw e; | |
} | |
} | |
}, | |
abort: function() { | |
if ( callback ) { | |
callback(); | |
} | |
} | |
}; | |
} | |
}); | |
// Install script dataType | |
jQuery.ajaxSetup({ | |
accepts: { | |
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" | |
}, | |
contents: { | |
script: /(?:java|ecma)script/ | |
}, | |
converters: { | |
"text script": function( text ) { | |
jQuery.globalEval( text ); | |
return text; | |
} | |
} | |
}); | |
// Handle cache's special case and crossDomain | |
jQuery.ajaxPrefilter( "script", function( s ) { | |
if ( s.cache === undefined ) { | |
s.cache = false; | |
} | |
if ( s.crossDomain ) { | |
s.type = "GET"; | |
} | |
}); | |
// Bind script tag hack transport | |
jQuery.ajaxTransport( "script", function( s ) { | |
// This transport only deals with cross domain requests | |
if ( s.crossDomain ) { | |
var script, callback; | |
return { | |
send: function( _, complete ) { | |
script = jQuery("<script>").prop({ | |
async: true, | |
charset: s.scriptCharset, | |
src: s.url | |
}).on( | |
"load error", | |
callback = function( evt ) { | |
script.remove(); | |
callback = null; | |
if ( evt ) { | |
complete( evt.type === "error" ? 404 : 200, evt.type ); | |
} | |
} | |
); | |
document.head.appendChild( script[ 0 ] ); | |
}, | |
abort: function() { | |
if ( callback ) { | |
callback(); | |
} | |
} | |
}; | |
} | |
}); | |
var oldCallbacks = [], | |
rjsonp = /(=)\?(?=&|$)|\?\?/; | |
// Default jsonp settings | |
jQuery.ajaxSetup({ | |
jsonp: "callback", | |
jsonpCallback: function() { | |
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); | |
this[ callback ] = true; | |
return callback; | |
} | |
}); | |
// Detect, normalize options and install callbacks for jsonp requests | |
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { | |
var callbackName, overwritten, responseContainer, | |
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? | |
"url" : | |
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" | |
); | |
// Handle iff the expected data type is "jsonp" or we have a parameter to set | |
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { | |
// Get callback name, remembering preexisting value associated with it | |
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? | |
s.jsonpCallback() : | |
s.jsonpCallback; | |
// Insert callback into url or form data | |
if ( jsonProp ) { | |
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); | |
} else if ( s.jsonp !== false ) { | |
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; | |
} | |
// Use data converter to retrieve json after script execution | |
s.converters["script json"] = function() { | |
if ( !responseContainer ) { | |
jQuery.error( callbackName + " was not called" ); | |
} | |
return responseContainer[ 0 ]; | |
}; | |
// force json dataType | |
s.dataTypes[ 0 ] = "json"; | |
// Install callback | |
overwritten = window[ callbackName ]; | |
window[ callbackName ] = function() { | |
responseContainer = arguments; | |
}; | |
// Clean-up function (fires after converters) | |
jqXHR.always(function() { | |
// Restore preexisting value | |
window[ callbackName ] = overwritten; | |
// Save back as free | |
if ( s[ callbackName ] ) { | |
// make sure that re-using the options doesn't screw things around | |
s.jsonpCallback = originalSettings.jsonpCallback; | |
// save the callback name for future use | |
oldCallbacks.push( callbackName ); | |
} | |
// Call if it was a function and we have a response | |
if ( responseContainer && jQuery.isFunction( overwritten ) ) { | |
overwritten( responseContainer[ 0 ] ); | |
} | |
responseContainer = overwritten = undefined; | |
}); | |
// Delegate to script | |
return "script"; | |
} | |
}); | |
// data: string of html | |
// context (optional): If specified, the fragment will be created in this context, defaults to document | |
// keepScripts (optional): If true, will include scripts passed in the html string | |
jQuery.parseHTML = function( data, context, keepScripts ) { | |
if ( !data || typeof data !== "string" ) { | |
return null; | |
} | |
if ( typeof context === "boolean" ) { | |
keepScripts = context; | |
context = false; | |
} | |
context = context || document; | |
var parsed = rsingleTag.exec( data ), | |
scripts = !keepScripts && []; | |
// Single tag | |
if ( parsed ) { | |
return [ context.createElement( parsed[1] ) ]; | |
} | |
parsed = jQuery.buildFragment( [ data ], context, scripts ); | |
if ( scripts && scripts.length ) { | |
jQuery( scripts ).remove(); | |
} | |
return jQuery.merge( [], parsed.childNodes ); | |
}; | |
// Keep a copy of the old load method | |
var _load = jQuery.fn.load; | |
/** | |
* Load a url into a page | |
*/ | |
jQuery.fn.load = function( url, params, callback ) { | |
if ( typeof url !== "string" && _load ) { | |
return _load.apply( this, arguments ); | |
} | |
var selector, type, response, | |
self = this, | |
off = url.indexOf(" "); | |
if ( off >= 0 ) { | |
selector = jQuery.trim( url.slice( off ) ); | |
url = url.slice( 0, off ); | |
} | |
// If it's a function | |
if ( jQuery.isFunction( params ) ) { | |
// We assume that it's the callback | |
callback = params; | |
params = undefined; | |
// Otherwise, build a param string | |
} else if ( params && typeof params === "object" ) { | |
type = "POST"; | |
} | |
// If we have elements to modify, make the request | |
if ( self.length > 0 ) { | |
jQuery.ajax({ | |
url: url, | |
// if "type" variable is undefined, then "GET" method will be used | |
type: type, | |
dataType: "html", | |
data: params | |
}).done(function( responseText ) { | |
// Save response for use in complete callback | |
response = arguments; | |
self.html( selector ? | |
// If a selector was specified, locate the right elements in a dummy div | |
// Exclude scripts to avoid IE 'Permission Denied' errors | |
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : | |
// Otherwise use the full result | |
responseText ); | |
}).complete( callback && function( jqXHR, status ) { | |
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); | |
}); | |
} | |
return this; | |
}; | |
jQuery.expr.filters.animated = function( elem ) { | |
return jQuery.grep(jQuery.timers, function( fn ) { | |
return elem === fn.elem; | |
}).length; | |
}; | |
var docElem = window.document.documentElement; | |
/** | |
* Gets a window from an element | |
*/ | |
function getWindow( elem ) { | |
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; | |
} | |
jQuery.offset = { | |
setOffset: function( elem, options, i ) { | |
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, | |
position = jQuery.css( elem, "position" ), | |
curElem = jQuery( elem ), | |
props = {}; | |
// Set position first, in-case top/left are set even on static elem | |
if ( position === "static" ) { | |
elem.style.position = "relative"; | |
} | |
curOffset = curElem.offset(); | |
curCSSTop = jQuery.css( elem, "top" ); | |
curCSSLeft = jQuery.css( elem, "left" ); | |
calculatePosition = ( position === "absolute" || position === "fixed" ) && | |
( curCSSTop + curCSSLeft ).indexOf("auto") > -1; | |
// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed | |
if ( calculatePosition ) { | |
curPosition = curElem.position(); | |
curTop = curPosition.top; | |
curLeft = curPosition.left; | |
} else { | |
curTop = parseFloat( curCSSTop ) || 0; | |
curLeft = parseFloat( curCSSLeft ) || 0; | |
} | |
if ( jQuery.isFunction( options ) ) { | |
options = options.call( elem, i, curOffset ); | |
} | |
if ( options.top != null ) { | |
props.top = ( options.top - curOffset.top ) + curTop; | |
} | |
if ( options.left != null ) { | |
props.left = ( options.left - curOffset.left ) + curLeft; | |
} | |
if ( "using" in options ) { | |
options.using.call( elem, props ); | |
} else { | |
curElem.css( props ); | |
} | |
} | |
}; | |
jQuery.fn.extend({ | |
offset: function( options ) { | |
if ( arguments.length ) { | |
return options === undefined ? | |
this : | |
this.each(function( i ) { | |
jQuery.offset.setOffset( this, options, i ); | |
}); | |
} | |
var docElem, win, | |
elem = this[ 0 ], | |
box = { top: 0, left: 0 }, | |
doc = elem && elem.ownerDocument; | |
if ( !doc ) { | |
return; | |
} | |
docElem = doc.documentElement; | |
// Make sure it's not a disconnected DOM node | |
if ( !jQuery.contains( docElem, elem ) ) { | |
return box; | |
} | |
// If we don't have gBCR, just use 0,0 rather than error | |
// BlackBerry 5, iOS 3 (original iPhone) | |
if ( typeof elem.getBoundingClientRect !== strundefined ) { | |
box = elem.getBoundingClientRect(); | |
} | |
win = getWindow( doc ); | |
return { | |
top: box.top + win.pageYOffset - docElem.clientTop, | |
left: box.left + win.pageXOffset - docElem.clientLeft | |
}; | |
}, | |
position: function() { | |
if ( !this[ 0 ] ) { | |
return; | |
} | |
var offsetParent, offset, | |
elem = this[ 0 ], | |
parentOffset = { top: 0, left: 0 }; | |
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent | |
if ( jQuery.css( elem, "position" ) === "fixed" ) { | |
// We assume that getBoundingClientRect is available when computed position is fixed | |
offset = elem.getBoundingClientRect(); | |
} else { | |
// Get *real* offsetParent | |
offsetParent = this.offsetParent(); | |
// Get correct offsets | |
offset = this.offset(); | |
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { | |
parentOffset = offsetParent.offset(); | |
} | |
// Add offsetParent borders | |
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); | |
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); | |
} | |
// Subtract parent offsets and element margins | |
return { | |
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), | |
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) | |
}; | |
}, | |
offsetParent: function() { | |
return this.map(function() { | |
var offsetParent = this.offsetParent || docElem; | |
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { | |
offsetParent = offsetParent.offsetParent; | |
} | |
return offsetParent || docElem; | |
}); | |
} | |
}); | |
// Create scrollLeft and scrollTop methods | |
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { | |
var top = "pageYOffset" === prop; | |
jQuery.fn[ method ] = function( val ) { | |
return access( this, function( elem, method, val ) { | |
var win = getWindow( elem ); | |
if ( val === undefined ) { | |
return win ? win[ prop ] : elem[ method ]; | |
} | |
if ( win ) { | |
win.scrollTo( | |
!top ? val : window.pageXOffset, | |
top ? val : window.pageYOffset | |
); | |
} else { | |
elem[ method ] = val; | |
} | |
}, method, val, arguments.length, null ); | |
}; | |
}); | |
// Add the top/left cssHooks using jQuery.fn.position | |
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 | |
// getComputedStyle returns percent when specified for top/left/bottom/right | |
// rather than make the css module depend on the offset module, we just check for it here | |
jQuery.each( [ "top", "left" ], function( i, prop ) { | |
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, | |
function( elem, computed ) { | |
if ( computed ) { | |
computed = curCSS( elem, prop ); | |
// if curCSS returns percentage, fallback to offset | |
return rnumnonpx.test( computed ) ? | |
jQuery( elem ).position()[ prop ] + "px" : | |
computed; | |
} | |
} | |
); | |
}); | |
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods | |
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { | |
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { | |
// margin is only for outerHeight, outerWidth | |
jQuery.fn[ funcName ] = function( margin, value ) { | |
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), | |
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); | |
return access( this, function( elem, type, value ) { | |
var doc; | |
if ( jQuery.isWindow( elem ) ) { | |
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there | |
// isn't a whole lot we can do. See pull request at this URL for discussion: | |
// https://github.com/jquery/jquery/pull/764 | |
return elem.document.documentElement[ "client" + name ]; | |
} | |
// Get document width or height | |
if ( elem.nodeType === 9 ) { | |
doc = elem.documentElement; | |
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], | |
// whichever is greatest | |
return Math.max( | |
elem.body[ "scroll" + name ], doc[ "scroll" + name ], | |
elem.body[ "offset" + name ], doc[ "offset" + name ], | |
doc[ "client" + name ] | |
); | |
} | |
return value === undefined ? | |
// Get width or height on the element, requesting but not forcing parseFloat | |
jQuery.css( elem, type, extra ) : | |
// Set width or height on the element | |
jQuery.style( elem, type, value, extra ); | |
}, type, chainable ? margin : undefined, chainable, null ); | |
}; | |
}); | |
}); | |
// The number of elements contained in the matched element set | |
jQuery.fn.size = function() { | |
return this.length; | |
}; | |
jQuery.fn.andSelf = jQuery.fn.addBack; | |
// Register as a named AMD module, since jQuery can be concatenated with other | |
// files that may use define, but not via a proper concatenation script that | |
// understands anonymous AMD modules. A named AMD is safest and most robust | |
// way to register. Lowercase jquery is used because AMD module names are | |
// derived from file names, and jQuery is normally delivered in a lowercase | |
// file name. Do this after creating the global so that if an AMD module wants | |
// to call noConflict to hide this version of jQuery, it will work. | |
// Note that for maximum portability, libraries that are not jQuery should | |
// declare themselves as anonymous modules, and avoid setting a global if an | |
// AMD loader is present. jQuery is a special case. For more information, see | |
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon | |
if ( typeof define === "function" && define.amd ) { | |
define( "jquery", [], function() { | |
return jQuery; | |
}); | |
} | |
var | |
// Map over jQuery in case of overwrite | |
_jQuery = window.jQuery, | |
// Map over the $ in case of overwrite | |
_$ = window.$; | |
jQuery.noConflict = function( deep ) { | |
if ( window.$ === jQuery ) { | |
window.$ = _$; | |
} | |
if ( deep && window.jQuery === jQuery ) { | |
window.jQuery = _jQuery; | |
} | |
return jQuery; | |
}; | |
// Expose jQuery and $ identifiers, even in | |
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) | |
// and CommonJS for browser emulators (#13566) | |
if ( typeof noGlobal === strundefined ) { | |
window.jQuery = window.$ = jQuery; | |
} | |
return jQuery; | |
})); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com | |
(c) 2010-2013, Vladimir Agafonkin | |
(c) 2010-2011, CloudMade | |
*/ | |
(function (window, document, undefined) { | |
var oldL = window.L, | |
L = {}; | |
L.version = '0.7.3'; | |
// define Leaflet for Node module pattern loaders, including Browserify | |
if (typeof module === 'object' && typeof module.exports === 'object') { | |
module.exports = L; | |
// define Leaflet as an AMD module | |
} else if (typeof define === 'function' && define.amd) { | |
define(L); | |
} | |
// define Leaflet as a global L variable, saving the original L to restore later if needed | |
L.noConflict = function () { | |
window.L = oldL; | |
return this; | |
}; | |
window.L = L; | |
/* | |
* L.Util contains various utility functions used throughout Leaflet code. | |
*/ | |
L.Util = { | |
extend: function (dest) { // (Object[, Object, ...]) -> | |
var sources = Array.prototype.slice.call(arguments, 1), | |
i, j, len, src; | |
for (j = 0, len = sources.length; j < len; j++) { | |
src = sources[j] || {}; | |
for (i in src) { | |
if (src.hasOwnProperty(i)) { | |
dest[i] = src[i]; | |
} | |
} | |
} | |
return dest; | |
}, | |
bind: function (fn, obj) { // (Function, Object) -> Function | |
var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null; | |
return function () { | |
return fn.apply(obj, args || arguments); | |
}; | |
}, | |
stamp: (function () { | |
var lastId = 0, | |
key = '_leaflet_id'; | |
return function (obj) { | |
obj[key] = obj[key] || ++lastId; | |
return obj[key]; | |
}; | |
}()), | |
invokeEach: function (obj, method, context) { | |
var i, args; | |
if (typeof obj === 'object') { | |
args = Array.prototype.slice.call(arguments, 3); | |
for (i in obj) { | |
method.apply(context, [i, obj[i]].concat(args)); | |
} | |
return true; | |
} | |
return false; | |
}, | |
limitExecByInterval: function (fn, time, context) { | |
var lock, execOnUnlock; | |
return function wrapperFn() { | |
var args = arguments; | |
if (lock) { | |
execOnUnlock = true; | |
return; | |
} | |
lock = true; | |
setTimeout(function () { | |
lock = false; | |
if (execOnUnlock) { | |
wrapperFn.apply(context, args); | |
execOnUnlock = false; | |
} | |
}, time); | |
fn.apply(context, args); | |
}; | |
}, | |
falseFn: function () { | |
return false; | |
}, | |
formatNum: function (num, digits) { | |
var pow = Math.pow(10, digits || 5); | |
return Math.round(num * pow) / pow; | |
}, | |
trim: function (str) { | |
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); | |
}, | |
splitWords: function (str) { | |
return L.Util.trim(str).split(/\s+/); | |
}, | |
setOptions: function (obj, options) { | |
obj.options = L.extend({}, obj.options, options); | |
return obj.options; | |
}, | |
getParamString: function (obj, existingUrl, uppercase) { | |
var params = []; | |
for (var i in obj) { | |
params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i])); | |
} | |
return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&'); | |
}, | |
template: function (str, data) { | |
return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { | |
var value = data[key]; | |
if (value === undefined) { | |
throw new Error('No value provided for variable ' + str); | |
} else if (typeof value === 'function') { | |
value = value(data); | |
} | |
return value; | |
}); | |
}, | |
isArray: Array.isArray || function (obj) { | |
return (Object.prototype.toString.call(obj) === '[object Array]'); | |
}, | |
emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' | |
}; | |
(function () { | |
// inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/ | |
function getPrefixed(name) { | |
var i, fn, | |
prefixes = ['webkit', 'moz', 'o', 'ms']; | |
for (i = 0; i < prefixes.length && !fn; i++) { | |
fn = window[prefixes[i] + name]; | |
} | |
return fn; | |
} | |
var lastTime = 0; | |
function timeoutDefer(fn) { | |
var time = +new Date(), | |
timeToCall = Math.max(0, 16 - (time - lastTime)); | |
lastTime = time + timeToCall; | |
return window.setTimeout(fn, timeToCall); | |
} | |
var requestFn = window.requestAnimationFrame || | |
getPrefixed('RequestAnimationFrame') || timeoutDefer; | |
var cancelFn = window.cancelAnimationFrame || | |
getPrefixed('CancelAnimationFrame') || | |
getPrefixed('CancelRequestAnimationFrame') || | |
function (id) { window.clearTimeout(id); }; | |
L.Util.requestAnimFrame = function (fn, context, immediate, element) { | |
fn = L.bind(fn, context); | |
if (immediate && requestFn === timeoutDefer) { | |
fn(); | |
} else { | |
return requestFn.call(window, fn, element); | |
} | |
}; | |
L.Util.cancelAnimFrame = function (id) { | |
if (id) { | |
cancelFn.call(window, id); | |
} | |
}; | |
}()); | |
// shortcuts for most used utility functions | |
L.extend = L.Util.extend; | |
L.bind = L.Util.bind; | |
L.stamp = L.Util.stamp; | |
L.setOptions = L.Util.setOptions; | |
/* | |
* L.Class powers the OOP facilities of the library. | |
* Thanks to John Resig and Dean Edwards for inspiration! | |
*/ | |
L.Class = function () {}; | |
L.Class.extend = function (props) { | |
// extended class with the new prototype | |
var NewClass = function () { | |
// call the constructor | |
if (this.initialize) { | |
this.initialize.apply(this, arguments); | |
} | |
// call all constructor hooks | |
if (this._initHooks) { | |
this.callInitHooks(); | |
} | |
}; | |
// instantiate class without calling constructor | |
var F = function () {}; | |
F.prototype = this.prototype; | |
var proto = new F(); | |
proto.constructor = NewClass; | |
NewClass.prototype = proto; | |
//inherit parent's statics | |
for (var i in this) { | |
if (this.hasOwnProperty(i) && i !== 'prototype') { | |
NewClass[i] = this[i]; | |
} | |
} | |
// mix static properties into the class | |
if (props.statics) { | |
L.extend(NewClass, props.statics); | |
delete props.statics; | |
} | |
// mix includes into the prototype | |
if (props.includes) { | |
L.Util.extend.apply(null, [proto].concat(props.includes)); | |
delete props.includes; | |
} | |
// merge options | |
if (props.options && proto.options) { | |
props.options = L.extend({}, proto.options, props.options); | |
} | |
// mix given properties into the prototype | |
L.extend(proto, props); | |
proto._initHooks = []; | |
var parent = this; | |
// jshint camelcase: false | |
NewClass.__super__ = parent.prototype; | |
// add method for calling all hooks | |
proto.callInitHooks = function () { | |
if (this._initHooksCalled) { return; } | |
if (parent.prototype.callInitHooks) { | |
parent.prototype.callInitHooks.call(this); | |
} | |
this._initHooksCalled = true; | |
for (var i = 0, len = proto._initHooks.length; i < len; i++) { | |
proto._initHooks[i].call(this); | |
} | |
}; | |
return NewClass; | |
}; | |
// method for adding properties to prototype | |
L.Class.include = function (props) { | |
L.extend(this.prototype, props); | |
}; | |
// merge new default options to the Class | |
L.Class.mergeOptions = function (options) { | |
L.extend(this.prototype.options, options); | |
}; | |
// add a constructor hook | |
L.Class.addInitHook = function (fn) { // (Function) || (String, args...) | |
var args = Array.prototype.slice.call(arguments, 1); | |
var init = typeof fn === 'function' ? fn : function () { | |
this[fn].apply(this, args); | |
}; | |
this.prototype._initHooks = this.prototype._initHooks || []; | |
this.prototype._initHooks.push(init); | |
}; | |
/* | |
* L.Mixin.Events is used to add custom events functionality to Leaflet classes. | |
*/ | |
var eventsKey = '_leaflet_events'; | |
L.Mixin = {}; | |
L.Mixin.Events = { | |
addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object]) | |
// types can be a map of types/handlers | |
if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; } | |
var events = this[eventsKey] = this[eventsKey] || {}, | |
contextId = context && context !== this && L.stamp(context), | |
i, len, event, type, indexKey, indexLenKey, typeIndex; | |
// types can be a string of space-separated words | |
types = L.Util.splitWords(types); | |
for (i = 0, len = types.length; i < len; i++) { | |
event = { | |
action: fn, | |
context: context || this | |
}; | |
type = types[i]; | |
if (contextId) { | |
// store listeners of a particular context in a separate hash (if it has an id) | |
// gives a major performance boost when removing thousands of map layers | |
indexKey = type + '_idx'; | |
indexLenKey = indexKey + '_len'; | |
typeIndex = events[indexKey] = events[indexKey] || {}; | |
if (!typeIndex[contextId]) { | |
typeIndex[contextId] = []; | |
// keep track of the number of keys in the index to quickly check if it's empty | |
events[indexLenKey] = (events[indexLenKey] || 0) + 1; | |
} | |
typeIndex[contextId].push(event); | |
} else { | |
events[type] = events[type] || []; | |
events[type].push(event); | |
} | |
} | |
return this; | |
}, | |
hasEventListeners: function (type) { // (String) -> Boolean | |
var events = this[eventsKey]; | |
return !!events && ((type in events && events[type].length > 0) || | |
(type + '_idx' in events && events[type + '_idx_len'] > 0)); | |
}, | |
removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object]) | |
if (!this[eventsKey]) { | |
return this; | |
} | |
if (!types) { | |
return this.clearAllEventListeners(); | |
} | |
if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; } | |
var events = this[eventsKey], | |
contextId = context && context !== this && L.stamp(context), | |
i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed; | |
types = L.Util.splitWords(types); | |
for (i = 0, len = types.length; i < len; i++) { | |
type = types[i]; | |
indexKey = type + '_idx'; | |
indexLenKey = indexKey + '_len'; | |
typeIndex = events[indexKey]; | |
if (!fn) { | |
// clear all listeners for a type if function isn't specified | |
delete events[type]; | |
delete events[indexKey]; | |
delete events[indexLenKey]; | |
} else { | |
listeners = contextId && typeIndex ? typeIndex[contextId] : events[type]; | |
if (listeners) { | |
for (j = listeners.length - 1; j >= 0; j--) { | |
if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) { | |
removed = listeners.splice(j, 1); | |
// set the old action to a no-op, because it is possible | |
// that the listener is being iterated over as part of a dispatch | |
removed[0].action = L.Util.falseFn; | |
} | |
} | |
if (context && typeIndex && (listeners.length === 0)) { | |
delete typeIndex[contextId]; | |
events[indexLenKey]--; | |
} | |
} | |
} | |
} | |
return this; | |
}, | |
clearAllEventListeners: function () { | |
delete this[eventsKey]; | |
return this; | |
}, | |
fireEvent: function (type, data) { // (String[, Object]) | |
if (!this.hasEventListeners(type)) { | |
return this; | |
} | |
var event = L.Util.extend({}, data, { type: type, target: this }); | |
var events = this[eventsKey], | |
listeners, i, len, typeIndex, contextId; | |
if (events[type]) { | |
// make sure adding/removing listeners inside other listeners won't cause infinite loop | |
listeners = events[type].slice(); | |
for (i = 0, len = listeners.length; i < len; i++) { | |
listeners[i].action.call(listeners[i].context, event); | |
} | |
} | |
// fire event for the context-indexed listeners as well | |
typeIndex = events[type + '_idx']; | |
for (contextId in typeIndex) { | |
listeners = typeIndex[contextId].slice(); | |
if (listeners) { | |
for (i = 0, len = listeners.length; i < len; i++) { | |
listeners[i].action.call(listeners[i].context, event); | |
} | |
} | |
} | |
return this; | |
}, | |
addOneTimeEventListener: function (types, fn, context) { | |
if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; } | |
var handler = L.bind(function () { | |
this | |
.removeEventListener(types, fn, context) | |
.removeEventListener(types, handler, context); | |
}, this); | |
return this | |
.addEventListener(types, fn, context) | |
.addEventListener(types, handler, context); | |
} | |
}; | |
L.Mixin.Events.on = L.Mixin.Events.addEventListener; | |
L.Mixin.Events.off = L.Mixin.Events.removeEventListener; | |
L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener; | |
L.Mixin.Events.fire = L.Mixin.Events.fireEvent; | |
/* | |
* L.Browser handles different browser and feature detections for internal Leaflet use. | |
*/ | |
(function () { | |
var ie = 'ActiveXObject' in window, | |
ielt9 = ie && !document.addEventListener, | |
// terrible browser detection to work around Safari / iOS / Android browser bugs | |
ua = navigator.userAgent.toLowerCase(), | |
webkit = ua.indexOf('webkit') !== -1, | |
chrome = ua.indexOf('chrome') !== -1, | |
phantomjs = ua.indexOf('phantom') !== -1, | |
android = ua.indexOf('android') !== -1, | |
android23 = ua.search('android [23]') !== -1, | |
gecko = ua.indexOf('gecko') !== -1, | |
mobile = typeof orientation !== undefined + '', | |
msPointer = window.navigator && window.navigator.msPointerEnabled && | |
window.navigator.msMaxTouchPoints && !window.PointerEvent, | |
pointer = (window.PointerEvent && window.navigator.pointerEnabled && window.navigator.maxTouchPoints) || | |
msPointer, | |
retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) || | |
('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') && | |
window.matchMedia('(min-resolution:144dpi)').matches), | |
doc = document.documentElement, | |
ie3d = ie && ('transition' in doc.style), | |
webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23, | |
gecko3d = 'MozPerspective' in doc.style, | |
opera3d = 'OTransition' in doc.style, | |
any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs; | |
// PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch. | |
// https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151 | |
var touch = !window.L_NO_TOUCH && !phantomjs && (function () { | |
var startName = 'ontouchstart'; | |
// IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.Pointer) or WebKit, etc. | |
if (pointer || (startName in doc)) { | |
return true; | |
} | |
// Firefox/Gecko | |
var div = document.createElement('div'), | |
supported = false; | |
if (!div.setAttribute) { | |
return false; | |
} | |
div.setAttribute(startName, 'return;'); | |
if (typeof div[startName] === 'function') { | |
supported = true; | |
} | |
div.removeAttribute(startName); | |
div = null; | |
return supported; | |
}()); | |
L.Browser = { | |
ie: ie, | |
ielt9: ielt9, | |
webkit: webkit, | |
gecko: gecko && !webkit && !window.opera && !ie, | |
android: android, | |
android23: android23, | |
chrome: chrome, | |
ie3d: ie3d, | |
webkit3d: webkit3d, | |
gecko3d: gecko3d, | |
opera3d: opera3d, | |
any3d: any3d, | |
mobile: mobile, | |
mobileWebkit: mobile && webkit, | |
mobileWebkit3d: mobile && webkit3d, | |
mobileOpera: mobile && window.opera, | |
touch: touch, | |
msPointer: msPointer, | |
pointer: pointer, | |
retina: retina | |
}; | |
}()); | |
/* | |
* L.Point represents a point with x and y coordinates. | |
*/ | |
L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) { | |
this.x = (round ? Math.round(x) : x); | |
this.y = (round ? Math.round(y) : y); | |
}; | |
L.Point.prototype = { | |
clone: function () { | |
return new L.Point(this.x, this.y); | |
}, | |
// non-destructive, returns a new point | |
add: function (point) { | |
return this.clone()._add(L.point(point)); | |
}, | |
// destructive, used directly for performance in situations where it's safe to modify existing point | |
_add: function (point) { | |
this.x += point.x; | |
this.y += point.y; | |
return this; | |
}, | |
subtract: function (point) { | |
return this.clone()._subtract(L.point(point)); | |
}, | |
_subtract: function (point) { | |
this.x -= point.x; | |
this.y -= point.y; | |
return this; | |
}, | |
divideBy: function (num) { | |
return this.clone()._divideBy(num); | |
}, | |
_divideBy: function (num) { | |
this.x /= num; | |
this.y /= num; | |
return this; | |
}, | |
multiplyBy: function (num) { | |
return this.clone()._multiplyBy(num); | |
}, | |
_multiplyBy: function (num) { | |
this.x *= num; | |
this.y *= num; | |
return this; | |
}, | |
round: function () { | |
return this.clone()._round(); | |
}, | |
_round: function () { | |
this.x = Math.round(this.x); | |
this.y = Math.round(this.y); | |
return this; | |
}, | |
floor: function () { | |
return this.clone()._floor(); | |
}, | |
_floor: function () { | |
this.x = Math.floor(this.x); | |
this.y = Math.floor(this.y); | |
return this; | |
}, | |
distanceTo: function (point) { | |
point = L.point(point); | |
var x = point.x - this.x, | |
y = point.y - this.y; | |
return Math.sqrt(x * x + y * y); | |
}, | |
equals: function (point) { | |
point = L.point(point); | |
return point.x === this.x && | |
point.y === this.y; | |
}, | |
contains: function (point) { | |
point = L.point(point); | |
return Math.abs(point.x) <= Math.abs(this.x) && | |
Math.abs(point.y) <= Math.abs(this.y); | |
}, | |
toString: function () { | |
return 'Point(' + | |
L.Util.formatNum(this.x) + ', ' + | |
L.Util.formatNum(this.y) + ')'; | |
} | |
}; | |
L.point = function (x, y, round) { | |
if (x instanceof L.Point) { | |
return x; | |
} | |
if (L.Util.isArray(x)) { | |
return new L.Point(x[0], x[1]); | |
} | |
if (x === undefined || x === null) { | |
return x; | |
} | |
return new L.Point(x, y, round); | |
}; | |
/* | |
* L.Bounds represents a rectangular area on the screen in pixel coordinates. | |
*/ | |
L.Bounds = function (a, b) { //(Point, Point) or Point[] | |
if (!a) { return; } | |
var points = b ? [a, b] : a; | |
for (var i = 0, len = points.length; i < len; i++) { | |
this.extend(points[i]); | |
} | |
}; | |
L.Bounds.prototype = { | |
// extend the bounds to contain the given point | |
extend: function (point) { // (Point) | |
point = L.point(point); | |
if (!this.min && !this.max) { | |
this.min = point.clone(); | |
this.max = point.clone(); | |
} else { | |
this.min.x = Math.min(point.x, this.min.x); | |
this.max.x = Math.max(point.x, this.max.x); | |
this.min.y = Math.min(point.y, this.min.y); | |
this.max.y = Math.max(point.y, this.max.y); | |
} | |
return this; | |
}, | |
getCenter: function (round) { // (Boolean) -> Point | |
return new L.Point( | |
(this.min.x + this.max.x) / 2, | |
(this.min.y + this.max.y) / 2, round); | |
}, | |
getBottomLeft: function () { // -> Point | |
return new L.Point(this.min.x, this.max.y); | |
}, | |
getTopRight: function () { // -> Point | |
return new L.Point(this.max.x, this.min.y); | |
}, | |
getSize: function () { | |
return this.max.subtract(this.min); | |
}, | |
contains: function (obj) { // (Bounds) or (Point) -> Boolean | |
var min, max; | |
if (typeof obj[0] === 'number' || obj instanceof L.Point) { | |
obj = L.point(obj); | |
} else { | |
obj = L.bounds(obj); | |
} | |
if (obj instanceof L.Bounds) { | |
min = obj.min; | |
max = obj.max; | |
} else { | |
min = max = obj; | |
} | |
return (min.x >= this.min.x) && | |
(max.x <= this.max.x) && | |
(min.y >= this.min.y) && | |
(max.y <= this.max.y); | |
}, | |
intersects: function (bounds) { // (Bounds) -> Boolean | |
bounds = L.bounds(bounds); | |
var min = this.min, | |
max = this.max, | |
min2 = bounds.min, | |
max2 = bounds.max, | |
xIntersects = (max2.x >= min.x) && (min2.x <= max.x), | |
yIntersects = (max2.y >= min.y) && (min2.y <= max.y); | |
return xIntersects && yIntersects; | |
}, | |
isValid: function () { | |
return !!(this.min && this.max); | |
} | |
}; | |
L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[]) | |
if (!a || a instanceof L.Bounds) { | |
return a; | |
} | |
return new L.Bounds(a, b); | |
}; | |
/* | |
* L.Transformation is an utility class to perform simple point transformations through a 2d-matrix. | |
*/ | |
L.Transformation = function (a, b, c, d) { | |
this._a = a; | |
this._b = b; | |
this._c = c; | |
this._d = d; | |
}; | |
L.Transformation.prototype = { | |
transform: function (point, scale) { // (Point, Number) -> Point | |
return this._transform(point.clone(), scale); | |
}, | |
// destructive transform (faster) | |
_transform: function (point, scale) { | |
scale = scale || 1; | |
point.x = scale * (this._a * point.x + this._b); | |
point.y = scale * (this._c * point.y + this._d); | |
return point; | |
}, | |
untransform: function (point, scale) { | |
scale = scale || 1; | |
return new L.Point( | |
(point.x / scale - this._b) / this._a, | |
(point.y / scale - this._d) / this._c); | |
} | |
}; | |
/* | |
* L.DomUtil contains various utility functions for working with DOM. | |
*/ | |
L.DomUtil = { | |
get: function (id) { | |
return (typeof id === 'string' ? document.getElementById(id) : id); | |
}, | |
getStyle: function (el, style) { | |
var value = el.style[style]; | |
if (!value && el.currentStyle) { | |
value = el.currentStyle[style]; | |
} | |
if ((!value || value === 'auto') && document.defaultView) { | |
var css = document.defaultView.getComputedStyle(el, null); | |
value = css ? css[style] : null; | |
} | |
return value === 'auto' ? null : value; | |
}, | |
getViewportOffset: function (element) { | |
var top = 0, | |
left = 0, | |
el = element, | |
docBody = document.body, | |
docEl = document.documentElement, | |
pos; | |
do { | |
top += el.offsetTop || 0; | |
left += el.offsetLeft || 0; | |
//add borders | |
top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0; | |
left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0; | |
pos = L.DomUtil.getStyle(el, 'position'); | |
if (el.offsetParent === docBody && pos === 'absolute') { break; } | |
if (pos === 'fixed') { | |
top += docBody.scrollTop || docEl.scrollTop || 0; | |
left += docBody.scrollLeft || docEl.scrollLeft || 0; | |
break; | |
} | |
if (pos === 'relative' && !el.offsetLeft) { | |
var width = L.DomUtil.getStyle(el, 'width'), | |
maxWidth = L.DomUtil.getStyle(el, 'max-width'), | |
r = el.getBoundingClientRect(); | |
if (width !== 'none' || maxWidth !== 'none') { | |
left += r.left + el.clientLeft; | |
} | |
//calculate full y offset since we're breaking out of the loop | |
top += r.top + (docBody.scrollTop || docEl.scrollTop || 0); | |
break; | |
} | |
el = el.offsetParent; | |
} while (el); | |
el = element; | |
do { | |
if (el === docBody) { break; } | |
top -= el.scrollTop || 0; | |
left -= el.scrollLeft || 0; | |
el = el.parentNode; | |
} while (el); | |
return new L.Point(left, top); | |
}, | |
documentIsLtr: function () { | |
if (!L.DomUtil._docIsLtrCached) { | |
L.DomUtil._docIsLtrCached = true; | |
L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr'; | |
} | |
return L.DomUtil._docIsLtr; | |
}, | |
create: function (tagName, className, container) { | |
var el = document.createElement(tagName); | |
el.className = className; | |
if (container) { | |
container.appendChild(el); | |
} | |
return el; | |
}, | |
hasClass: function (el, name) { | |
if (el.classList !== undefined) { | |
return el.classList.contains(name); | |
} | |
var className = L.DomUtil._getClass(el); | |
return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className); | |
}, | |
addClass: function (el, name) { | |
if (el.classList !== undefined) { | |
var classes = L.Util.splitWords(name); | |
for (var i = 0, len = classes.length; i < len; i++) { | |
el.classList.add(classes[i]); | |
} | |
} else if (!L.DomUtil.hasClass(el, name)) { | |
var className = L.DomUtil._getClass(el); | |
L.DomUtil._setClass(el, (className ? className + ' ' : '') + name); | |
} | |
}, | |
removeClass: function (el, name) { | |
if (el.classList !== undefined) { | |
el.classList.remove(name); | |
} else { | |
L.DomUtil._setClass(el, L.Util.trim((' ' + L.DomUtil._getClass(el) + ' ').replace(' ' + name + ' ', ' '))); | |
} | |
}, | |
_setClass: function (el, name) { | |
if (el.className.baseVal === undefined) { | |
el.className = name; | |
} else { | |
// in case of SVG element | |
el.className.baseVal = name; | |
} | |
}, | |
_getClass: function (el) { | |
return el.className.baseVal === undefined ? el.className : el.className.baseVal; | |
}, | |
setOpacity: function (el, value) { | |
if ('opacity' in el.style) { | |
el.style.opacity = value; | |
} else if ('filter' in el.style) { | |
var filter = false, | |
filterName = 'DXImageTransform.Microsoft.Alpha'; | |
// filters collection throws an error if we try to retrieve a filter that doesn't exist | |
try { | |
filter = el.filters.item(filterName); | |
} catch (e) { | |
// don't set opacity to 1 if we haven't already set an opacity, | |
// it isn't needed and breaks transparent pngs. | |
if (value === 1) { return; } | |
} | |
value = Math.round(value * 100); | |
if (filter) { | |
filter.Enabled = (value !== 100); | |
filter.Opacity = value; | |
} else { | |
el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')'; | |
} | |
} | |
}, | |
testProp: function (props) { | |
var style = document.documentElement.style; | |
for (var i = 0; i < props.length; i++) { | |
if (props[i] in style) { | |
return props[i]; | |
} | |
} | |
return false; | |
}, | |
getTranslateString: function (point) { | |
// on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate | |
// makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care | |
// (same speed either way), Opera 12 doesn't support translate3d | |
var is3d = L.Browser.webkit3d, | |
open = 'translate' + (is3d ? '3d' : '') + '(', | |
close = (is3d ? ',0' : '') + ')'; | |
return open + point.x + 'px,' + point.y + 'px' + close; | |
}, | |
getScaleString: function (scale, origin) { | |
var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))), | |
scaleStr = ' scale(' + scale + ') '; | |
return preTranslateStr + scaleStr; | |
}, | |
setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean]) | |
// jshint camelcase: false | |
el._leaflet_pos = point; | |
if (!disable3D && L.Browser.any3d) { | |
el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point); | |
} else { | |
el.style.left = point.x + 'px'; | |
el.style.top = point.y + 'px'; | |
} | |
}, | |
getPosition: function (el) { | |
// this method is only used for elements previously positioned using setPosition, | |
// so it's safe to cache the position for performance | |
// jshint camelcase: false | |
return el._leaflet_pos; | |
} | |
}; | |
// prefix style property names | |
L.DomUtil.TRANSFORM = L.DomUtil.testProp( | |
['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']); | |
// webkitTransition comes first because some browser versions that drop vendor prefix don't do | |
// the same for the transitionend event, in particular the Android 4.1 stock browser | |
L.DomUtil.TRANSITION = L.DomUtil.testProp( | |
['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']); | |
L.DomUtil.TRANSITION_END = | |
L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ? | |
L.DomUtil.TRANSITION + 'End' : 'transitionend'; | |
(function () { | |
if ('onselectstart' in document) { | |
L.extend(L.DomUtil, { | |
disableTextSelection: function () { | |
L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault); | |
}, | |
enableTextSelection: function () { | |
L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault); | |
} | |
}); | |
} else { | |
var userSelectProperty = L.DomUtil.testProp( | |
['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']); | |
L.extend(L.DomUtil, { | |
disableTextSelection: function () { | |
if (userSelectProperty) { | |
var style = document.documentElement.style; | |
this._userSelect = style[userSelectProperty]; | |
style[userSelectProperty] = 'none'; | |
} | |
}, | |
enableTextSelection: function () { | |
if (userSelectProperty) { | |
document.documentElement.style[userSelectProperty] = this._userSelect; | |
delete this._userSelect; | |
} | |
} | |
}); | |
} | |
L.extend(L.DomUtil, { | |
disableImageDrag: function () { | |
L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault); | |
}, | |
enableImageDrag: function () { | |
L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault); | |
} | |
}); | |
})(); | |
/* | |
* L.LatLng represents a geographical point with latitude and longitude coordinates. | |
*/ | |
L.LatLng = function (lat, lng, alt) { // (Number, Number, Number) | |
lat = parseFloat(lat); | |
lng = parseFloat(lng); | |
if (isNaN(lat) || isNaN(lng)) { | |
throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')'); | |
} | |
this.lat = lat; | |
this.lng = lng; | |
if (alt !== undefined) { | |
this.alt = parseFloat(alt); | |
} | |
}; | |
L.extend(L.LatLng, { | |
DEG_TO_RAD: Math.PI / 180, | |
RAD_TO_DEG: 180 / Math.PI, | |
MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check | |
}); | |
L.LatLng.prototype = { | |
equals: function (obj) { // (LatLng) -> Boolean | |
if (!obj) { return false; } | |
obj = L.latLng(obj); | |
var margin = Math.max( | |
Math.abs(this.lat - obj.lat), | |
Math.abs(this.lng - obj.lng)); | |
return margin <= L.LatLng.MAX_MARGIN; | |
}, | |
toString: function (precision) { // (Number) -> String | |
return 'LatLng(' + | |
L.Util.formatNum(this.lat, precision) + ', ' + | |
L.Util.formatNum(this.lng, precision) + ')'; | |
}, | |
// Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula | |
// TODO move to projection code, LatLng shouldn't know about Earth | |
distanceTo: function (other) { // (LatLng) -> Number | |
other = L.latLng(other); | |
var R = 6378137, // earth radius in meters | |
d2r = L.LatLng.DEG_TO_RAD, | |
dLat = (other.lat - this.lat) * d2r, | |
dLon = (other.lng - this.lng) * d2r, | |
lat1 = this.lat * d2r, | |
lat2 = other.lat * d2r, | |
sin1 = Math.sin(dLat / 2), | |
sin2 = Math.sin(dLon / 2); | |
var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2); | |
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
}, | |
wrap: function (a, b) { // (Number, Number) -> LatLng | |
var lng = this.lng; | |
a = a || -180; | |
b = b || 180; | |
lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a); | |
return new L.LatLng(this.lat, lng); | |
} | |
}; | |
L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number) | |
if (a instanceof L.LatLng) { | |
return a; | |
} | |
if (L.Util.isArray(a)) { | |
if (typeof a[0] === 'number' || typeof a[0] === 'string') { | |
return new L.LatLng(a[0], a[1], a[2]); | |
} else { | |
return null; | |
} | |
} | |
if (a === undefined || a === null) { | |
return a; | |
} | |
if (typeof a === 'object' && 'lat' in a) { | |
return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon); | |
} | |
if (b === undefined) { | |
return null; | |
} | |
return new L.LatLng(a, b); | |
}; | |
/* | |
* L.LatLngBounds represents a rectangular area on the map in geographical coordinates. | |
*/ | |
L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[]) | |
if (!southWest) { return; } | |
var latlngs = northEast ? [southWest, northEast] : southWest; | |
for (var i = 0, len = latlngs.length; i < len; i++) { | |
this.extend(latlngs[i]); | |
} | |
}; | |
L.LatLngBounds.prototype = { | |
// extend the bounds to contain the given point or bounds | |
extend: function (obj) { // (LatLng) or (LatLngBounds) | |
if (!obj) { return this; } | |
var latLng = L.latLng(obj); | |
if (latLng !== null) { | |
obj = latLng; | |
} else { | |
obj = L.latLngBounds(obj); | |
} | |
if (obj instanceof L.LatLng) { | |
if (!this._southWest && !this._northEast) { | |
this._southWest = new L.LatLng(obj.lat, obj.lng); | |
this._northEast = new L.LatLng(obj.lat, obj.lng); | |
} else { | |
this._southWest.lat = Math.min(obj.lat, this._southWest.lat); | |
this._southWest.lng = Math.min(obj.lng, this._southWest.lng); | |
this._northEast.lat = Math.max(obj.lat, this._northEast.lat); | |
this._northEast.lng = Math.max(obj.lng, this._northEast.lng); | |
} | |
} else if (obj instanceof L.LatLngBounds) { | |
this.extend(obj._southWest); | |
this.extend(obj._northEast); | |
} | |
return this; | |
}, | |
// extend the bounds by a percentage | |
pad: function (bufferRatio) { // (Number) -> LatLngBounds | |
var sw = this._southWest, | |
ne = this._northEast, | |
heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, | |
widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio; | |
return new L.LatLngBounds( | |
new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer), | |
new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)); | |
}, | |
getCenter: function () { // -> LatLng | |
return new L.LatLng( | |
(this._southWest.lat + this._northEast.lat) / 2, | |
(this._southWest.lng + this._northEast.lng) / 2); | |
}, | |
getSouthWest: function () { | |
return this._southWest; | |
}, | |
getNorthEast: function () { | |
return this._northEast; | |
}, | |
getNorthWest: function () { | |
return new L.LatLng(this.getNorth(), this.getWest()); | |
}, | |
getSouthEast: function () { | |
return new L.LatLng(this.getSouth(), this.getEast()); | |
}, | |
getWest: function () { | |
return this._southWest.lng; | |
}, | |
getSouth: function () { | |
return this._southWest.lat; | |
}, | |
getEast: function () { | |
return this._northEast.lng; | |
}, | |
getNorth: function () { | |
return this._northEast.lat; | |
}, | |
contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean | |
if (typeof obj[0] === 'number' || obj instanceof L.LatLng) { | |
obj = L.latLng(obj); | |
} else { | |
obj = L.latLngBounds(obj); | |
} | |
var sw = this._southWest, | |
ne = this._northEast, | |
sw2, ne2; | |
if (obj instanceof L.LatLngBounds) { | |
sw2 = obj.getSouthWest(); | |
ne2 = obj.getNorthEast(); | |
} else { | |
sw2 = ne2 = obj; | |
} | |
return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) && | |
(sw2.lng >= sw.lng) && (ne2.lng <= ne.lng); | |
}, | |
intersects: function (bounds) { // (LatLngBounds) | |
bounds = L.latLngBounds(bounds); | |
var sw = this._southWest, | |
ne = this._northEast, | |
sw2 = bounds.getSouthWest(), | |
ne2 = bounds.getNorthEast(), | |
latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat), | |
lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng); | |
return latIntersects && lngIntersects; | |
}, | |
toBBoxString: function () { | |
return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(','); | |
}, | |
equals: function (bounds) { // (LatLngBounds) | |
if (!bounds) { return false; } | |
bounds = L.latLngBounds(bounds); | |
return this._southWest.equals(bounds.getSouthWest()) && | |
this._northEast.equals(bounds.getNorthEast()); | |
}, | |
isValid: function () { | |
return !!(this._southWest && this._northEast); | |
} | |
}; | |
//TODO International date line? | |
L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng) | |
if (!a || a instanceof L.LatLngBounds) { | |
return a; | |
} | |
return new L.LatLngBounds(a, b); | |
}; | |
/* | |
* L.Projection contains various geographical projections used by CRS classes. | |
*/ | |
L.Projection = {}; | |
/* | |
* Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default. | |
*/ | |
L.Projection.SphericalMercator = { | |
MAX_LATITUDE: 85.0511287798, | |
project: function (latlng) { // (LatLng) -> Point | |
var d = L.LatLng.DEG_TO_RAD, | |
max = this.MAX_LATITUDE, | |
lat = Math.max(Math.min(max, latlng.lat), -max), | |
x = latlng.lng * d, | |
y = lat * d; | |
y = Math.log(Math.tan((Math.PI / 4) + (y / 2))); | |
return new L.Point(x, y); | |
}, | |
unproject: function (point) { // (Point, Boolean) -> LatLng | |
var d = L.LatLng.RAD_TO_DEG, | |
lng = point.x * d, | |
lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d; | |
return new L.LatLng(lat, lng); | |
} | |
}; | |
/* | |
* Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple. | |
*/ | |
L.Projection.LonLat = { | |
project: function (latlng) { | |
return new L.Point(latlng.lng, latlng.lat); | |
}, | |
unproject: function (point) { | |
return new L.LatLng(point.y, point.x); | |
} | |
}; | |
/* | |
* L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet. | |
*/ | |
L.CRS = { | |
latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point | |
var projectedPoint = this.projection.project(latlng), | |
scale = this.scale(zoom); | |
return this.transformation._transform(projectedPoint, scale); | |
}, | |
pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng | |
var scale = this.scale(zoom), | |
untransformedPoint = this.transformation.untransform(point, scale); | |
return this.projection.unproject(untransformedPoint); | |
}, | |
project: function (latlng) { | |
return this.projection.project(latlng); | |
}, | |
scale: function (zoom) { | |
return 256 * Math.pow(2, zoom); | |
}, | |
getSize: function (zoom) { | |
var s = this.scale(zoom); | |
return L.point(s, s); | |
} | |
}; | |
/* | |
* A simple CRS that can be used for flat non-Earth maps like panoramas or game maps. | |
*/ | |
L.CRS.Simple = L.extend({}, L.CRS, { | |
projection: L.Projection.LonLat, | |
transformation: new L.Transformation(1, 0, -1, 0), | |
scale: function (zoom) { | |
return Math.pow(2, zoom); | |
} | |
}); | |
/* | |
* L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping | |
* and is used by Leaflet by default. | |
*/ | |
L.CRS.EPSG3857 = L.extend({}, L.CRS, { | |
code: 'EPSG:3857', | |
projection: L.Projection.SphericalMercator, | |
transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5), | |
project: function (latlng) { // (LatLng) -> Point | |
var projectedPoint = this.projection.project(latlng), | |
earthRadius = 6378137; | |
return projectedPoint.multiplyBy(earthRadius); | |
} | |
}); | |
L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, { | |
code: 'EPSG:900913' | |
}); | |
/* | |
* L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists. | |
*/ | |
L.CRS.EPSG4326 = L.extend({}, L.CRS, { | |
code: 'EPSG:4326', | |
projection: L.Projection.LonLat, | |
transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5) | |
}); | |
/* | |
* L.Map is the central class of the API - it is used to create a map. | |
*/ | |
L.Map = L.Class.extend({ | |
includes: L.Mixin.Events, | |
options: { | |
crs: L.CRS.EPSG3857, | |
/* | |
center: LatLng, | |
zoom: Number, | |
layers: Array, | |
*/ | |
fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23, | |
trackResize: true, | |
markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d | |
}, | |
initialize: function (id, options) { // (HTMLElement or String, Object) | |
options = L.setOptions(this, options); | |
this._initContainer(id); | |
this._initLayout(); | |
// hack for https://github.com/Leaflet/Leaflet/issues/1980 | |
this._onResize = L.bind(this._onResize, this); | |
this._initEvents(); | |
if (options.maxBounds) { | |
this.setMaxBounds(options.maxBounds); | |
} | |
if (options.center && options.zoom !== undefined) { | |
this.setView(L.latLng(options.center), options.zoom, {reset: true}); | |
} | |
this._handlers = []; | |
this._layers = {}; | |
this._zoomBoundLayers = {}; | |
this._tileLayersNum = 0; | |
this.callInitHooks(); | |
this._addLayers(options.layers); | |
}, | |
// public methods that modify map state | |
// replaced by animation-powered implementation in Map.PanAnimation.js | |
setView: function (center, zoom) { | |
zoom = zoom === undefined ? this.getZoom() : zoom; | |
this._resetView(L.latLng(center), this._limitZoom(zoom)); | |
return this; | |
}, | |
setZoom: function (zoom, options) { | |
if (!this._loaded) { | |
this._zoom = this._limitZoom(zoom); | |
return this; | |
} | |
return this.setView(this.getCenter(), zoom, {zoom: options}); | |
}, | |
zoomIn: function (delta, options) { | |
return this.setZoom(this._zoom + (delta || 1), options); | |
}, | |
zoomOut: function (delta, options) { | |
return this.setZoom(this._zoom - (delta || 1), options); | |
}, | |
setZoomAround: function (latlng, zoom, options) { | |
var scale = this.getZoomScale(zoom), | |
viewHalf = this.getSize().divideBy(2), | |
containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng), | |
centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale), | |
newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset)); | |
return this.setView(newCenter, zoom, {zoom: options}); | |
}, | |
fitBounds: function (bounds, options) { | |
options = options || {}; | |
bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds); | |
var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]), | |
paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]), | |
zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)), | |
paddingOffset = paddingBR.subtract(paddingTL).divideBy(2), | |
swPoint = this.project(bounds.getSouthWest(), zoom), | |
nePoint = this.project(bounds.getNorthEast(), zoom), | |
center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom); | |
zoom = options && options.maxZoom ? Math.min(options.maxZoom, zoom) : zoom; | |
return this.setView(center, zoom, options); | |
}, | |
fitWorld: function (options) { | |
return this.fitBounds([[-90, -180], [90, 180]], options); | |
}, | |
panTo: function (center, options) { // (LatLng) | |
return this.setView(center, this._zoom, {pan: options}); | |
}, | |
panBy: function (offset) { // (Point) | |
// replaced with animated panBy in Map.PanAnimation.js | |
this.fire('movestart'); | |
this._rawPanBy(L.point(offset)); | |
this.fire('move'); | |
return this.fire('moveend'); | |
}, | |
setMaxBounds: function (bounds) { | |
bounds = L.latLngBounds(bounds); | |
this.options.maxBounds = bounds; | |
if (!bounds) { | |
return this.off('moveend', this._panInsideMaxBounds, this); | |
} | |
if (this._loaded) { | |
this._panInsideMaxBounds(); | |
} | |
return this.on('moveend', this._panInsideMaxBounds, this); | |
}, | |
panInsideBounds: function (bounds, options) { | |
var center = this.getCenter(), | |
newCenter = this._limitCenter(center, this._zoom, bounds); | |
if (center.equals(newCenter)) { return this; } | |
return this.panTo(newCenter, options); | |
}, | |
addLayer: function (layer) { | |
// TODO method is too big, refactor | |
var id = L.stamp(layer); | |
if (this._layers[id]) { return this; } | |
this._layers[id] = layer; | |
// TODO getMaxZoom, getMinZoom in ILayer (instead of options) | |
if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) { | |
this._zoomBoundLayers[id] = layer; | |
this._updateZoomLevels(); | |
} | |
// TODO looks ugly, refactor!!! | |
if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) { | |
this._tileLayersNum++; | |
this._tileLayersToLoad++; | |
layer.on('load', this._onTileLayerLoad, this); | |
} | |
if (this._loaded) { | |
this._layerAdd(layer); | |
} | |
return this; | |
}, | |
removeLayer: function (layer) { | |
var id = L.stamp(layer); | |
if (!this._layers[id]) { return this; } | |
if (this._loaded) { | |
layer.onRemove(this); | |
} | |
delete this._layers[id]; | |
if (this._loaded) { | |
this.fire('layerremove', {layer: layer}); | |
} | |
if (this._zoomBoundLayers[id]) { | |
delete this._zoomBoundLayers[id]; | |
this._updateZoomLevels(); | |
} | |
// TODO looks ugly, refactor | |
if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) { | |
this._tileLayersNum--; | |
this._tileLayersToLoad--; | |
layer.off('load', this._onTileLayerLoad, this); | |
} | |
return this; | |
}, | |
hasLayer: function (layer) { | |
if (!layer) { return false; } | |
return (L.stamp(layer) in this._layers); | |
}, | |
eachLayer: function (method, context) { | |
for (var i in this._layers) { | |
method.call(context, this._layers[i]); | |
} | |
return this; | |
}, | |
invalidateSize: function (options) { | |
if (!this._loaded) { return this; } | |
options = L.extend({ | |
animate: false, | |
pan: true | |
}, options === true ? {animate: true} : options); | |
var oldSize = this.getSize(); | |
this._sizeChanged = true; | |
this._initialCenter = null; | |
var newSize = this.getSize(), | |
oldCenter = oldSize.divideBy(2).round(), | |
newCenter = newSize.divideBy(2).round(), | |
offset = oldCenter.subtract(newCenter); | |
if (!offset.x && !offset.y) { return this; } | |
if (options.animate && options.pan) { | |
this.panBy(offset); | |
} else { | |
if (options.pan) { | |
this._rawPanBy(offset); | |
} | |
this.fire('move'); | |
if (options.debounceMoveend) { | |
clearTimeout(this._sizeTimer); | |
this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200); | |
} else { | |
this.fire('moveend'); | |
} | |
} | |
return this.fire('resize', { | |
oldSize: oldSize, | |
newSize: newSize | |
}); | |
}, | |
// TODO handler.addTo | |
addHandler: function (name, HandlerClass) { | |
if (!HandlerClass) { return this; } | |
var handler = this[name] = new HandlerClass(this); | |
this._handlers.push(handler); | |
if (this.options[name]) { | |
handler.enable(); | |
} | |
return this; | |
}, | |
remove: function () { | |
if (this._loaded) { | |
this.fire('unload'); | |
} | |
this._initEvents('off'); | |
try { | |
// throws error in IE6-8 | |
delete this._container._leaflet; | |
} catch (e) { | |
this._container._leaflet = undefined; | |
} | |
this._clearPanes(); | |
if (this._clearControlPos) { | |
this._clearControlPos(); | |
} | |
this._clearHandlers(); | |
return this; | |
}, | |
// public methods for getting map state | |
getCenter: function () { // (Boolean) -> LatLng | |
this._checkIfLoaded(); | |
if (this._initialCenter && !this._moved()) { | |
return this._initialCenter; | |
} | |
return this.layerPointToLatLng(this._getCenterLayerPoint()); | |
}, | |
getZoom: function () { | |
return this._zoom; | |
}, | |
getBounds: function () { | |
var bounds = this.getPixelBounds(), | |
sw = this.unproject(bounds.getBottomLeft()), | |
ne = this.unproject(bounds.getTopRight()); | |
return new L.LatLngBounds(sw, ne); | |
}, | |
getMinZoom: function () { | |
return this.options.minZoom === undefined ? | |
(this._layersMinZoom === undefined ? 0 : this._layersMinZoom) : | |
this.options.minZoom; | |
}, | |
getMaxZoom: function () { | |
return this.options.maxZoom === undefined ? | |
(this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) : | |
this.options.maxZoom; | |
}, | |
getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number | |
bounds = L.latLngBounds(bounds); | |
var zoom = this.getMinZoom() - (inside ? 1 : 0), | |
maxZoom = this.getMaxZoom(), | |
size = this.getSize(), | |
nw = bounds.getNorthWest(), | |
se = bounds.getSouthEast(), | |
zoomNotFound = true, | |
boundsSize; | |
padding = L.point(padding || [0, 0]); | |
do { | |
zoom++; | |
boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding); | |
zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y; | |
} while (zoomNotFound && zoom <= maxZoom); | |
if (zoomNotFound && inside) { | |
return null; | |
} | |
return inside ? zoom : zoom - 1; | |
}, | |
getSize: function () { | |
if (!this._size || this._sizeChanged) { | |
this._size = new L.Point( | |
this._container.clientWidth, | |
this._container.clientHeight); | |
this._sizeChanged = false; | |
} | |
return this._size.clone(); | |
}, | |
getPixelBounds: function () { | |
var topLeftPoint = this._getTopLeftPoint(); | |
return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize())); | |
}, | |
getPixelOrigin: function () { | |
this._checkIfLoaded(); | |
return this._initialTopLeftPoint; | |
}, | |
getPanes: function () { | |
return this._panes; | |
}, | |
getContainer: function () { | |
return this._container; | |
}, | |
// TODO replace with universal implementation after refactoring projections | |
getZoomScale: function (toZoom) { | |
var crs = this.options.crs; | |
return crs.scale(toZoom) / crs.scale(this._zoom); | |
}, | |
getScaleZoom: function (scale) { | |
return this._zoom + (Math.log(scale) / Math.LN2); | |
}, | |
// conversion methods | |
project: function (latlng, zoom) { // (LatLng[, Number]) -> Point | |
zoom = zoom === undefined ? this._zoom : zoom; | |
return this.options.crs.latLngToPoint(L.latLng(latlng), zoom); | |
}, | |
unproject: function (point, zoom) { // (Point[, Number]) -> LatLng | |
zoom = zoom === undefined ? this._zoom : zoom; | |
return this.options.crs.pointToLatLng(L.point(point), zoom); | |
}, | |
layerPointToLatLng: function (point) { // (Point) | |
var projectedPoint = L.point(point).add(this.getPixelOrigin()); | |
return this.unproject(projectedPoint); | |
}, | |
latLngToLayerPoint: function (latlng) { // (LatLng) | |
var projectedPoint = this.project(L.latLng(latlng))._round(); | |
return projectedPoint._subtract(this.getPixelOrigin()); | |
}, | |
containerPointToLayerPoint: function (point) { // (Point) | |
return L.point(point).subtract(this._getMapPanePos()); | |
}, | |
layerPointToContainerPoint: function (point) { // (Point) | |
return L.point(point).add(this._getMapPanePos()); | |
}, | |
containerPointToLatLng: function (point) { | |
var layerPoint = this.containerPointToLayerPoint(L.point(point)); | |
return this.layerPointToLatLng(layerPoint); | |
}, | |
latLngToContainerPoint: function (latlng) { | |
return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng))); | |
}, | |
mouseEventToContainerPoint: function (e) { // (MouseEvent) | |
return L.DomEvent.getMousePosition(e, this._container); | |
}, | |
mouseEventToLayerPoint: function (e) { // (MouseEvent) | |
return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e)); | |
}, | |
mouseEventToLatLng: function (e) { // (MouseEvent) | |
return this.layerPointToLatLng(this.mouseEventToLayerPoint(e)); | |
}, | |
// map initialization methods | |
_initContainer: function (id) { | |
var container = this._container = L.DomUtil.get(id); | |
if (!container) { | |
throw new Error('Map container not found.'); | |
} else if (container._leaflet) { | |
throw new Error('Map container is already initialized.'); | |
} | |
container._leaflet = true; | |
}, | |
_initLayout: function () { | |
var container = this._container; | |
L.DomUtil.addClass(container, 'leaflet-container' + | |
(L.Browser.touch ? ' leaflet-touch' : '') + | |
(L.Browser.retina ? ' leaflet-retina' : '') + | |
(L.Browser.ielt9 ? ' leaflet-oldie' : '') + | |
(this.options.fadeAnimation ? ' leaflet-fade-anim' : '')); | |
var position = L.DomUtil.getStyle(container, 'position'); | |
if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') { | |
container.style.position = 'relative'; | |
} | |
this._initPanes(); | |
if (this._initControlPos) { | |
this._initControlPos(); | |
} | |
}, | |
_initPanes: function () { | |
var panes = this._panes = {}; | |
this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container); | |
this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane); | |
panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane); | |
panes.shadowPane = this._createPane('leaflet-shadow-pane'); | |
panes.overlayPane = this._createPane('leaflet-overlay-pane'); | |
panes.markerPane = this._createPane('leaflet-marker-pane'); | |
panes.popupPane = this._createPane('leaflet-popup-pane'); | |
var zoomHide = ' leaflet-zoom-hide'; | |
if (!this.options.markerZoomAnimation) { | |
L.DomUtil.addClass(panes.markerPane, zoomHide); | |
L.DomUtil.addClass(panes.shadowPane, zoomHide); | |
L.DomUtil.addClass(panes.popupPane, zoomHide); | |
} | |
}, | |
_createPane: function (className, container) { | |
return L.DomUtil.create('div', className, container || this._panes.objectsPane); | |
}, | |
_clearPanes: function () { | |
this._container.removeChild(this._mapPane); | |
}, | |
_addLayers: function (layers) { | |
layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : []; | |
for (var i = 0, len = layers.length; i < len; i++) { | |
this.addLayer(layers[i]); | |
} | |
}, | |
// private methods that modify map state | |
_resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) { | |
var zoomChanged = (this._zoom !== zoom); | |
if (!afterZoomAnim) { | |
this.fire('movestart'); | |
if (zoomChanged) { | |
this.fire('zoomstart'); | |
} | |
} | |
this._zoom = zoom; | |
this._initialCenter = center; | |
this._initialTopLeftPoint = this._getNewTopLeftPoint(center); | |
if (!preserveMapOffset) { | |
L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0)); | |
} else { | |
this._initialTopLeftPoint._add(this._getMapPanePos()); | |
} | |
this._tileLayersToLoad = this._tileLayersNum; | |
var loading = !this._loaded; | |
this._loaded = true; | |
this.fire('viewreset', {hard: !preserveMapOffset}); | |
if (loading) { | |
this.fire('load'); | |
this.eachLayer(this._layerAdd, this); | |
} | |
this.fire('move'); | |
if (zoomChanged || afterZoomAnim) { | |
this.fire('zoomend'); | |
} | |
this.fire('moveend', {hard: !preserveMapOffset}); | |
}, | |
_rawPanBy: function (offset) { | |
L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset)); | |
}, | |
_getZoomSpan: function () { | |
return this.getMaxZoom() - this.getMinZoom(); | |
}, | |
_updateZoomLevels: function () { | |
var i, | |
minZoom = Infinity, | |
maxZoom = -Infinity, | |
oldZoomSpan = this._getZoomSpan(); | |
for (i in this._zoomBoundLayers) { | |
var layer = this._zoomBoundLayers[i]; | |
if (!isNaN(layer.options.minZoom)) { | |
minZoom = Math.min(minZoom, layer.options.minZoom); | |
} | |
if (!isNaN(layer.options.maxZoom)) { | |
maxZoom = Math.max(maxZoom, layer.options.maxZoom); | |
} | |
} | |
if (i === undefined) { // we have no tilelayers | |
this._layersMaxZoom = this._layersMinZoom = undefined; | |
} else { | |
this._layersMaxZoom = maxZoom; | |
this._layersMinZoom = minZoom; | |
} | |
if (oldZoomSpan !== this._getZoomSpan()) { | |
this.fire('zoomlevelschange'); | |
} | |
}, | |
_panInsideMaxBounds: function () { | |
this.panInsideBounds(this.options.maxBounds); | |
}, | |
_checkIfLoaded: function () { | |
if (!this._loaded) { | |
throw new Error('Set map center and zoom first.'); | |
} | |
}, | |
// map events | |
_initEvents: function (onOff) { | |
if (!L.DomEvent) { return; } | |
onOff = onOff || 'on'; | |
L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this); | |
var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter', | |
'mouseleave', 'mousemove', 'contextmenu'], | |
i, len; | |
for (i = 0, len = events.length; i < len; i++) { | |
L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this); | |
} | |
if (this.options.trackResize) { | |
L.DomEvent[onOff](window, 'resize', this._onResize, this); | |
} | |
}, | |
_onResize: function () { | |
L.Util.cancelAnimFrame(this._resizeRequest); | |
this._resizeRequest = L.Util.requestAnimFrame( | |
function () { this.invalidateSize({debounceMoveend: true}); }, this, false, this._container); | |
}, | |
_onMouseClick: function (e) { | |
if (!this._loaded || (!e._simulated && | |
((this.dragging && this.dragging.moved()) || | |
(this.boxZoom && this.boxZoom.moved()))) || | |
L.DomEvent._skipped(e)) { return; } | |
this.fire('preclick'); | |
this._fireMouseEvent(e); | |
}, | |
_fireMouseEvent: function (e) { | |
if (!this._loaded || L.DomEvent._skipped(e)) { return; } | |
var type = e.type; | |
type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type)); | |
if (!this.hasEventListeners(type)) { return; } | |
if (type === 'contextmenu') { | |
L.DomEvent.preventDefault(e); | |
} | |
var containerPoint = this.mouseEventToContainerPoint(e), | |
layerPoint = this.containerPointToLayerPoint(containerPoint), | |
latlng = this.layerPointToLatLng(layerPoint); | |
this.fire(type, { | |
latlng: latlng, | |
layerPoint: layerPoint, | |
containerPoint: containerPoint, | |
originalEvent: e | |
}); | |
}, | |
_onTileLayerLoad: function () { | |
this._tileLayersToLoad--; | |
if (this._tileLayersNum && !this._tileLayersToLoad) { | |
this.fire('tilelayersload'); | |
} | |
}, | |
_clearHandlers: function () { | |
for (var i = 0, len = this._handlers.length; i < len; i++) { | |
this._handlers[i].disable(); | |
} | |
}, | |
whenReady: function (callback, context) { | |
if (this._loaded) { | |
callback.call(context || this, this); | |
} else { | |
this.on('load', callback, context); | |
} | |
return this; | |
}, | |
_layerAdd: function (layer) { | |
layer.onAdd(this); | |
this.fire('layeradd', {layer: layer}); | |
}, | |
// private methods for getting map state | |
_getMapPanePos: function () { | |
return L.DomUtil.getPosition(this._mapPane); | |
}, | |
_moved: function () { | |
var pos = this._getMapPanePos(); | |
return pos && !pos.equals([0, 0]); | |
}, | |
_getTopLeftPoint: function () { | |
return this.getPixelOrigin().subtract(this._getMapPanePos()); | |
}, | |
_getNewTopLeftPoint: function (center, zoom) { | |
var viewHalf = this.getSize()._divideBy(2); | |
// TODO round on display, not calculation to increase precision? | |
return this.project(center, zoom)._subtract(viewHalf)._round(); | |
}, | |
_latLngToNewLayerPoint: function (latlng, newZoom, newCenter) { | |
var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos()); | |
return this.project(latlng, newZoom)._subtract(topLeft); | |
}, | |
// layer point of the current center | |
_getCenterLayerPoint: function () { | |
return this.containerPointToLayerPoint(this.getSize()._divideBy(2)); | |
}, | |
// offset of the specified place to the current center in pixels | |
_getCenterOffset: function (latlng) { | |
return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint()); | |
}, | |
// adjust center for view to get inside bounds | |
_limitCenter: function (center, zoom, bounds) { | |
if (!bounds) { return center; } | |
var centerPoint = this.project(center, zoom), | |
viewHalf = this.getSize().divideBy(2), | |
viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)), | |
offset = this._getBoundsOffset(viewBounds, bounds, zoom); | |
return this.unproject(centerPoint.add(offset), zoom); | |
}, | |
// adjust offset for view to get inside bounds | |
_limitOffset: function (offset, bounds) { | |
if (!bounds) { return offset; } | |
var viewBounds = this.getPixelBounds(), | |
newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset)); | |
return offset.add(this._getBoundsOffset(newBounds, bounds)); | |
}, | |
// returns offset needed for pxBounds to get inside maxBounds at a specified zoom | |
_getBoundsOffset: function (pxBounds, maxBounds, zoom) { | |
var nwOffset = this.project(maxBounds.getNorthWest(), zoom).subtract(pxBounds.min), | |
seOffset = this.project(maxBounds.getSouthEast(), zoom).subtract(pxBounds.max), | |
dx = this._rebound(nwOffset.x, -seOffset.x), | |
dy = this._rebound(nwOffset.y, -seOffset.y); | |
return new L.Point(dx, dy); | |
}, | |
_rebound: function (left, right) { | |
return left + right > 0 ? | |
Math.round(left - right) / 2 : | |
Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right)); | |
}, | |
_limitZoom: function (zoom) { | |
var min = this.getMinZoom(), | |
max = this.getMaxZoom(); | |
return Math.max(min, Math.min(max, zoom)); | |
} | |
}); | |
L.map = function (id, options) { | |
return new L.Map(id, options); | |
}; | |
/* | |
* Mercator projection that takes into account that the Earth is not a perfect sphere. | |
* Less popular than spherical mercator; used by projections like EPSG:3395. | |
*/ | |
L.Projection.Mercator = { | |
MAX_LATITUDE: 85.0840591556, | |
R_MINOR: 6356752.314245179, | |
R_MAJOR: 6378137, | |
project: function (latlng) { // (LatLng) -> Point | |
var d = L.LatLng.DEG_TO_RAD, | |
max = this.MAX_LATITUDE, | |
lat = Math.max(Math.min(max, latlng.lat), -max), | |
r = this.R_MAJOR, | |
r2 = this.R_MINOR, | |
x = latlng.lng * d * r, | |
y = lat * d, | |
tmp = r2 / r, | |
eccent = Math.sqrt(1.0 - tmp * tmp), | |
con = eccent * Math.sin(y); | |
con = Math.pow((1 - con) / (1 + con), eccent * 0.5); | |
var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con; | |
y = -r * Math.log(ts); | |
return new L.Point(x, y); | |
}, | |
unproject: function (point) { // (Point, Boolean) -> LatLng | |
var d = L.LatLng.RAD_TO_DEG, | |
r = this.R_MAJOR, | |
r2 = this.R_MINOR, | |
lng = point.x * d / r, | |
tmp = r2 / r, | |
eccent = Math.sqrt(1 - (tmp * tmp)), | |
ts = Math.exp(- point.y / r), | |
phi = (Math.PI / 2) - 2 * Math.atan(ts), | |
numIter = 15, | |
tol = 1e-7, | |
i = numIter, | |
dphi = 0.1, | |
con; | |
while ((Math.abs(dphi) > tol) && (--i > 0)) { | |
con = eccent * Math.sin(phi); | |
dphi = (Math.PI / 2) - 2 * Math.atan(ts * | |
Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi; | |
phi += dphi; | |
} | |
return new L.LatLng(phi * d, lng); | |
} | |
}; | |
L.CRS.EPSG3395 = L.extend({}, L.CRS, { | |
code: 'EPSG:3395', | |
projection: L.Projection.Mercator, | |
transformation: (function () { | |
var m = L.Projection.Mercator, | |
r = m.R_MAJOR, | |
scale = 0.5 / (Math.PI * r); | |
return new L.Transformation(scale, 0.5, -scale, 0.5); | |
}()) | |
}); | |
/* | |
* L.TileLayer is used for standard xyz-numbered tile layers. | |
*/ | |
L.TileLayer = L.Class.extend({ | |
includes: L.Mixin.Events, | |
options: { | |
minZoom: 0, | |
maxZoom: 18, | |
tileSize: 256, | |
subdomains: 'abc', | |
errorTileUrl: '', | |
attribution: '', | |
zoomOffset: 0, | |
opacity: 1, | |
/* | |
maxNativeZoom: null, | |
zIndex: null, | |
tms: false, | |
continuousWorld: false, | |
noWrap: false, | |
zoomReverse: false, | |
detectRetina: false, | |
reuseTiles: false, | |
bounds: false, | |
*/ | |
unloadInvisibleTiles: L.Browser.mobile, | |
updateWhenIdle: L.Browser.mobile | |
}, | |
initialize: function (url, options) { | |
options = L.setOptions(this, options); | |
// detecting retina displays, adjusting tileSize and zoom levels | |
if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) { | |
options.tileSize = Math.floor(options.tileSize / 2); | |
options.zoomOffset++; | |
if (options.minZoom > 0) { | |
options.minZoom--; | |
} | |
this.options.maxZoom--; | |
} | |
if (options.bounds) { | |
options.bounds = L.latLngBounds(options.bounds); | |
} | |
this._url = url; | |
var subdomains = this.options.subdomains; | |
if (typeof subdomains === 'string') { | |
this.options.subdomains = subdomains.split(''); | |
} | |
}, | |
onAdd: function (map) { | |
this._map = map; | |
this._animated = map._zoomAnimated; | |
// create a container div for tiles | |
this._initContainer(); | |
// set up events | |
map.on({ | |
'viewreset': this._reset, | |
'moveend': this._update | |
}, this); | |
if (this._animated) { | |
map.on({ | |
'zoomanim': this._animateZoom, | |
'zoomend': this._endZoomAnim | |
}, this); | |
} | |
if (!this.options.updateWhenIdle) { | |
this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this); | |
map.on('move', this._limitedUpdate, this); | |
} | |
this._reset(); | |
this._update(); | |
}, | |
addTo: function (map) { | |
map.addLayer(this); | |
return this; | |
}, | |
onRemove: function (map) { | |
this._container.parentNode.removeChild(this._container); | |
map.off({ | |
'viewreset': this._reset, | |
'moveend': this._update | |
}, this); | |
if (this._animated) { | |
map.off({ | |
'zoomanim': this._animateZoom, | |
'zoomend': this._endZoomAnim | |
}, this); | |
} | |
if (!this.options.updateWhenIdle) { | |
map.off('move', this._limitedUpdate, this); | |
} | |
this._container = null; | |
this._map = null; | |
}, | |
bringToFront: function () { | |
var pane = this._map._panes.tilePane; | |
if (this._container) { | |
pane.appendChild(this._container); | |
this._setAutoZIndex(pane, Math.max); | |
} | |
return this; | |
}, | |
bringToBack: function () { | |
var pane = this._map._panes.tilePane; | |
if (this._container) { | |
pane.insertBefore(this._container, pane.firstChild); | |
this._setAutoZIndex(pane, Math.min); | |
} | |
return this; | |
}, | |
getAttribution: function () { | |
return this.options.attribution; | |
}, | |
getContainer: function () { | |
return this._container; | |
}, | |
setOpacity: function (opacity) { | |
this.options.opacity = opacity; | |
if (this._map) { | |
this._updateOpacity(); | |
} | |
return this; | |
}, | |
setZIndex: function (zIndex) { | |
this.options.zIndex = zIndex; | |
this._updateZIndex(); | |
return this; | |
}, | |
setUrl: function (url, noRedraw) { | |
this._url = url; | |
if (!noRedraw) { | |
this.redraw(); | |
} | |
return this; | |
}, | |
redraw: function () { | |
if (this._map) { | |
this._reset({hard: true}); | |
this._update(); | |
} | |
return this; | |
}, | |
_updateZIndex: function () { | |
if (this._container && this.options.zIndex !== undefined) { | |
this._container.style.zIndex = this.options.zIndex; | |
} | |
}, | |
_setAutoZIndex: function (pane, compare) { | |
var layers = pane.children, | |
edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min | |
zIndex, i, len; | |
for (i = 0, len = layers.length; i < len; i++) { | |
if (layers[i] !== this._container) { | |
zIndex = parseInt(layers[i].style.zIndex, 10); | |
if (!isNaN(zIndex)) { | |
edgeZIndex = compare(edgeZIndex, zIndex); | |
} | |
} | |
} | |
this.options.zIndex = this._container.style.zIndex = | |
(isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1); | |
}, | |
_updateOpacity: function () { | |
var i, | |
tiles = this._tiles; | |
if (L.Browser.ielt9) { | |
for (i in tiles) { | |
L.DomUtil.setOpacity(tiles[i], this.options.opacity); | |
} | |
} else { | |
L.DomUtil.setOpacity(this._container, this.options.opacity); | |
} | |
}, | |
_initContainer: function () { | |
var tilePane = this._map._panes.tilePane; | |
if (!this._container) { | |
this._container = L.DomUtil.create('div', 'leaflet-layer'); | |
this._updateZIndex(); | |
if (this._animated) { | |
var className = 'leaflet-tile-container'; | |
this._bgBuffer = L.DomUtil.create('div', className, this._container); | |
this._tileContainer = L.DomUtil.create('div', className, this._container); | |
} else { | |
this._tileContainer = this._container; | |
} | |
tilePane.appendChild(this._container); | |
if (this.options.opacity < 1) { | |
this._updateOpacity(); | |
} | |
} | |
}, | |
_reset: function (e) { | |
for (var key in this._tiles) { | |
this.fire('tileunload', {tile: this._tiles[key]}); | |
} | |
this._tiles = {}; | |
this._tilesToLoad = 0; | |
if (this.options.reuseTiles) { | |
this._unusedTiles = []; | |
} | |
this._tileContainer.innerHTML = ''; | |
if (this._animated && e && e.hard) { | |
this._clearBgBuffer(); | |
} | |
this._initContainer(); | |
}, | |
_getTileSize: function () { | |
var map = this._map, | |
zoom = map.getZoom() + this.options.zoomOffset, | |
zoomN = this.options.maxNativeZoom, | |
tileSize = this.options.tileSize; | |
if (zoomN && zoom > zoomN) { | |
tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize); | |
} | |
return tileSize; | |
}, | |
_update: function () { | |
if (!this._map) { return; } | |
var map = this._map, | |
bounds = map.getPixelBounds(), | |
zoom = map.getZoom(), | |
tileSize = this._getTileSize(); | |
if (zoom > this.options.maxZoom || zoom < this.options.minZoom) { | |
return; | |
} | |
var tileBounds = L.bounds( | |
bounds.min.divideBy(tileSize)._floor(), | |
bounds.max.divideBy(tileSize)._floor()); | |
this._addTilesFromCenterOut(tileBounds); | |
if (this.options.unloadInvisibleTiles || this.options.reuseTiles) { | |
this._removeOtherTiles(tileBounds); | |
} | |
}, | |
_addTilesFromCenterOut: function (bounds) { | |
var queue = [], | |
center = bounds.getCenter(); | |
var j, i, point; | |
for (j = bounds.min.y; j <= bounds.max.y; j++) { | |
for (i = bounds.min.x; i <= bounds.max.x; i++) { | |
point = new L.Point(i, j); | |
if (this._tileShouldBeLoaded(point)) { | |
queue.push(point); | |
} | |
} | |
} | |
var tilesToLoad = queue.length; | |
if (tilesToLoad === 0) { return; } | |
// load tiles in order of their distance to center | |
queue.sort(function (a, b) { | |
return a.distanceTo(center) - b.distanceTo(center); | |
}); | |
var fragment = document.createDocumentFragment(); | |
// if its the first batch of tiles to load | |
if (!this._tilesToLoad) { | |
this.fire('loading'); | |
} | |
this._tilesToLoad += tilesToLoad; | |
for (i = 0; i < tilesToLoad; i++) { | |
this._addTile(queue[i], fragment); | |
} | |
this._tileContainer.appendChild(fragment); | |
}, | |
_tileShouldBeLoaded: function (tilePoint) { | |
if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) { | |
return false; // already loaded | |
} | |
var options = this.options; | |
if (!options.continuousWorld) { | |
var limit = this._getWrapTileNum(); | |
// don't load if exceeds world bounds | |
if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) || | |
tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; } | |
} | |
if (options.bounds) { | |
var tileSize = options.tileSize, | |
nwPoint = tilePoint.multiplyBy(tileSize), | |
sePoint = nwPoint.add([tileSize, tileSize]), | |
nw = this._map.unproject(nwPoint), | |
se = this._map.unproject(sePoint); | |
// TODO temporary hack, will be removed after refactoring projections | |
// https://github.com/Leaflet/Leaflet/issues/1618 | |
if (!options.continuousWorld && !options.noWrap) { | |
nw = nw.wrap(); | |
se = se.wrap(); | |
} | |
if (!options.bounds.intersects([nw, se])) { return false; } | |
} | |
return true; | |
}, | |
_removeOtherTiles: function (bounds) { | |
var kArr, x, y, key; | |
for (key in this._tiles) { | |
kArr = key.split(':'); | |
x = parseInt(kArr[0], 10); | |
y = parseInt(kArr[1], 10); | |
// remove tile if it's out of bounds | |
if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) { | |
this._removeTile(key); | |
} | |
} | |
}, | |
_removeTile: function (key) { | |
var tile = this._tiles[key]; | |
this.fire('tileunload', {tile: tile, url: tile.src}); | |
if (this.options.reuseTiles) { | |
L.DomUtil.removeClass(tile, 'leaflet-tile-loaded'); | |
this._unusedTiles.push(tile); | |
} else if (tile.parentNode === this._tileContainer) { | |
this._tileContainer.removeChild(tile); | |
} | |
// for https://github.com/CloudMade/Leaflet/issues/137 | |
if (!L.Browser.android) { | |
tile.onload = null; | |
tile.src = L.Util.emptyImageUrl; | |
} | |
delete this._tiles[key]; | |
}, | |
_addTile: function (tilePoint, container) { | |
var tilePos = this._getTilePos(tilePoint); | |
// get unused tile - or create a new tile | |
var tile = this._getTile(); | |
/* | |
Chrome 20 layouts much faster with top/left (verify with timeline, frames) | |
Android 4 browser has display issues with top/left and requires transform instead | |
(other browsers don't currently care) - see debug/hacks/jitter.html for an example | |
*/ | |
L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome); | |
this._tiles[tilePoint.x + ':' + tilePoint.y] = tile; | |
this._loadTile(tile, tilePoint); | |
if (tile.parentNode !== this._tileContainer) { | |
container.appendChild(tile); | |
} | |
}, | |
_getZoomForUrl: function () { | |
var options = this.options, | |
zoom = this._map.getZoom(); | |
if (options.zoomReverse) { | |
zoom = options.maxZoom - zoom; | |
} | |
zoom += options.zoomOffset; | |
return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom; | |
}, | |
_getTilePos: function (tilePoint) { | |
var origin = this._map.getPixelOrigin(), | |
tileSize = this._getTileSize(); | |
return tilePoint.multiplyBy(tileSize).subtract(origin); | |
}, | |
// image-specific code (override to implement e.g. Canvas or SVG tile layer) | |
getTileUrl: function (tilePoint) { | |
return L.Util.template(this._url, L.extend({ | |
s: this._getSubdomain(tilePoint), | |
z: tilePoint.z, | |
x: tilePoint.x, | |
y: tilePoint.y | |
}, this.options)); | |
}, | |
_getWrapTileNum: function () { | |
var crs = this._map.options.crs, | |
size = crs.getSize(this._map.getZoom()); | |
return size.divideBy(this._getTileSize())._floor(); | |
}, | |
_adjustTilePoint: function (tilePoint) { | |
var limit = this._getWrapTileNum(); | |
// wrap tile coordinates | |
if (!this.options.continuousWorld && !this.options.noWrap) { | |
tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x; | |
} | |
if (this.options.tms) { | |
tilePoint.y = limit.y - tilePoint.y - 1; | |
} | |
tilePoint.z = this._getZoomForUrl(); | |
}, | |
_getSubdomain: function (tilePoint) { | |
var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length; | |
return this.options.subdomains[index]; | |
}, | |
_getTile: function () { | |
if (this.options.reuseTiles && this._unusedTiles.length > 0) { | |
var tile = this._unusedTiles.pop(); | |
this._resetTile(tile); | |
return tile; | |
} | |
return this._createTile(); | |
}, | |
// Override if data stored on a tile needs to be cleaned up before reuse | |
_resetTile: function (/*tile*/) {}, | |
_createTile: function () { | |
var tile = L.DomUtil.create('img', 'leaflet-tile'); | |
tile.style.width = tile.style.height = this._getTileSize() + 'px'; | |
tile.galleryimg = 'no'; | |
tile.onselectstart = tile.onmousemove = L.Util.falseFn; | |
if (L.Browser.ielt9 && this.options.opacity !== undefined) { | |
L.DomUtil.setOpacity(tile, this.options.opacity); | |
} | |
// without this hack, tiles disappear after zoom on Chrome for Android | |
// https://github.com/Leaflet/Leaflet/issues/2078 | |
if (L.Browser.mobileWebkit3d) { | |
tile.style.WebkitBackfaceVisibility = 'hidden'; | |
} | |
return tile; | |
}, | |
_loadTile: function (tile, tilePoint) { | |
tile._layer = this; | |
tile.onload = this._tileOnLoad; | |
tile.onerror = this._tileOnError; | |
this._adjustTilePoint(tilePoint); | |
tile.src = this.getTileUrl(tilePoint); | |
this.fire('tileloadstart', { | |
tile: tile, | |
url: tile.src | |
}); | |
}, | |
_tileLoaded: function () { | |
this._tilesToLoad--; | |
if (this._animated) { | |
L.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated'); | |
} | |
if (!this._tilesToLoad) { | |
this.fire('load'); | |
if (this._animated) { | |
// clear scaled tiles after all new tiles are loaded (for performance) | |
clearTimeout(this._clearBgBufferTimer); | |
this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500); | |
} | |
} | |
}, | |
_tileOnLoad: function () { | |
var layer = this._layer; | |
//Only if we are loading an actual image | |
if (this.src !== L.Util.emptyImageUrl) { | |
L.DomUtil.addClass(this, 'leaflet-tile-loaded'); | |
layer.fire('tileload', { | |
tile: this, | |
url: this.src | |
}); | |
} | |
layer._tileLoaded(); | |
}, | |
_tileOnError: function () { | |
var layer = this._layer; | |
layer.fire('tileerror', { | |
tile: this, | |
url: this.src | |
}); | |
var newUrl = layer.options.errorTileUrl; | |
if (newUrl) { | |
this.src = newUrl; | |
} | |
layer._tileLoaded(); | |
} | |
}); | |
L.tileLayer = function (url, options) { | |
return new L.TileLayer(url, options); | |
}; | |
/* | |
* L.TileLayer.WMS is used for putting WMS tile layers on the map. | |
*/ | |
L.TileLayer.WMS = L.TileLayer.extend({ | |
defaultWmsParams: { | |
service: 'WMS', | |
request: 'GetMap', | |
version: '1.1.1', | |
layers: '', | |
styles: '', | |
format: 'image/jpeg', | |
transparent: false | |
}, | |
initialize: function (url, options) { // (String, Object) | |
this._url = url; | |
var wmsParams = L.extend({}, this.defaultWmsParams), | |
tileSize = options.tileSize || this.options.tileSize; | |
if (options.detectRetina && L.Browser.retina) { | |
wmsParams.width = wmsParams.height = tileSize * 2; | |
} else { | |
wmsParams.width = wmsParams.height = tileSize; | |
} | |
for (var i in options) { | |
// all keys that are not TileLayer options go to WMS params | |
if (!this.options.hasOwnProperty(i) && i !== 'crs') { | |
wmsParams[i] = options[i]; | |
} | |
} | |
this.wmsParams = wmsParams; | |
L.setOptions(this, options); | |
}, | |
onAdd: function (map) { | |
this._crs = this.options.crs || map.options.crs; | |
this._wmsVersion = parseFloat(this.wmsParams.version); | |
var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs'; | |
this.wmsParams[projectionKey] = this._crs.code; | |
L.TileLayer.prototype.onAdd.call(this, map); | |
}, | |
getTileUrl: function (tilePoint) { // (Point, Number) -> String | |
var map = this._map, | |
tileSize = this.options.tileSize, | |
nwPoint = tilePoint.multiplyBy(tileSize), | |
sePoint = nwPoint.add([tileSize, tileSize]), | |
nw = this._crs.project(map.unproject(nwPoint, tilePoint.z)), | |
se = this._crs.project(map.unproject(sePoint, tilePoint.z)), | |
bbox = this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ? | |
[se.y, nw.x, nw.y, se.x].join(',') : | |
[nw.x, se.y, se.x, nw.y].join(','), | |
url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)}); | |
return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox; | |
}, | |
setParams: function (params, noRedraw) { | |
L.extend(this.wmsParams, params); | |
if (!noRedraw) { | |
this.redraw(); | |
} | |
return this; | |
} | |
}); | |
L.tileLayer.wms = function (url, options) { | |
return new L.TileLayer.WMS(url, options); | |
}; | |
/* | |
* L.TileLayer.Canvas is a class that you can use as a base for creating | |
* dynamically drawn Canvas-based tile layers. | |
*/ | |
L.TileLayer.Canvas = L.TileLayer.extend({ | |
options: { | |
async: false | |
}, | |
initialize: function (options) { | |
L.setOptions(this, options); | |
}, | |
redraw: function () { | |
if (this._map) { | |
this._reset({hard: true}); | |
this._update(); | |
} | |
for (var i in this._tiles) { | |
this._redrawTile(this._tiles[i]); | |
} | |
return this; | |
}, | |
_redrawTile: function (tile) { | |
this.drawTile(tile, tile._tilePoint, this._map._zoom); | |
}, | |
_createTile: function () { | |
var tile = L.DomUtil.create('canvas', 'leaflet-tile'); | |
tile.width = tile.height = this.options.tileSize; | |
tile.onselectstart = tile.onmousemove = L.Util.falseFn; | |
return tile; | |
}, | |
_loadTile: function (tile, tilePoint) { | |
tile._layer = this; | |
tile._tilePoint = tilePoint; | |
this._redrawTile(tile); | |
if (!this.options.async) { | |
this.tileDrawn(tile); | |
} | |
}, | |
drawTile: function (/*tile, tilePoint*/) { | |
// override with rendering code | |
}, | |
tileDrawn: function (tile) { | |
this._tileOnLoad.call(tile); | |
} | |
}); | |
L.tileLayer.canvas = function (options) { | |
return new L.TileLayer.Canvas(options); | |
}; | |
/* | |
* L.ImageOverlay is used to overlay images over the map (to specific geographical bounds). | |
*/ | |
L.ImageOverlay = L.Class.extend({ | |
includes: L.Mixin.Events, | |
options: { | |
opacity: 1 | |
}, | |
initialize: function (url, bounds, options) { // (String, LatLngBounds, Object) | |
this._url = url; | |
this._bounds = L.latLngBounds(bounds); | |
L.setOptions(this, options); | |
}, | |
onAdd: function (map) { | |
this._map = map; | |
if (!this._image) { | |
this._initImage(); | |
} | |
map._panes.overlayPane.appendChild(this._image); | |
map.on('viewreset', this._reset, this); | |
if (map.options.zoomAnimation && L.Browser.any3d) { | |
map.on('zoomanim', this._animateZoom, this); | |
} | |
this._reset(); | |
}, | |
onRemove: function (map) { | |
map.getPanes().overlayPane.removeChild(this._image); | |
map.off('viewreset', this._reset, this); | |
if (map.options.zoomAnimation) { | |
map.off('zoomanim', this._animateZoom, this); | |
} | |
}, | |
addTo: function (map) { | |
map.addLayer(this); | |
return this; | |
}, | |
setOpacity: function (opacity) { | |
this.options.opacity = opacity; | |
this._updateOpacity(); | |
return this; | |
}, | |
// TODO remove bringToFront/bringToBack duplication from TileLayer/Path | |
bringToFront: function () { | |
if (this._image) { | |
this._map._panes.overlayPane.appendChild(this._image); | |
} | |
return this; | |
}, | |
bringToBack: function () { | |
var pane = this._map._panes.overlayPane; | |
if (this._image) { | |
pane.insertBefore(this._image, pane.firstChild); | |
} | |
return this; | |
}, | |
setUrl: function (url) { | |
this._url = url; | |
this._image.src = this._url; | |
}, | |
getAttribution: function () { | |
return this.options.attribution; | |
}, | |
_initImage: function () { | |
this._image = L.DomUtil.create('img', 'leaflet-image-layer'); | |
if (this._map.options.zoomAnimation && L.Browser.any3d) { | |
L.DomUtil.addClass(this._image, 'leaflet-zoom-animated'); | |
} else { | |
L.DomUtil.addClass(this._image, 'leaflet-zoom-hide'); | |
} | |
this._updateOpacity(); | |
//TODO createImage util method to remove duplication | |
L.extend(this._image, { | |
galleryimg: 'no', | |
onselectstart: L.Util.falseFn, | |
onmousemove: L.Util.falseFn, | |
onload: L.bind(this._onImageLoad, this), | |
src: this._url | |
}); | |
}, | |
_animateZoom: function (e) { | |
var map = this._map, | |
image = this._image, | |
scale = map.getZoomScale(e.zoom), | |
nw = this._bounds.getNorthWest(), | |
se = this._bounds.getSouthEast(), | |
topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center), | |
size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft), | |
origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale))); | |
image.style[L.DomUtil.TRANSFORM] = | |
L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') '; | |
}, | |
_reset: function () { | |
var image = this._image, | |
topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()), | |
size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft); | |
L.DomUtil.setPosition(image, topLeft); | |
image.style.width = size.x + 'px'; | |
image.style.height = size.y + 'px'; | |
}, | |
_onImageLoad: function () { | |
this.fire('load'); | |
}, | |
_updateOpacity: function () { | |
L.DomUtil.setOpacity(this._image, this.options.opacity); | |
} | |
}); | |
L.imageOverlay = function (url, bounds, options) { | |
return new L.ImageOverlay(url, bounds, options); | |
}; | |
/* | |
* L.Icon is an image-based icon class that you can use with L.Marker for custom markers. | |
*/ | |
L.Icon = L.Class.extend({ | |
options: { | |
/* | |
iconUrl: (String) (required) | |
iconRetinaUrl: (String) (optional, used for retina devices if detected) | |
iconSize: (Point) (can be set through CSS) | |
iconAnchor: (Point) (centered by default, can be set in CSS with negative margins) | |
popupAnchor: (Point) (if not specified, popup opens in the anchor point) | |
shadowUrl: (String) (no shadow by default) | |
shadowRetinaUrl: (String) (optional, used for retina devices if detected) | |
shadowSize: (Point) | |
shadowAnchor: (Point) | |
*/ | |
className: '' | |
}, | |
initialize: function (options) { | |
L.setOptions(this, options); | |
}, | |
createIcon: function (oldIcon) { | |
return this._createIcon('icon', oldIcon); | |
}, | |
createShadow: function (oldIcon) { | |
return this._createIcon('shadow', oldIcon); | |
}, | |
_createIcon: function (name, oldIcon) { | |
var src = this._getIconUrl(name); | |
if (!src) { | |
if (name === 'icon') { | |
throw new Error('iconUrl not set in Icon options (see the docs).'); | |
} | |
return null; | |
} | |
var img; | |
if (!oldIcon || oldIcon.tagName !== 'IMG') { | |
img = this._createImg(src); | |
} else { | |
img = this._createImg(src, oldIcon); | |
} | |
this._setIconStyles(img, name); | |
return img; | |
}, | |
_setIconStyles: function (img, name) { | |
var options = this.options, | |
size = L.point(options[name + 'Size']), | |
anchor; | |
if (name === 'shadow') { | |
anchor = L.point(options.shadowAnchor || options.iconAnchor); | |
} else { | |
anchor = L.point(options.iconAnchor); | |
} | |
if (!anchor && size) { | |
anchor = size.divideBy(2, true); | |
} | |
img.className = 'leaflet-marker-' + name + ' ' + options.className; | |
if (anchor) { | |
img.style.marginLeft = (-anchor.x) + 'px'; | |
img.style.marginTop = (-anchor.y) + 'px'; | |
} | |
if (size) { | |
img.style.width = size.x + 'px'; | |
img.style.height = size.y + 'px'; | |
} | |
}, | |
_createImg: function (src, el) { | |
el = el || document.createElement('img'); | |
el.src = src; | |
return el; | |
}, | |
_getIconUrl: function (name) { | |
if (L.Browser.retina && this.options[name + 'RetinaUrl']) { | |
return this.options[name + 'RetinaUrl']; | |
} | |
return this.options[name + 'Url']; | |
} | |
}); | |
L.icon = function (options) { | |
return new L.Icon(options); | |
}; | |
/* | |
* L.Icon.Default is the blue marker icon used by default in Leaflet. | |
*/ | |
L.Icon.Default = L.Icon.extend({ | |
options: { | |
iconSize: [25, 41], | |
iconAnchor: [12, 41], | |
popupAnchor: [1, -34], | |
shadowSize: [41, 41] | |
}, | |
_getIconUrl: function (name) { | |
var key = name + 'Url'; | |
if (this.options[key]) { | |
return this.options[key]; | |
} | |
if (L.Browser.retina && name === 'icon') { | |
name += '-2x'; | |
} | |
var path = L.Icon.Default.imagePath; | |
if (!path) { | |
throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.'); | |
} | |
return path + '/marker-' + name + '.png'; | |
} | |
}); | |
L.Icon.Default.imagePath = (function () { | |
var scripts = document.getElementsByTagName('script'), | |
leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/; | |
var i, len, src, matches, path; | |
for (i = 0, len = scripts.length; i < len; i++) { | |
src = scripts[i].src; | |
matches = src.match(leafletRe); | |
if (matches) { | |
path = src.split(leafletRe)[0]; | |
return (path ? path + '/' : '') + 'images'; | |
} | |
} | |
}()); | |
/* | |
* L.Marker is used to display clickable/draggable icons on the map. | |
*/ | |
L.Marker = L.Class.extend({ | |
includes: L.Mixin.Events, | |
options: { | |
icon: new L.Icon.Default(), | |
title: '', | |
alt: '', | |
clickable: true, | |
draggable: false, | |
keyboard: true, | |
zIndexOffset: 0, | |
opacity: 1, | |
riseOnHover: false, | |
riseOffset: 250 | |
}, | |
initialize: function (latlng, options) { | |
L.setOptions(this, options); | |
this._latlng = L.latLng(latlng); | |
}, | |
onAdd: function (map) { | |
this._map = map; | |
map.on('viewreset', this.update, this); | |
this._initIcon(); | |
this.update(); | |
this.fire('add'); | |
if (map.options.zoomAnimation && map.options.markerZoomAnimation) { | |
map.on('zoomanim', this._animateZoom, this); | |
} | |
}, | |
addTo: function (map) { | |
map.addLayer(this); | |
return this; | |
}, | |
onRemove: function (map) { | |
if (this.dragging) { | |
this.dragging.disable(); | |
} | |
this._removeIcon(); | |
this._removeShadow(); | |
this.fire('remove'); | |
map.off({ | |
'viewreset': this.update, | |
'zoomanim': this._animateZoom | |
}, this); | |
this._map = null; | |
}, | |
getLatLng: function () { | |
return this._latlng; | |
}, | |
setLatLng: function (latlng) { | |
this._latlng = L.latLng(latlng); | |
this.update(); | |
return this.fire('move', { latlng: this._latlng }); | |
}, | |
setZIndexOffset: function (offset) { | |
this.options.zIndexOffset = offset; | |
this.update(); | |
return this; | |
}, | |
setIcon: function (icon) { | |
this.options.icon = icon; | |
if (this._map) { | |
this._initIcon(); | |
this.update(); | |
} | |
if (this._popup) { | |
this.bindPopup(this._popup); | |
} | |
return this; | |
}, | |
update: function () { | |
if (this._icon) { | |
var pos = this._map.latLngToLayerPoint(this._latlng).round(); | |
this._setPos(pos); | |
} | |
return this; | |
}, | |
_initIcon: function () { | |
var options = this.options, | |
map = this._map, | |
animation = (map.options.zoomAnimation && map.options.markerZoomAnimation), | |
classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide'; | |
var icon = options.icon.createIcon(this._icon), | |
addIcon = false; | |
// if we're not reusing the icon, remove the old one and init new one | |
if (icon !== this._icon) { | |
if (this._icon) { | |
this._removeIcon(); | |
} | |
addIcon = true; | |
if (options.title) { | |
icon.title = options.title; | |
} | |
if (options.alt) { | |
icon.alt = options.alt; | |
} | |
} | |
L.DomUtil.addClass(icon, classToAdd); | |
if (options.keyboard) { | |
icon.tabIndex = '0'; | |
} | |
this._icon = icon; | |
this._initInteraction(); | |
if (options.riseOnHover) { | |
L.DomEvent | |
.on(icon, 'mouseover', this._bringToFront, this) | |
.on(icon, 'mouseout', this._resetZIndex, this); | |
} | |
var newShadow = options.icon.createShadow(this._shadow), | |
addShadow = false; | |
if (newShadow !== this._shadow) { | |
this._removeShadow(); | |
addShadow = true; | |
} | |
if (newShadow) { | |
L.DomUtil.addClass(newShadow, classToAdd); | |
} | |
this._shadow = newShadow; | |
if (options.opacity < 1) { | |
this._updateOpacity(); | |
} | |
var panes = this._map._panes; | |
if (addIcon) { | |
panes.markerPane.appendChild(this._icon); | |
} | |
if (newShadow && addShadow) { | |
panes.shadowPane.appendChild(this._shadow); | |
} | |
}, | |
_removeIcon: function () { | |
if (this.options.riseOnHover) { | |
L.DomEvent | |
.off(this._icon, 'mouseover', this._bringToFront) | |
.off(this._icon, 'mouseout', this._resetZIndex); | |
} | |
this._map._panes.markerPane.removeChild(this._icon); | |
this._icon = null; | |
}, | |
_removeShadow: function () { | |
if (this._shadow) { | |
this._map._panes.shadowPane.removeChild(this._shadow); | |
} | |
this._shadow = null; | |
}, | |
_setPos: function (pos) { | |
L.DomUtil.setPosition(this._icon, pos); | |
if (this._shadow) { | |
L.DomUtil.setPosition(this._shadow, pos); | |
} | |
this._zIndex = pos.y + this.options.zIndexOffset; | |
this._resetZIndex(); | |
}, | |
_updateZIndex: function (offset) { | |
this._icon.style.zIndex = this._zIndex + offset; | |
}, | |
_animateZoom: function (opt) { | |
var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round(); | |
this._setPos(pos); | |
}, | |
_initInteraction: function () { | |
if (!this.options.clickable) { return; } | |
// TODO refactor into something shared with Map/Path/etc. to DRY it up | |
var icon = this._icon, | |
events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu']; | |
L.DomUtil.addClass(icon, 'leaflet-clickable'); | |
L.DomEvent.on(icon, 'click', this._onMouseClick, this); | |
L.DomEvent.on(icon, 'keypress', this._onKeyPress, this); | |
for (var i = 0; i < events.length; i++) { | |
L.DomEvent.on(icon, events[i], this._fireMouseEvent, this); | |
} | |
if (L.Handler.MarkerDrag) { | |
this.dragging = new L.Handler.MarkerDrag(this); | |
if (this.options.draggable) { | |
this.dragging.enable(); | |
} | |
} | |
}, | |
_onMouseClick: function (e) { | |
var wasDragged = this.dragging && this.dragging.moved(); | |
if (this.hasEventListeners(e.type) || wasDragged) { | |
L.DomEvent.stopPropagation(e); | |
} | |
if (wasDragged) { return; } | |
if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; } | |
this.fire(e.type, { | |
originalEvent: e, | |
latlng: this._latlng | |
}); | |
}, | |
_onKeyPress: function (e) { | |
if (e.keyCode === 13) { | |
this.fire('click', { | |
originalEvent: e, | |
latlng: this._latlng | |
}); | |
} | |
}, | |
_fireMouseEvent: function (e) { | |
this.fire(e.type, { | |
originalEvent: e, | |
latlng: this._latlng | |
}); | |
// TODO proper custom event propagation | |
// this line will always be called if marker is in a FeatureGroup | |
if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) { | |
L.DomEvent.preventDefault(e); | |
} | |
if (e.type !== 'mousedown') { | |
L.DomEvent.stopPropagation(e); | |
} else { | |
L.DomEvent.preventDefault(e); | |
} | |
}, | |
setOpacity: function (opacity) { | |
this.options.opacity = opacity; | |
if (this._map) { | |
this._updateOpacity(); | |
} | |
return this; | |
}, | |
_updateOpacity: function () { | |
L.DomUtil.setOpacity(this._icon, this.options.opacity); | |
if (this._shadow) { | |
L.DomUtil.setOpacity(this._shadow, this.options.opacity); | |
} | |
}, | |
_bringToFront: function () { | |
this._updateZIndex(this.options.riseOffset); | |
}, | |
_resetZIndex: function () { | |
this._updateZIndex(0); | |
} | |
}); | |
L.marker = function (latlng, options) { | |
return new L.Marker(latlng, options); | |
}; | |
/* | |
* L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon) | |
* to use with L.Marker. | |
*/ | |
L.DivIcon = L.Icon.extend({ | |
options: { | |
iconSize: [12, 12], // also can be set through CSS | |
/* | |
iconAnchor: (Point) | |
popupAnchor: (Point) | |
html: (String) | |
bgPos: (Point) | |
*/ | |
className: 'leaflet-div-icon', | |
html: false | |
}, | |
createIcon: function (oldIcon) { | |
var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'), | |
options = this.options; | |
if (options.html !== false) { | |
div.innerHTML = options.html; | |
} else { | |
div.innerHTML = ''; | |
} | |
if (options.bgPos) { | |
div.style.backgroundPosition = | |
(-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px'; | |
} | |
this._setIconStyles(div, 'icon'); | |
return div; | |
}, | |
createShadow: function () { | |
return null; | |
} | |
}); | |
L.divIcon = function (options) { | |
return new L.DivIcon(options); | |
}; | |
/* | |
* L.Popup is used for displaying popups on the map. | |
*/ | |
L.Map.mergeOptions({ | |
closePopupOnClick: true | |
}); | |
L.Popup = L.Class.extend({ | |
includes: L.Mixin.Events, | |
options: { | |
minWidth: 50, | |
maxWidth: 300, | |
// maxHeight: null, | |
autoPan: true, | |
closeButton: true, | |
offset: [0, 7], | |
autoPanPadding: [5, 5], | |
// autoPanPaddingTopLeft: null, | |
// autoPanPaddingBottomRight: null, | |
keepInView: false, | |
className: '', | |
zoomAnimation: true | |
}, | |
initialize: function (options, source) { | |
L.setOptions(this, options); | |
this._source = source; | |
this._animated = L.Browser.any3d && this.options.zoomAnimation; | |
this._isOpen = false; | |
}, | |
onAdd: function (map) { | |
this._map = map; | |
if (!this._container) { | |
this._initLayout(); | |
} | |
var animFade = map.options.fadeAnimation; | |
if (animFade) { | |
L.DomUtil.setOpacity(this._container, 0); | |
} | |
map._panes.popupPane.appendChild(this._container); | |
map.on(this._getEvents(), this); | |
this.update(); | |
if (animFade) { | |
L.DomUtil.setOpacity(this._container, 1); | |
} | |
this.fire('open'); | |
map.fire('popupopen', {popup: this}); | |
if (this._source) { | |
this._source.fire('popupopen', {popup: this}); | |
} | |
}, | |
addTo: function (map) { | |
map.addLayer(this); | |
return this; | |
}, | |
openOn: function (map) { | |
map.openPopup(this); | |
return this; | |
}, | |
onRemove: function (map) { | |
map._panes.popupPane.removeChild(this._container); | |
L.Util.falseFn(this._container.offsetWidth); // force reflow | |
map.off(this._getEvents(), this); | |
if (map.options.fadeAnimation) { | |
L.DomUtil.setOpacity(this._container, 0); | |
} | |
this._map = null; | |
this.fire('close'); | |
map.fire('popupclose', {popup: this}); | |
if (this._source) { | |
this._source.fire('popupclose', {popup: this}); | |
} | |
}, | |
getLatLng: function () { | |
return this._latlng; | |
}, | |
setLatLng: function (latlng) { | |
this._latlng = L.latLng(latlng); | |
if (this._map) { | |
this._updatePosition(); | |
this._adjustPan(); | |
} | |
return this; | |
}, | |
getContent: function () { | |
return this._content; | |
}, | |
setContent: function (content) { | |
this._content = content; | |
this.update(); | |
return this; | |
}, | |
update: function () { | |
if (!this._map) { return; } | |
this._container.style.visibility = 'hidden'; | |
this._updateContent(); | |
this._updateLayout(); | |
this._updatePosition(); | |
this._container.style.visibility = ''; | |
this._adjustPan(); | |
}, | |
_getEvents: function () { | |
var events = { | |
viewreset: this._updatePosition | |
}; | |
if (this._animated) { | |
events.zoomanim = this._zoomAnimation; | |
} | |
if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) { | |
events.preclick = this._close; | |
} | |
if (this.options.keepInView) { | |
events.moveend = this._adjustPan; | |
} | |
return events; | |
}, | |
_close: function () { | |
if (this._map) { | |
this._map.closePopup(this); | |
} | |
}, | |
_initLayout: function () { | |
var prefix = 'leaflet-popup', | |
containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' + | |
(this._animated ? 'animated' : 'hide'), | |
container = this._container = L.DomUtil.create('div', containerClass), | |
closeButton; | |
if (this.options.closeButton) { | |
closeButton = this._closeButton = | |
L.DomUtil.create('a', prefix + '-close-button', container); | |
closeButton.href = '#close'; | |
closeButton.innerHTML = '×'; | |
L.DomEvent.disableClickPropagation(closeButton); | |
L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this); | |
} | |
var wrapper = this._wrapper = | |
L.DomUtil.create('div', prefix + '-content-wrapper', container); | |
L.DomEvent.disableClickPropagation(wrapper); | |
this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper); | |
L.DomEvent.disableScrollPropagation(this._contentNode); | |
L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation); | |
this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container); | |
this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer); | |
}, | |
_updateContent: function () { | |
if (!this._content) { return; } | |
if (typeof this._content === 'string') { | |
this._contentNode.innerHTML = this._content; | |
} else { | |
while (this._contentNode.hasChildNodes()) { | |
this._contentNode.removeChild(this._contentNode.firstChild); | |
} | |
this._contentNode.appendChild(this._content); | |
} | |
this.fire('contentupdate'); | |
}, | |
_updateLayout: function () { | |
var container = this._contentNode, | |
style = container.style; | |
style.width = ''; | |
style.whiteSpace = 'nowrap'; | |
var width = container.offsetWidth; | |
width = Math.min(width, this.options.maxWidth); | |
width = Math.max(width, this.options.minWidth); | |
style.width = (width + 1) + 'px'; | |
style.whiteSpace = ''; | |
style.height = ''; | |
var height = container.offsetHeight, | |
maxHeight = this.options.maxHeight, | |
scrolledClass = 'leaflet-popup-scrolled'; | |
if (maxHeight && height > maxHeight) { | |
style.height = maxHeight + 'px'; | |
L.DomUtil.addClass(container, scrolledClass); | |
} else { | |
L.DomUtil.removeClass(container, scrolledClass); | |
} | |
this._containerWidth = this._container.offsetWidth; | |
}, | |
_updatePosition: function () { | |
if (!this._map) { return; } | |
var pos = this._map.latLngToLayerPoint(this._latlng), | |
animated = this._animated, | |
offset = L.point(this.options.offset); | |
if (animated) { | |
L.DomUtil.setPosition(this._container, pos); | |
} | |
this._containerBottom = -offset.y - (animated ? 0 : pos.y); | |
this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x); | |
// bottom position the popup in case the height of the popup changes (images loading etc) | |
this._container.style.bottom = this._containerBottom + 'px'; | |
this._container.style.left = this._containerLeft + 'px'; | |
}, | |
_zoomAnimation: function (opt) { | |
var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center); | |
L.DomUtil.setPosition(this._container, pos); | |
}, | |
_adjustPan: function () { | |
if (!this.options.autoPan) { return; } | |
var map = this._map, | |
containerHeight = this._container.offsetHeight, | |
containerWidth = this._containerWidth, | |
layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom); | |
if (this._animated) { | |
layerPos._add(L.DomUtil.getPosition(this._container)); | |
} | |
var containerPos = map.layerPointToContainerPoint(layerPos), | |
padding = L.point(this.options.autoPanPadding), | |
paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding), | |
paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding), | |
size = map.getSize(), | |
dx = 0, | |
dy = 0; | |
if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right | |
dx = containerPos.x + containerWidth - size.x + paddingBR.x; | |
} | |
if (containerPos.x - dx - paddingTL.x < 0) { // left | |
dx = containerPos.x - paddingTL.x; | |
} | |
if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom | |
dy = containerPos.y + containerHeight - size.y + paddingBR.y; | |
} | |
if (containerPos.y - dy - paddingTL.y < 0) { // top | |
dy = containerPos.y - paddingTL.y; | |
} | |
if (dx || dy) { | |
map | |
.fire('autopanstart') | |
.panBy([dx, dy]); | |
} | |
}, | |
_onCloseButtonClick: function (e) { | |
this._close(); | |
L.DomEvent.stop(e); | |
} | |
}); | |
L.popup = function (options, source) { | |
return new L.Popup(options, source); | |
}; | |
L.Map.include({ | |
openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object]) | |
this.closePopup(); | |
if (!(popup instanceof L.Popup)) { | |
var content = popup; | |
popup = new L.Popup(options) | |
.setLatLng(latlng) | |
.setContent(content); | |
} | |
popup._isOpen = true; | |
this._popup = popup; | |
return this.addLayer(popup); | |
}, | |
closePopup: function (popup) { | |
if (!popup || popup === this._popup) { | |
popup = this._popup; | |
this._popup = null; | |
} | |
if (popup) { | |
this.removeLayer(popup); | |
popup._isOpen = false; | |
} | |
return this; | |
} | |
}); | |
/* | |
* Popup extension to L.Marker, adding popup-related methods. | |
*/ | |
L.Marker.include({ | |
openPopup: function () { | |
if (this._popup && this._map && !this._map.hasLayer(this._popup)) { | |
this._popup.setLatLng(this._latlng); | |
this._map.openPopup(this._popup); | |
} | |
return this; | |
}, | |
closePopup: function () { | |
if (this._popup) { | |
this._popup._close(); | |
} | |
return this; | |
}, | |
togglePopup: function () { | |
if (this._popup) { | |
if (this._popup._isOpen) { | |
this.closePopup(); | |
} else { | |
this.openPopup(); | |
} | |
} | |
return this; | |
}, | |
bindPopup: function (content, options) { | |
var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]); | |
anchor = anchor.add(L.Popup.prototype.options.offset); | |
if (options && options.offset) { | |
anchor = anchor.add(options.offset); | |
} | |
options = L.extend({offset: anchor}, options); | |
if (!this._popupHandlersAdded) { | |
this | |
.on('click', this.togglePopup, this) | |
.on('remove', this.closePopup, this) | |
.on('move', this._movePopup, this); | |
this._popupHandlersAdded = true; | |
} | |
if (content instanceof L.Popup) { | |
L.setOptions(content, options); | |
this._popup = content; | |
} else { | |
this._popup = new L.Popup(options, this) | |
.setContent(content); | |
} | |
return this; | |
}, | |
setPopupContent: function (content) { | |
if (this._popup) { | |
this._popup.setContent(content); | |
} | |
return this; | |
}, | |
unbindPopup: function () { | |
if (this._popup) { | |
this._popup = null; | |
this | |
.off('click', this.togglePopup, this) | |
.off('remove', this.closePopup, this) | |
.off('move', this._movePopup, this); | |
this._popupHandlersAdded = false; | |
} | |
return this; | |
}, | |
getPopup: function () { | |
return this._popup; | |
}, | |
_movePopup: function (e) { | |
this._popup.setLatLng(e.latlng); | |
} | |
}); | |
/* | |
* L.LayerGroup is a class to combine several layers into one so that | |
* you can manipulate the group (e.g. add/remove it) as one layer. | |
*/ | |
L.LayerGroup = L.Class.extend({ | |
initialize: function (layers) { | |
this._layers = {}; | |
var i, len; | |
if (layers) { | |
for (i = 0, len = layers.length; i < len; i++) { | |
this.addLayer(layers[i]); | |
} | |
} | |
}, | |
addLayer: function (layer) { | |
var id = this.getLayerId(layer); | |
this._layers[id] = layer; | |
if (this._map) { | |
this._map.addLayer(layer); | |
} | |
return this; | |
}, | |
removeLayer: function (layer) { | |
var id = layer in this._layers ? layer : this.getLayerId(layer); | |
if (this._map && this._layers[id]) { | |
this._map.removeLayer(this._layers[id]); | |
} | |
delete this._layers[id]; | |
return this; | |
}, | |
hasLayer: function (layer) { | |
if (!layer) { return false; } | |
return (layer in this._layers || this.getLayerId(layer) in this._layers); | |
}, | |
clearLayers: function () { | |
this.eachLayer(this.removeLayer, this); | |
return this; | |
}, | |
invoke: function (methodName) { | |
var args = Array.prototype.slice.call(arguments, 1), | |
i, layer; | |
for (i in this._layers) { | |
layer = this._layers[i]; | |
if (layer[methodName]) { | |
layer[methodName].apply(layer, args); | |
} | |
} | |
return this; | |
}, | |
onAdd: function (map) { | |
this._map = map; | |
this.eachLayer(map.addLayer, map); | |
}, | |
onRemove: function (map) { | |
this.eachLayer(map.removeLayer, map); | |
this._map = null; | |
}, | |
addTo: function (map) { | |
map.addLayer(this); | |
return this; | |
}, | |
eachLayer: function (method, context) { | |
for (var i in this._layers) { | |
method.call(context, this._layers[i]); | |
} | |
return this; | |
}, | |
getLayer: function (id) { | |
return this._layers[id]; | |
}, | |
getLayers: function () { | |
var layers = []; | |
for (var i in this._layers) { | |
layers.push(this._layers[i]); | |
} | |
return layers; | |
}, | |
setZIndex: function (zIndex) { | |
return this.invoke('setZIndex', zIndex); | |
}, | |
getLayerId: function (layer) { | |
return L.stamp(layer); | |
} | |
}); | |
L.layerGroup = function (layers) { | |
return new L.LayerGroup(layers); | |
}; | |
/* | |
* L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods | |
* shared between a group of interactive layers (like vectors or markers). | |
*/ | |
L.FeatureGroup = L.LayerGroup.extend({ | |
includes: L.Mixin.Events, | |
statics: { | |
EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose' | |
}, | |
addLayer: function (layer) { | |
if (this.hasLayer(layer)) { | |
return this; | |
} | |
if ('on' in layer) { | |
layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this); | |
} | |
L.LayerGroup.prototype.addLayer.call(this, layer); | |
if (this._popupContent && layer.bindPopup) { | |
layer.bindPopup(this._popupContent, this._popupOptions); | |
} | |
return this.fire('layeradd', {layer: layer}); | |
}, | |
removeLayer: function (layer) { | |
if (!this.hasLayer(layer)) { | |
return this; | |
} | |
if (layer in this._layers) { | |
layer = this._layers[layer]; | |
} | |
layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this); | |
L.LayerGroup.prototype.removeLayer.call(this, layer); | |
if (this._popupContent) { | |
this.invoke('unbindPopup'); | |
} | |
return this.fire('layerremove', {layer: layer}); | |
}, | |
bindPopup: function (content, options) { | |
this._popupContent = content; | |
this._popupOptions = options; | |
return this.invoke('bindPopup', content, options); | |
}, | |
openPopup: function (latlng) { | |
// open popup on the first layer | |
for (var id in this._layers) { | |
this._layers[id].openPopup(latlng); | |
break; | |
} | |
return this; | |
}, | |
setStyle: function (style) { | |
return this.invoke('setStyle', style); | |
}, | |
bringToFront: function () { | |
return this.invoke('bringToFront'); | |
}, | |
bringToBack: function () { | |
return this.invoke('bringToBack'); | |
}, | |
getBounds: function () { | |
var bounds = new L.LatLngBounds(); | |
this.eachLayer(function (layer) { | |
bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds()); | |
}); | |
return bounds; | |
}, | |
_propagateEvent: function (e) { | |
e = L.extend({ | |
layer: e.target, | |
target: this | |
}, e); | |
this.fire(e.type, e); | |
} | |
}); | |
L.featureGroup = function (layers) { | |
return new L.FeatureGroup(layers); | |
}; | |
/* | |
* L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc. | |
*/ | |
L.Path = L.Class.extend({ | |
includes: [L.Mixin.Events], | |
statics: { | |
// how much to extend the clip area around the map view | |
// (relative to its size, e.g. 0.5 is half the screen in each direction) | |
// set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is) | |
CLIP_PADDING: (function () { | |
var max = L.Browser.mobile ? 1280 : 2000, | |
target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2; | |
return Math.max(0, Math.min(0.5, target)); | |
})() | |
}, | |
options: { | |
stroke: true, | |
color: '#0033ff', | |
dashArray: null, | |
lineCap: null, | |
lineJoin: null, | |
weight: 5, | |
opacity: 0.5, | |
fill: false, | |
fillColor: null, //same as color by default | |
fillOpacity: 0.2, | |
clickable: true | |
}, | |
initialize: function (options) { | |
L.setOptions(this, options); | |
}, | |
onAdd: function (map) { | |
this._map = map; | |
if (!this._container) { | |
this._initElements(); | |
this._initEvents(); | |
} | |
this.projectLatlngs(); | |
this._updatePath(); | |
if (this._container) { | |
this._map._pathRoot.appendChild(this._container); | |
} | |
this.fire('add'); | |
map.on({ | |
'viewreset': this.projectLatlngs, | |
'moveend': this._updatePath | |
}, this); | |
}, | |
addTo: function (map) { | |
map.addLayer(this); | |
return this; | |
}, | |
onRemove: function (map) { | |
map._pathRoot.removeChild(this._container); | |
// Need to fire remove event before we set _map to null as the event hooks might need the object | |
this.fire('remove'); | |
this._map = null; | |
if (L.Browser.vml) { | |
this._container = null; | |
this._stroke = null; | |
this._fill = null; | |
} | |
map.off({ | |
'viewreset': this.projectLatlngs, | |
'moveend': this._updatePath | |
}, this); | |
}, | |
projectLatlngs: function () { | |
// do all projection stuff here | |
}, | |
setStyle: function (style) { | |
L.setOptions(this, style); | |
if (this._container) { | |
this._updateStyle(); | |
} | |
return this; | |
}, | |
redraw: function () { | |
if (this._map) { | |
this.projectLatlngs(); | |
this._updatePath(); | |
} | |
return this; | |
} | |
}); | |
L.Map.include({ | |
_updatePathViewport: function () { | |
var p = L.Path.CLIP_PADDING, | |
size = this.getSize(), | |
panePos = L.DomUtil.getPosition(this._mapPane), | |
min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()), | |
max = min.add(size.multiplyBy(1 + p * 2)._round()); | |
this._pathViewport = new L.Bounds(min, max); | |
} | |
}); | |
/* | |
* Extends L.Path with SVG-specific rendering code. | |
*/ | |
L.Path.SVG_NS = 'http://www.w3.org/2000/svg'; | |
L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect); | |
L.Path = L.Path.extend({ | |
statics: { | |
SVG: L.Browser.svg | |
}, | |
bringToFront: function () { | |
var root = this._map._pathRoot, | |
path = this._container; | |
if (path && root.lastChild !== path) { | |
root.appendChild(path); | |
} | |
return this; | |
}, | |
bringToBack: function () { | |
var root = this._map._pathRoot, | |
path = this._container, | |
first = root.firstChild; | |
if (path && first !== path) { | |
root.insertBefore(path, first); | |
} | |
return this; | |
}, | |
getPathString: function () { | |
// form path string here | |
}, | |
_createElement: function (name) { | |
return document.createElementNS(L.Path.SVG_NS, name); | |
}, | |
_initElements: function () { | |
this._map._initPathRoot(); | |
this._initPath(); | |
this._initStyle(); | |
}, | |
_initPath: function () { | |
this._container = this._createElement('g'); | |
this._path = this._createElement('path'); | |
if (this.options.className) { | |
L.DomUtil.addClass(this._path, this.options.className); | |
} | |
this._container.appendChild(this._path); | |
}, | |
_initStyle: function () { | |
if (this.options.stroke) { | |
this._path.setAttribute('stroke-linejoin', 'round'); | |
this._path.setAttribute('stroke-linecap', 'round'); | |
} | |
if (this.options.fill) { | |
this._path.setAttribute('fill-rule', 'evenodd'); | |
} | |
if (this.options.pointerEvents) { | |
this._path.setAttribute('pointer-events', this.options.pointerEvents); | |
} | |
if (!this.options.clickable && !this.options.pointerEvents) { | |
this._path.setAttribute('pointer-events', 'none'); | |
} | |
this._updateStyle(); | |
}, | |
_updateStyle: function () { | |
if (this.options.stroke) { | |
this._path.setAttribute('stroke', this.options.color); | |
this._path.setAttribute('stroke-opacity', this.options.opacity); | |
this._path.setAttribute('stroke-width', this.options.weight); | |
if (this.options.dashArray) { | |
this._path.setAttribute('stroke-dasharray', this.options.dashArray); | |
} else { | |
this._path.removeAttribute('stroke-dasharray'); | |
} | |
if (this.options.lineCap) { | |
this._path.setAttribute('stroke-linecap', this.options.lineCap); | |
} | |
if (this.options.lineJoin) { | |
this._path.setAttribute('stroke-linejoin', this.options.lineJoin); | |
} | |
} else { | |
this._path.setAttribute('stroke', 'none'); | |
} | |
if (this.options.fill) { | |
this._path.setAttribute('fill', this.options.fillColor || this.options.color); | |
this._path.setAttribute('fill-opacity', this.options.fillOpacity); | |
} else { | |
this._path.setAttribute('fill', 'none'); | |
} | |
}, | |
_updatePath: function () { | |
var str = this.getPathString(); | |
if (!str) { | |
// fix webkit empty string parsing bug | |
str = 'M0 0'; | |
} | |
this._path.setAttribute('d', str); | |
}, | |
// TODO remove duplication with L.Map | |
_initEvents: function () { | |
if (this.options.clickable) { | |
if (L.Browser.svg || !L.Browser.vml) { | |
L.DomUtil.addClass(this._path, 'leaflet-clickable'); | |
} | |
L.DomEvent.on(this._container, 'click', this._onMouseClick, this); | |
var events = ['dblclick', 'mousedown', 'mouseover', | |
'mouseout', 'mousemove', 'contextmenu']; | |
for (var i = 0; i < events.length; i++) { | |
L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this); | |
} | |
} | |
}, | |
_onMouseClick: function (e) { | |
if (this._map.dragging && this._map.dragging.moved()) { return; } | |
this._fireMouseEvent(e); | |
}, | |
_fireMouseEvent: function (e) { | |
if (!this.hasEventListeners(e.type)) { return; } | |
var map = this._map, | |
containerPoint = map.mouseEventToContainerPoint(e), | |
layerPoint = map.containerPointToLayerPoint(containerPoint), | |
latlng = map.layerPointToLatLng(layerPoint); | |
this.fire(e.type, { | |
latlng: latlng, | |
layerPoint: layerPoint, | |
containerPoint: containerPoint, | |
originalEvent: e | |
}); | |
if (e.type === 'contextmenu') { | |
L.DomEvent.preventDefault(e); | |
} | |
if (e.type !== 'mousemove') { | |
L.DomEvent.stopPropagation(e); | |
} | |
} | |
}); | |
L.Map.include({ | |
_initPathRoot: function () { | |
if (!this._pathRoot) { | |
this._pathRoot = L.Path.prototype._createElement('svg'); | |
this._panes.overlayPane.appendChild(this._pathRoot); | |
if (this.options.zoomAnimation && L.Browser.any3d) { | |
L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-animated'); | |
this.on({ | |
'zoomanim': this._animatePathZoom, | |
'zoomend': this._endPathZoom | |
}); | |
} else { | |
L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-hide'); | |
} | |
this.on('moveend', this._updateSvgViewport); | |
this._updateSvgViewport(); | |
} | |
}, | |
_animatePathZoom: function (e) { | |
var scale = this.getZoomScale(e.zoom), | |
offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min); | |
this._pathRoot.style[L.DomUtil.TRANSFORM] = | |
L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') '; | |
this._pathZooming = true; | |
}, | |
_endPathZoom: function () { | |
this._pathZooming = false; | |
}, | |
_updateSvgViewport: function () { | |
if (this._pathZooming) { | |
// Do not update SVGs while a zoom animation is going on otherwise the animation will break. | |
// When the zoom animation ends we will be updated again anyway | |
// This fixes the case where you do a momentum move and zoom while the move is still ongoing. | |
return; | |
} | |
this._updatePathViewport(); | |
var vp = this._pathViewport, | |
min = vp.min, | |
max = vp.max, | |
width = max.x - min.x, | |
height = max.y - min.y, | |
root = this._pathRoot, | |
pane = this._panes.overlayPane; | |
// Hack to make flicker on drag end on mobile webkit less irritating | |
if (L.Browser.mobileWebkit) { | |
pane.removeChild(root); | |
} | |
L.DomUtil.setPosition(root, min); | |
root.setAttribute('width', width); | |
root.setAttribute('height', height); | |
root.setAttribute('viewBox', [min.x, min.y, width, height].join(' ')); | |
if (L.Browser.mobileWebkit) { | |
pane.appendChild(root); | |
} | |
} | |
}); | |
/* | |
* Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods. | |
*/ | |
L.Path.include({ | |
bindPopup: function (content, options) { | |
if (content instanceof L.Popup) { | |
this._popup = content; | |
} else { | |
if (!this._popup || options) { | |
this._popup = new L.Popup(options, this); | |
} | |
this._popup.setContent(content); | |
} | |
if (!this._popupHandlersAdded) { | |
this | |
.on('click', this._openPopup, this) | |
.on('remove', this.closePopup, this); | |
this._popupHandlersAdded = true; | |
} | |
return this; | |
}, | |
unbindPopup: function () { | |
if (this._popup) { | |
this._popup = null; | |
this | |
.off('click', this._openPopup) | |
.off('remove', this.closePopup); | |
this._popupHandlersAdded = false; | |
} | |
return this; | |
}, | |
openPopup: function (latlng) { | |
if (this._popup) { | |
// open the popup from one of the path's points if not specified | |
latlng = latlng || this._latlng || | |
this._latlngs[Math.floor(this._latlngs.length / 2)]; | |
this._openPopup({latlng: latlng}); | |
} | |
return this; | |
}, | |
closePopup: function () { | |
if (this._popup) { | |
this._popup._close(); | |
} | |
return this; | |
}, | |
_openPopup: function (e) { | |
this._popup.setLatLng(e.latlng); | |
this._map.openPopup(this._popup); | |
} | |
}); | |
/* | |
* Vector rendering for IE6-8 through VML. | |
* Thanks to Dmitry Baranovsky and his Raphael library for inspiration! | |
*/ | |
L.Browser.vml = !L.Browser.svg && (function () { | |
try { | |
var div = document.createElement('div'); | |
div.innerHTML = '<v:shape adj="1"/>'; | |
var shape = div.firstChild; | |
shape.style.behavior = 'url(#default#VML)'; | |
return shape && (typeof shape.adj === 'object'); | |
} catch (e) { | |
return false; | |
} | |
}()); | |
L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({ | |
statics: { | |
VML: true, | |
CLIP_PADDING: 0.02 | |
}, | |
_createElement: (function () { | |
try { | |
document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml'); | |
return function (name) { | |
return document.createElement('<lvml:' + name + ' class="lvml">'); | |
}; | |
} catch (e) { | |
return function (name) { | |
return document.createElement( | |
'<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">'); | |
}; | |
} | |
}()), | |
_initPath: function () { | |
var container = this._container = this._createElement('shape'); | |
L.DomUtil.addClass(container, 'leaflet-vml-shape' + | |
(this.options.className ? ' ' + this.options.className : '')); | |
if (this.options.clickable) { | |
L.DomUtil.addClass(container, 'leaflet-clickable'); | |
} | |
container.coordsize = '1 1'; | |
this._path = this._createElement('path'); | |
container.appendChild(this._path); | |
this._map._pathRoot.appendChild(container); | |
}, | |
_initStyle: function () { | |
this._updateStyle(); | |
}, | |
_updateStyle: function () { | |
var stroke = this._stroke, | |
fill = this._fill, | |
options = this.options, | |
container = this._container; | |
container.stroked = options.stroke; | |
container.filled = options.fill; | |
if (options.stroke) { | |
if (!stroke) { | |
stroke = this._stroke = this._createElement('stroke'); | |
stroke.endcap = 'round'; | |
container.appendChild(stroke); | |
} | |
stroke.weight = options.weight + 'px'; | |
stroke.color = options.color; | |
stroke.opacity = options.opacity; | |
if (options.dashArray) { | |
stroke.dashStyle = L.Util.isArray(options.dashArray) ? | |
options.dashArray.join(' ') : | |
options.dashArray.replace(/( *, *)/g, ' '); | |
} else { | |
stroke.dashStyle = ''; | |
} | |
if (options.lineCap) { | |
stroke.endcap = options.lineCap.replace('butt', 'flat'); | |
} | |
if (options.lineJoin) { | |
stroke.joinstyle = options.lineJoin; | |
} | |
} else if (stroke) { | |
container.removeChild(stroke); | |
this._stroke = null; | |
} | |
if (options.fill) { | |
if (!fill) { | |
fill = this._fill = this._createElement('fill'); | |
container.appendChild(fill); | |
} | |
fill.color = options.fillColor || options.color; | |
fill.opacity = options.fillOpacity; | |
} else if (fill) { | |
container.removeChild(fill); | |
this._fill = null; | |
} | |
}, | |
_updatePath: function () { | |
var style = this._container.style; | |
style.display = 'none'; | |
this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug | |
style.display = ''; | |
} | |
}); | |
L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : { | |
_initPathRoot: function () { | |
if (this._pathRoot) { return; } | |
var root = this._pathRoot = document.createElement('div'); | |
root.className = 'leaflet-vml-container'; | |
this._panes.overlayPane.appendChild(root); | |
this.on('moveend', this._updatePathViewport); | |
this._updatePathViewport(); | |
} | |
}); | |
/* | |
* Vector rendering for all browsers that support canvas. | |
*/ | |
L.Browser.canvas = (function () { | |
return !!document.createElement('canvas').getContext; | |
}()); | |
L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({ | |
statics: { | |
//CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value | |
CANVAS: true, | |
SVG: false | |
}, | |
redraw: function () { | |
if (this._map) { | |
this.projectLatlngs(); | |
this._requestUpdate(); | |
} | |
return this; | |
}, | |
setStyle: function (style) { | |
L.setOptions(this, style); | |
if (this._map) { | |
this._updateStyle(); | |
this._requestUpdate(); | |
} | |
return this; | |
}, | |
onRemove: function (map) { | |
map | |
.off('viewreset', this.projectLatlngs, this) | |
.off('moveend', this._updatePath, this); | |
if (this.options.clickable) { | |
this._map.off('click', this._onClick, this); | |
this._map.off('mousemove', this._onMouseMove, this); | |
} | |
this._requestUpdate(); | |
this.fire('remove'); | |
this._map = null; | |
}, | |
_requestUpdate: function () { | |
if (this._map && !L.Path._updateRequest) { | |
L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map); | |
} | |
}, | |
_fireMapMoveEnd: function () { | |
L.Path._updateRequest = null; | |
this.fire('moveend'); | |
}, | |
_initElements: function () { | |
this._map._initPathRoot(); | |
this._ctx = this._map._canvasCtx; | |
}, | |
_updateStyle: function () { | |
var options = this.options; | |
if (options.stroke) { | |
this._ctx.lineWidth = options.weight; | |
this._ctx.strokeStyle = options.color; | |
} | |
if (options.fill) { | |
this._ctx.fillStyle = options.fillColor || options.color; | |
} | |
}, | |
_drawPath: function () { | |
var i, j, len, len2, point, drawMethod; | |
this._ctx.beginPath(); | |
for (i = 0, len = this._parts.length; i < len; i++) { | |
for (j = 0, len2 = this._parts[i].length; j < len2; j++) { | |
point = this._parts[i][j]; | |
drawMethod = (j === 0 ? 'move' : 'line') + 'To'; | |
this._ctx[drawMethod](point.x, point.y); | |
} | |
// TODO refactor ugly hack | |
if (this instanceof L.Polygon) { | |
this._ctx.closePath(); | |
} | |
} | |
}, | |
_checkIfEmpty: function () { | |
return !this._parts.length; | |
}, | |
_updatePath: function () { | |
if (this._checkIfEmpty()) { return; } | |
var ctx = this._ctx, | |
options = this.options; | |
this._drawPath(); | |
ctx.save(); | |
this._updateStyle(); | |
if (options.fill) { | |
ctx.globalAlpha = options.fillOpacity; | |
ctx.fill(); | |
} | |
if (options.stroke) { | |
ctx.globalAlpha = options.opacity; | |
ctx.stroke(); | |
} | |
ctx.restore(); | |
// TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature | |
}, | |
_initEvents: function () { | |
if (this.options.clickable) { | |
// TODO dblclick | |
this._map.on('mousemove', this._onMouseMove, this); | |
this._map.on('click', this._onClick, this); | |
} | |
}, | |
_onClick: function (e) { | |
if (this._containsPoint(e.layerPoint)) { | |
this.fire('click', e); | |
} | |
}, | |
_onMouseMove: function (e) { | |
if (!this._map || this._map._animatingZoom) { return; } | |
// TODO don't do on each move | |
if (this._containsPoint(e.layerPoint)) { | |
this._ctx.canvas.style.cursor = 'pointer'; | |
this._mouseInside = true; | |
this.fire('mouseover', e); | |
} else if (this._mouseInside) { | |
this._ctx.canvas.style.cursor = ''; | |
this._mouseInside = false; | |
this.fire('mouseout', e); | |
} | |
} | |
}); | |
L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : { | |
_initPathRoot: function () { | |
var root = this._pathRoot, | |
ctx; | |
if (!root) { | |
root = this._pathRoot = document.createElement('canvas'); | |
root.style.position = 'absolute'; | |
ctx = this._canvasCtx = root.getContext('2d'); | |
ctx.lineCap = 'round'; | |
ctx.lineJoin = 'round'; | |
this._panes.overlayPane.appendChild(root); | |
if (this.options.zoomAnimation) { | |
this._pathRoot.className = 'leaflet-zoom-animated'; | |
this.on('zoomanim', this._animatePathZoom); | |
this.on('zoomend', this._endPathZoom); | |
} | |
this.on('moveend', this._updateCanvasViewport); | |
this._updateCanvasViewport(); | |
} | |
}, | |
_updateCanvasViewport: function () { | |
// don't redraw while zooming. See _updateSvgViewport for more details | |
if (this._pathZooming) { return; } | |
this._updatePathViewport(); | |
var vp = this._pathViewport, | |
min = vp.min, | |
size = vp.max.subtract(min), | |
root = this._pathRoot; | |
//TODO check if this works properly on mobile webkit | |
L.DomUtil.setPosition(root, min); | |
root.width = size.x; | |
root.height = size.y; | |
root.getContext('2d').translate(-min.x, -min.y); | |
} | |
}); | |
/* | |
* L.LineUtil contains different utility functions for line segments | |
* and polylines (clipping, simplification, distances, etc.) | |
*/ | |
/*jshint bitwise:false */ // allow bitwise operations for this file | |
L.LineUtil = { | |
// Simplify polyline with vertex reduction and Douglas-Peucker simplification. | |
// Improves rendering performance dramatically by lessening the number of points to draw. | |
simplify: function (/*Point[]*/ points, /*Number*/ tolerance) { | |
if (!tolerance || !points.length) { | |
return points.slice(); | |
} | |
var sqTolerance = tolerance * tolerance; | |
// stage 1: vertex reduction | |
points = this._reducePoints(points, sqTolerance); | |
// stage 2: Douglas-Peucker simplification | |
points = this._simplifyDP(points, sqTolerance); | |
return points; | |
}, | |
// distance from a point to a segment between two points | |
pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) { | |
return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true)); | |
}, | |
closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) { | |
return this._sqClosestPointOnSegment(p, p1, p2); | |
}, | |
// Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm | |
_simplifyDP: function (points, sqTolerance) { | |
var len = points.length, | |
ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array, | |
markers = new ArrayConstructor(len); | |
markers[0] = markers[len - 1] = 1; | |
this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1); | |
var i, | |
newPoints = []; | |
for (i = 0; i < len; i++) { | |
if (markers[i]) { | |
newPoints.push(points[i]); | |
} | |
} | |
return newPoints; | |
}, | |
_simplifyDPStep: function (points, markers, sqTolerance, first, last) { | |
var maxSqDist = 0, | |
index, i, sqDist; | |
for (i = first + 1; i <= last - 1; i++) { | |
sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true); | |
if (sqDist > maxSqDist) { | |
index = i; | |
maxSqDist = sqDist; | |
} | |
} | |
if (maxSqDist > sqTolerance) { | |
markers[index] = 1; | |
this._simplifyDPStep(points, markers, sqTolerance, first, index); | |
this._simplifyDPStep(points, markers, sqTolerance, index, last); | |
} | |
}, | |
// reduce points that are too close to each other to a single point | |
_reducePoints: function (points, sqTolerance) { | |
var reducedPoints = [points[0]]; | |
for (var i = 1, prev = 0, len = points.length; i < len; i++) { | |
if (this._sqDist(points[i], points[prev]) > sqTolerance) { | |
reducedPoints.push(points[i]); | |
prev = i; | |
} | |
} | |
if (prev < len - 1) { | |
reducedPoints.push(points[len - 1]); | |
} | |
return reducedPoints; | |
}, | |
// Cohen-Sutherland line clipping algorithm. | |
// Used to avoid rendering parts of a polyline that are not currently visible. | |
clipSegment: function (a, b, bounds, useLastCode) { | |
var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds), | |
codeB = this._getBitCode(b, bounds), | |
codeOut, p, newCode; | |
// save 2nd code to avoid calculating it on the next segment | |
this._lastCode = codeB; | |
while (true) { | |
// if a,b is inside the clip window (trivial accept) | |
if (!(codeA | codeB)) { | |
return [a, b]; | |
// if a,b is outside the clip window (trivial reject) | |
} else if (codeA & codeB) { | |
return false; | |
// other cases | |
} else { | |
codeOut = codeA || codeB; | |
p = this._getEdgeIntersection(a, b, codeOut, bounds); | |
newCode = this._getBitCode(p, bounds); | |
if (codeOut === codeA) { | |
a = p; | |
codeA = newCode; | |
} else { | |
b = p; | |
codeB = newCode; | |
} | |
} | |
} | |
}, | |
_getEdgeIntersection: function (a, b, code, bounds) { | |
var dx = b.x - a.x, | |
dy = b.y - a.y, | |
min = bounds.min, | |
max = bounds.max; | |
if (code & 8) { // top | |
return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y); | |
} else if (code & 4) { // bottom | |
return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y); | |
} else if (code & 2) { // right | |
return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx); | |
} else if (code & 1) { // left | |
return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx); | |
} | |
}, | |
_getBitCode: function (/*Point*/ p, bounds) { | |
var code = 0; | |
if (p.x < bounds.min.x) { // left | |
code |= 1; | |
} else if (p.x > bounds.max.x) { // right | |
code |= 2; | |
} | |
if (p.y < bounds.min.y) { // bottom | |
code |= 4; | |
} else if (p.y > bounds.max.y) { // top | |
code |= 8; | |
} | |
return code; | |
}, | |
// square distance (to avoid unnecessary Math.sqrt calls) | |
_sqDist: function (p1, p2) { | |
var dx = p2.x - p1.x, | |
dy = p2.y - p1.y; | |
return dx * dx + dy * dy; | |
}, | |
// return closest point on segment or distance to that point | |
_sqClosestPointOnSegment: function (p, p1, p2, sqDist) { | |
var x = p1.x, | |
y = p1.y, | |
dx = p2.x - x, | |
dy = p2.y - y, | |
dot = dx * dx + dy * dy, | |
t; | |
if (dot > 0) { | |
t = ((p.x - x) * dx + (p.y - y) * dy) / dot; | |
if (t > 1) { | |
x = p2.x; | |
y = p2.y; | |
} else if (t > 0) { | |
x += dx * t; | |
y += dy * t; | |
} | |
} | |
dx = p.x - x; | |
dy = p.y - y; | |
return sqDist ? dx * dx + dy * dy : new L.Point(x, y); | |
} | |
}; | |
/* | |
* L.Polyline is used to display polylines on a map. | |
*/ | |
L.Polyline = L.Path.extend({ | |
initialize: function (latlngs, options) { | |
L.Path.prototype.initialize.call(this, options); | |
this._latlngs = this._convertLatLngs(latlngs); | |
}, | |
options: { | |
// how much to simplify the polyline on each zoom level | |
// more = better performance and smoother look, less = more accurate | |
smoothFactor: 1.0, | |
noClip: false | |
}, | |
projectLatlngs: function () { | |
this._originalPoints = []; | |
for (var i = 0, len = this._latlngs.length; i < len; i++) { | |
this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]); | |
} | |
}, | |
getPathString: function () { | |
for (var i = 0, len = this._parts.length, str = ''; i < len; i++) { | |
str += this._getPathPartStr(this._parts[i]); | |
} | |
return str; | |
}, | |
getLatLngs: function () { | |
return this._latlngs; | |
}, | |
setLatLngs: function (latlngs) { | |
this._latlngs = this._convertLatLngs(latlngs); | |
return this.redraw(); | |
}, | |
addLatLng: function (latlng) { | |
this._latlngs.push(L.latLng(latlng)); | |
return this.redraw(); | |
}, | |
spliceLatLngs: function () { // (Number index, Number howMany) | |
var removed = [].splice.apply(this._latlngs, arguments); | |
this._convertLatLngs(this._latlngs, true); | |
this.redraw(); | |
return removed; | |
}, | |
closestLayerPoint: function (p) { | |
var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null; | |
for (var j = 0, jLen = parts.length; j < jLen; j++) { | |
var points = parts[j]; | |
for (var i = 1, len = points.length; i < len; i++) { | |
p1 = points[i - 1]; | |
p2 = points[i]; | |
var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true); | |
if (sqDist < minDistance) { | |
minDistance = sqDist; | |
minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2); | |
} | |
} | |
} | |
if (minPoint) { | |
minPoint.distance = Math.sqrt(minDistance); | |
} | |
return minPoint; | |
}, | |
getBounds: function () { | |
return new L.LatLngBounds(this.getLatLngs()); | |
}, | |
_convertLatLngs: function (latlngs, overwrite) { | |
var i, len, target = overwrite ? latlngs : []; | |
for (i = 0, len = latlngs.length; i < len; i++) { | |
if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') { | |
return; | |
} | |
target[i] = L.latLng(latlngs[i]); | |
} | |
return target; | |
}, | |
_initEvents: function () { | |
L.Path.prototype._initEvents.call(this); | |
}, | |
_getPathPartStr: function (points) { | |
var round = L.Path.VML; | |
for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) { | |
p = points[j]; | |
if (round) { | |
p._round(); | |
} | |
str += (j ? 'L' : 'M') + p.x + ' ' + p.y; | |
} | |
return str; | |
}, | |
_clipPoints: function () { | |
var points = this._originalPoints, | |
len = points.length, | |
i, k, segment; | |
if (this.options.noClip) { | |
this._parts = [points]; | |
return; | |
} | |
this._parts = []; | |
var parts = this._parts, | |
vp = this._map._pathViewport, | |
lu = L.LineUtil; | |
for (i = 0, k = 0; i < len - 1; i++) { | |
segment = lu.clipSegment(points[i], points[i + 1], vp, i); | |
if (!segment) { | |
continue; | |
} | |
parts[k] = parts[k] || []; | |
parts[k].push(segment[0]); | |
// if segment goes out of screen, or it's the last one, it's the end of the line part | |
if ((segment[1] !== points[i + 1]) || (i === len - 2)) { | |
parts[k].push(segment[1]); | |
k++; | |
} | |
} | |
}, | |
// simplify each clipped part of the polyline | |
_simplifyPoints: function () { | |
var parts = this._parts, | |
lu = L.LineUtil; | |
for (var i = 0, len = parts.length; i < len; i++) { | |
parts[i] = lu.simplify(parts[i], this.options.smoothFactor); | |
} | |
}, | |
_updatePath: function () { | |
if (!this._map) { return; } | |
this._clipPoints(); | |
this._simplifyPoints(); | |
L.Path.prototype._updatePath.call(this); | |
} | |
}); | |
L.polyline = function (latlngs, options) { | |
return new L.Polyline(latlngs, options); | |
}; | |
/* | |
* L.PolyUtil contains utility functions for polygons (clipping, etc.). | |
*/ | |
/*jshint bitwise:false */ // allow bitwise operations here | |
L.PolyUtil = {}; | |
/* | |
* Sutherland-Hodgeman polygon clipping algorithm. | |
* Used to avoid rendering parts of a polygon that are not currently visible. | |
*/ | |
L.PolyUtil.clipPolygon = function (points, bounds) { | |
var clippedPoints, | |
edges = [1, 4, 2, 8], | |
i, j, k, | |
a, b, | |
len, edge, p, | |
lu = L.LineUtil; | |
for (i = 0, len = points.length; i < len; i++) { | |
points[i]._code = lu._getBitCode(points[i], bounds); | |
} | |
// for each edge (left, bottom, right, top) | |
for (k = 0; k < 4; k++) { | |
edge = edges[k]; | |
clippedPoints = []; | |
for (i = 0, len = points.length, j = len - 1; i < len; j = i++) { | |
a = points[i]; | |
b = points[j]; | |
// if a is inside the clip window | |
if (!(a._code & edge)) { | |
// if b is outside the clip window (a->b goes out of screen) | |
if (b._code & edge) { | |
p = lu._getEdgeIntersection(b, a, edge, bounds); | |
p._code = lu._getBitCode(p, bounds); | |
clippedPoints.push(p); | |
} | |
clippedPoints.push(a); | |
// else if b is inside the clip window (a->b enters the screen) | |
} else if (!(b._code & edge)) { | |
p = lu._getEdgeIntersection(b, a, edge, bounds); | |
p._code = lu._getBitCode(p, bounds); | |
clippedPoints.push(p); | |
} | |
} | |
points = clippedPoints; | |
} | |
return points; | |
}; | |
/* | |
* L.Polygon is used to display polygons on a map. | |
*/ | |
L.Polygon = L.Polyline.extend({ | |
options: { | |
fill: true | |
}, | |
initialize: function (latlngs, options) { | |
L.Polyline.prototype.initialize.call(this, latlngs, options); | |
this._initWithHoles(latlngs); | |
}, | |
_initWithHoles: function (latlngs) { | |
var i, len, hole; | |
if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) { | |
this._latlngs = this._convertLatLngs(latlngs[0]); | |
this._holes = latlngs.slice(1); | |
for (i = 0, len = this._holes.length; i < len; i++) { | |
hole = this._holes[i] = this._convertLatLngs(this._holes[i]); | |
if (hole[0].equals(hole[hole.length - 1])) { | |
hole.pop(); | |
} | |
} | |
} | |
// filter out last point if its equal to the first one | |
latlngs = this._latlngs; | |
if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) { | |
latlngs.pop(); | |
} | |
}, | |
projectLatlngs: function () { | |
L.Polyline.prototype.projectLatlngs.call(this); | |
// project polygon holes points | |
// TODO move this logic to Polyline to get rid of duplication | |
this._holePoints = []; | |
if (!this._holes) { return; } | |
var i, j, len, len2; | |
for (i = 0, len = this._holes.length; i < len; i++) { | |
this._holePoints[i] = []; | |
for (j = 0, len2 = this._holes[i].length; j < len2; j++) { | |
this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]); | |
} | |
} | |
}, | |
setLatLngs: function (latlngs) { | |
if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) { | |
this._initWithHoles(latlngs); | |
return this.redraw(); | |
} else { | |
return L.Polyline.prototype.setLatLngs.call(this, latlngs); | |
} | |
}, | |
_clipPoints: function () { | |
var points = this._originalPoints, | |
newParts = []; | |
this._parts = [points].concat(this._holePoints); | |
if (this.options.noClip) { return; } | |
for (var i = 0, len = this._parts.length; i < len; i++) { | |
var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport); | |
if (clipped.length) { | |
newParts.push(clipped); | |
} | |
} | |
this._parts = newParts; | |
}, | |
_getPathPartStr: function (points) { | |
var str = L.Polyline.prototype._getPathPartStr.call(this, points); | |
return str + (L.Browser.svg ? 'z' : 'x'); | |
} | |
}); | |
L.polygon = function (latlngs, options) { | |
return new L.Polygon(latlngs, options); | |
}; | |
/* | |
* Contains L.MultiPolyline and L.MultiPolygon layers. | |
*/ | |
(function () { | |
function createMulti(Klass) { | |
return L.FeatureGroup.extend({ | |
initialize: function (latlngs, options) { | |
this._layers = {}; | |
this._options = options; | |
this.setLatLngs(latlngs); | |
}, | |
setLatLngs: function (latlngs) { | |
var i = 0, | |
len = latlngs.length; | |
this.eachLayer(function (layer) { | |
if (i < len) { | |
layer.setLatLngs(latlngs[i++]); | |
} else { | |
this.removeLayer(layer); | |
} | |
}, this); | |
while (i < len) { | |
this.addLayer(new Klass(latlngs[i++], this._options)); | |
} | |
return this; | |
}, | |
getLatLngs: function () { | |
var latlngs = []; | |
this.eachLayer(function (layer) { | |
latlngs.push(layer.getLatLngs()); | |
}); | |
return latlngs; | |
} | |
}); | |
} | |
L.MultiPolyline = createMulti(L.Polyline); | |
L.MultiPolygon = createMulti(L.Polygon); | |
L.multiPolyline = function (latlngs, options) { | |
return new L.MultiPolyline(latlngs, options); | |
}; | |
L.multiPolygon = function (latlngs, options) { | |
return new L.MultiPolygon(latlngs, options); | |
}; | |
}()); | |
/* | |
* L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object. | |
*/ | |
L.Rectangle = L.Polygon.extend({ | |
initialize: function (latLngBounds, options) { | |
L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options); | |
}, | |
setBounds: function (latLngBounds) { | |
this.setLatLngs(this._boundsToLatLngs(latLngBounds)); | |
}, | |
_boundsToLatLngs: function (latLngBounds) { | |
latLngBounds = L.latLngBounds(latLngBounds); | |
return [ | |
latLngBounds.getSouthWest(), | |
latLngBounds.getNorthWest(), | |
latLngBounds.getNorthEast(), | |
latLngBounds.getSouthEast() | |
]; | |
} | |
}); | |
L.rectangle = function (latLngBounds, options) { | |
return new L.Rectangle(latLngBounds, options); | |
}; | |
/* | |
* L.Circle is a circle overlay (with a certain radius in meters). | |
*/ | |
L.Circle = L.Path.extend({ | |
initialize: function (latlng, radius, options) { | |
L.Path.prototype.initialize.call(this, options); | |
this._latlng = L.latLng(latlng); | |
this._mRadius = radius; | |
}, | |
options: { | |
fill: true | |
}, | |
setLatLng: function (latlng) { | |
this._latlng = L.latLng(latlng); | |
return this.redraw(); | |
}, | |
setRadius: function (radius) { | |
this._mRadius = radius; | |
return this.redraw(); | |
}, | |
projectLatlngs: function () { | |
var lngRadius = this._getLngRadius(), | |
latlng = this._latlng, | |
pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]); | |
this._point = this._map.latLngToLayerPoint(latlng); | |
this._radius = Math.max(this._point.x - pointLeft.x, 1); | |
}, | |
getBounds: function () { | |
var lngRadius = this._getLngRadius(), | |
latRadius = (this._mRadius / 40075017) * 360, | |
latlng = this._latlng; | |
return new L.LatLngBounds( | |
[latlng.lat - latRadius, latlng.lng - lngRadius], | |
[latlng.lat + latRadius, latlng.lng + lngRadius]); | |
}, | |
getLatLng: function () { | |
return this._latlng; | |
}, | |
getPathString: function () { | |
var p = this._point, | |
r = this._radius; | |
if (this._checkIfEmpty()) { | |
return ''; | |
} | |
if (L.Browser.svg) { | |
return 'M' + p.x + ',' + (p.y - r) + | |
'A' + r + ',' + r + ',0,1,1,' + | |
(p.x - 0.1) + ',' + (p.y - r) + ' z'; | |
} else { | |
p._round(); | |
r = Math.round(r); | |
return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360); | |
} | |
}, | |
getRadius: function () { | |
return this._mRadius; | |
}, | |
// TODO Earth hardcoded, move into projection code! | |
_getLatRadius: function () { | |
return (this._mRadius / 40075017) * 360; | |
}, | |
_getLngRadius: function () { | |
return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat); | |
}, | |
_checkIfEmpty: function () { | |
if (!this._map) { | |
return false; | |
} | |
var vp = this._map._pathViewport, | |
r = this._radius, | |
p = this._point; | |
return p.x - r > vp.max.x || p.y - r > vp.max.y || | |
p.x + r < vp.min.x || p.y + r < vp.min.y; | |
} | |
}); | |
L.circle = function (latlng, radius, options) { | |
return new L.Circle(latlng, radius, options); | |
}; | |
/* | |
* L.CircleMarker is a circle overlay with a permanent pixel radius. | |
*/ | |
L.CircleMarker = L.Circle.extend({ | |
options: { | |
radius: 10, | |
weight: 2 | |
}, | |
initialize: function (latlng, options) { | |
L.Circle.prototype.initialize.call(this, latlng, null, options); | |
this._radius = this.options.radius; | |
}, | |
projectLatlngs: function () { | |
this._point = this._map.latLngToLayerPoint(this._latlng); | |
}, | |
_updateStyle : function () { | |
L.Circle.prototype._updateStyle.call(this); | |
this.setRadius(this.options.radius); | |
}, | |
setLatLng: function (latlng) { | |
L.Circle.prototype.setLatLng.call(this, latlng); | |
if (this._popup && this._popup._isOpen) { | |
this._popup.setLatLng(latlng); | |
} | |
return this; | |
}, | |
setRadius: function (radius) { | |
this.options.radius = this._radius = radius; | |
return this.redraw(); | |
}, | |
getRadius: function () { | |
return this._radius; | |
} | |
}); | |
L.circleMarker = function (latlng, options) { | |
return new L.CircleMarker(latlng, options); | |
}; | |
/* | |
* Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines. | |
*/ | |
L.Polyline.include(!L.Path.CANVAS ? {} : { | |
_containsPoint: function (p, closed) { | |
var i, j, k, len, len2, dist, part, | |
w = this.options.weight / 2; | |
if (L.Browser.touch) { | |
w += 10; // polyline click tolerance on touch devices | |
} | |
for (i = 0, len = this._parts.length; i < len; i++) { | |
part = this._parts[i]; | |
for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { | |
if (!closed && (j === 0)) { | |
continue; | |
} | |
dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]); | |
if (dist <= w) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
}); | |
/* | |
* Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons. | |
*/ | |
L.Polygon.include(!L.Path.CANVAS ? {} : { | |
_containsPoint: function (p) { | |
var inside = false, | |
part, p1, p2, | |
i, j, k, | |
len, len2; | |
// TODO optimization: check if within bounds first | |
if (L.Polyline.prototype._containsPoint.call(this, p, true)) { | |
// click on polygon border | |
return true; | |
} | |
// ray casting algorithm for detecting if point is in polygon | |
for (i = 0, len = this._parts.length; i < len; i++) { | |
part = this._parts[i]; | |
for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { | |
p1 = part[j]; | |
p2 = part[k]; | |
if (((p1.y > p.y) !== (p2.y > p.y)) && | |
(p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { | |
inside = !inside; | |
} | |
} | |
} | |
return inside; | |
} | |
}); | |
/* | |
* Extends L.Circle with Canvas-specific code. | |
*/ | |
L.Circle.include(!L.Path.CANVAS ? {} : { | |
_drawPath: function () { | |
var p = this._point; | |
this._ctx.beginPath(); | |
this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false); | |
}, | |
_containsPoint: function (p) { | |
var center = this._point, | |
w2 = this.options.stroke ? this.options.weight / 2 : 0; | |
return (p.distanceTo(center) <= this._radius + w2); | |
} | |
}); | |
/* | |
* CircleMarker canvas specific drawing parts. | |
*/ | |
L.CircleMarker.include(!L.Path.CANVAS ? {} : { | |
_updateStyle: function () { | |
L.Path.prototype._updateStyle.call(this); | |
} | |
}); | |
/* | |
* L.GeoJSON turns any GeoJSON data into a Leaflet layer. | |
*/ | |
L.GeoJSON = L.FeatureGroup.extend({ | |
initialize: function (geojson, options) { | |
L.setOptions(this, options); | |
this._layers = {}; | |
if (geojson) { | |
this.addData(geojson); | |
} | |
}, | |
addData: function (geojson) { | |
var features = L.Util.isArray(geojson) ? geojson : geojson.features, | |
i, len, feature; | |
if (features) { | |
for (i = 0, len = features.length; i < len; i++) { | |
// Only add this if geometry or geometries are set and not null | |
feature = features[i]; | |
if (feature.geometries || feature.geometry || feature.features || feature.coordinates) { | |
this.addData(features[i]); | |
} | |
} | |
return this; | |
} | |
var options = this.options; | |
if (options.filter && !options.filter(geojson)) { return; } | |
var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng, options); | |
layer.feature = L.GeoJSON.asFeature(geojson); | |
layer.defaultOptions = layer.options; | |
this.resetStyle(layer); | |
if (options.onEachFeature) { | |
options.onEachFeature(geojson, layer); | |
} | |
return this.addLayer(layer); | |
}, | |
resetStyle: function (layer) { | |
var style = this.options.style; | |
if (style) { | |
// reset any custom styles | |
L.Util.extend(layer.options, layer.defaultOptions); | |
this._setLayerStyle(layer, style); | |
} | |
}, | |
setStyle: function (style) { | |
this.eachLayer(function (layer) { | |
this._setLayerStyle(layer, style); | |
}, this); | |
}, | |
_setLayerStyle: function (layer, style) { | |
if (typeof style === 'function') { | |
style = style(layer.feature); | |
} | |
if (layer.setStyle) { | |
layer.setStyle(style); | |
} | |
} | |
}); | |
L.extend(L.GeoJSON, { | |
geometryToLayer: function (geojson, pointToLayer, coordsToLatLng, vectorOptions) { | |
var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson, | |
coords = geometry.coordinates, | |
layers = [], | |
latlng, latlngs, i, len; | |
coordsToLatLng = coordsToLatLng || this.coordsToLatLng; | |
switch (geometry.type) { | |
case 'Point': | |
latlng = coordsToLatLng(coords); | |
return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng); | |
case 'MultiPoint': | |
for (i = 0, len = coords.length; i < len; i++) { | |
latlng = coordsToLatLng(coords[i]); | |
layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng)); | |
} | |
return new L.FeatureGroup(layers); | |
case 'LineString': | |
latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng); | |
return new L.Polyline(latlngs, vectorOptions); | |
case 'Polygon': | |
if (coords.length === 2 && !coords[1].length) { | |
throw new Error('Invalid GeoJSON object.'); | |
} | |
latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng); | |
return new L.Polygon(latlngs, vectorOptions); | |
case 'MultiLineString': | |
latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng); | |
return new L.MultiPolyline(latlngs, vectorOptions); | |
case 'MultiPolygon': | |
latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng); | |
return new L.MultiPolygon(latlngs, vectorOptions); | |
case 'GeometryCollection': | |
for (i = 0, len = geometry.geometries.length; i < len; i++) { | |
layers.push(this.geometryToLayer({ | |
geometry: geometry.geometries[i], | |
type: 'Feature', | |
properties: geojson.properties | |
}, pointToLayer, coordsToLatLng, vectorOptions)); | |
} | |
return new L.FeatureGroup(layers); | |
default: | |
throw new Error('Invalid GeoJSON object.'); | |
} | |
}, | |
coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng | |
return new L.LatLng(coords[1], coords[0], coords[2]); | |
}, | |
coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array | |
var latlng, i, len, | |
latlngs = []; | |
for (i = 0, len = coords.length; i < len; i++) { | |
latlng = levelsDeep ? | |
this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) : | |
(coordsToLatLng || this.coordsToLatLng)(coords[i]); | |
latlngs.push(latlng); | |
} | |
return latlngs; | |
}, | |
latLngToCoords: function (latlng) { | |
var coords = [latlng.lng, latlng.lat]; | |
if (latlng.alt !== undefined) { | |
coords.push(latlng.alt); | |
} | |
return coords; | |
}, | |
latLngsToCoords: function (latLngs) { | |
var coords = []; | |
for (var i = 0, len = latLngs.length; i < len; i++) { | |
coords.push(L.GeoJSON.latLngToCoords(latLngs[i])); | |
} | |
return coords; | |
}, | |
getFeature: function (layer, newGeometry) { | |
return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry); | |
}, | |
asFeature: function (geoJSON) { | |
if (geoJSON.type === 'Feature') { | |
return geoJSON; | |
} | |
return { | |
type: 'Feature', | |
properties: {}, | |
geometry: geoJSON | |
}; | |
} | |
}); | |
var PointToGeoJSON = { | |
toGeoJSON: function () { | |
return L.GeoJSON.getFeature(this, { | |
type: 'Point', | |
coordinates: L.GeoJSON.latLngToCoords(this.getLatLng()) | |
}); | |
} | |
}; | |
L.Marker.include(PointToGeoJSON); | |
L.Circle.include(PointToGeoJSON); | |
L.CircleMarker.include(PointToGeoJSON); | |
L.Polyline.include({ | |
toGeoJSON: function () { | |
return L.GeoJSON.getFeature(this, { | |
type: 'LineString', | |
coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs()) | |
}); | |
} | |
}); | |
L.Polygon.include({ | |
toGeoJSON: function () { | |
var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())], | |
i, len, hole; | |
coords[0].push(coords[0][0]); | |
if (this._holes) { | |
for (i = 0, len = this._holes.length; i < len; i++) { | |
hole = L.GeoJSON.latLngsToCoords(this._holes[i]); | |
hole.push(hole[0]); | |
coords.push(hole); | |
} | |
} | |
return L.GeoJSON.getFeature(this, { | |
type: 'Polygon', | |
coordinates: coords | |
}); | |
} | |
}); | |
(function () { | |
function multiToGeoJSON(type) { | |
return function () { | |
var coords = []; | |
this.eachLayer(function (layer) { | |
coords.push(layer.toGeoJSON().geometry.coordinates); | |
}); | |
return L.GeoJSON.getFeature(this, { | |
type: type, | |
coordinates: coords | |
}); | |
}; | |
} | |
L.MultiPolyline.include({toGeoJSON: multiToGeoJSON('MultiLineString')}); | |
L.MultiPolygon.include({toGeoJSON: multiToGeoJSON('MultiPolygon')}); | |
L.LayerGroup.include({ | |
toGeoJSON: function () { | |
var geometry = this.feature && this.feature.geometry, | |
jsons = [], | |
json; | |
if (geometry && geometry.type === 'MultiPoint') { | |
return multiToGeoJSON('MultiPoint').call(this); | |
} | |
var isGeometryCollection = geometry && geometry.type === 'GeometryCollection'; | |
this.eachLayer(function (layer) { | |
if (layer.toGeoJSON) { | |
json = layer.toGeoJSON(); | |
jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json)); | |
} | |
}); | |
if (isGeometryCollection) { | |
return L.GeoJSON.getFeature(this, { | |
geometries: jsons, | |
type: 'GeometryCollection' | |
}); | |
} | |
return { | |
type: 'FeatureCollection', | |
features: jsons | |
}; | |
} | |
}); | |
}()); | |
L.geoJson = function (geojson, options) { | |
return new L.GeoJSON(geojson, options); | |
}; | |
/* | |
* L.DomEvent contains functions for working with DOM events. | |
*/ | |
L.DomEvent = { | |
/* inspired by John Resig, Dean Edwards and YUI addEvent implementations */ | |
addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object]) | |
var id = L.stamp(fn), | |
key = '_leaflet_' + type + id, | |
handler, originalHandler, newType; | |
if (obj[key]) { return this; } | |
handler = function (e) { | |
return fn.call(context || obj, e || L.DomEvent._getEvent()); | |
}; | |
if (L.Browser.pointer && type.indexOf('touch') === 0) { | |
return this.addPointerListener(obj, type, handler, id); | |
} | |
if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) { | |
this.addDoubleTapListener(obj, handler, id); | |
} | |
if ('addEventListener' in obj) { | |
if (type === 'mousewheel') { | |
obj.addEventListener('DOMMouseScroll', handler, false); | |
obj.addEventListener(type, handler, false); | |
} else if ((type === 'mouseenter') || (type === 'mouseleave')) { | |
originalHandler = handler; | |
newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout'); | |
handler = function (e) { | |
if (!L.DomEvent._checkMouse(obj, e)) { return; } | |
return originalHandler(e); | |
}; | |
obj.addEventListener(newType, handler, false); | |
} else if (type === 'click' && L.Browser.android) { | |
originalHandler = handler; | |
handler = function (e) { | |
return L.DomEvent._filterClick(e, originalHandler); | |
}; | |
obj.addEventListener(type, handler, false); | |
} else { | |
obj.addEventListener(type, handler, false); | |
} | |
} else if ('attachEvent' in obj) { | |
obj.attachEvent('on' + type, handler); | |
} | |
obj[key] = handler; | |
return this; | |
}, | |
removeListener: function (obj, type, fn) { // (HTMLElement, String, Function) | |
var id = L.stamp(fn), | |
key = '_leaflet_' + type + id, | |
handler = obj[key]; | |
if (!handler) { return this; } | |
if (L.Browser.pointer && type.indexOf('touch') === 0) { | |
this.removePointerListener(obj, type, id); | |
} else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) { | |
this.removeDoubleTapListener(obj, id); | |
} else if ('removeEventListener' in obj) { | |
if (type === 'mousewheel') { | |
obj.removeEventListener('DOMMouseScroll', handler, false); | |
obj.removeEventListener(type, handler, false); | |
} else if ((type === 'mouseenter') || (type === 'mouseleave')) { | |
obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false); | |
} else { | |
obj.removeEventListener(type, handler, false); | |
} | |
} else if ('detachEvent' in obj) { | |
obj.detachEvent('on' + type, handler); | |
} | |
obj[key] = null; | |
return this; | |
}, | |
stopPropagation: function (e) { | |
if (e.stopPropagation) { | |
e.stopPropagation(); | |
} else { | |
e.cancelBubble = true; | |
} | |
L.DomEvent._skipped(e); | |
return this; | |
}, | |
disableScrollPropagation: function (el) { | |
var stop = L.DomEvent.stopPropagation; | |
return L.DomEvent | |
.on(el, 'mousewheel', stop) | |
.on(el, 'MozMousePixelScroll', stop); | |
}, | |
disableClickPropagation: function (el) { | |
var stop = L.DomEvent.stopPropagation; | |
for (var i = L.Draggable.START.length - 1; i >= 0; i--) { | |
L.DomEvent.on(el, L.Draggable.START[i], stop); | |
} | |
return L.DomEvent | |
.on(el, 'click', L.DomEvent._fakeStop) | |
.on(el, 'dblclick', stop); | |
}, | |
preventDefault: function (e) { | |
if (e.preventDefault) { | |
e.preventDefault(); | |
} else { | |
e.returnValue = false; | |
} | |
return this; | |
}, | |
stop: function (e) { | |
return L.DomEvent | |
.preventDefault(e) | |
.stopPropagation(e); | |
}, | |
getMousePosition: function (e, container) { | |
if (!container) { | |
return new L.Point(e.clientX, e.clientY); | |
} | |
var rect = container.getBoundingClientRect(); | |
return new L.Point( | |
e.clientX - rect.left - container.clientLeft, | |
e.clientY - rect.top - container.clientTop); | |
}, | |
getWheelDelta: function (e) { | |
var delta = 0; | |
if (e.wheelDelta) { | |
delta = e.wheelDelta / 120; | |
} | |
if (e.detail) { | |
delta = -e.detail / 3; | |
} | |
return delta; | |
}, | |
_skipEvents: {}, | |
_fakeStop: function (e) { | |
// fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e) | |
L.DomEvent._skipEvents[e.type] = true; | |
}, | |
_skipped: function (e) { | |
var skipped = this._skipEvents[e.type]; | |
// reset when checking, as it's only used in map container and propagates outside of the map | |
this._skipEvents[e.type] = false; | |
return skipped; | |
}, | |
// check if element really left/entered the event target (for mouseenter/mouseleave) | |
_checkMouse: function (el, e) { | |
var related = e.relatedTarget; | |
if (!related) { return true; } | |
try { | |
while (related && (related !== el)) { | |
related = related.parentNode; | |
} | |
} catch (err) { | |
return false; | |
} | |
return (related !== el); | |
}, | |
_getEvent: function () { // evil magic for IE | |
/*jshint noarg:false */ | |
var e = window.event; | |
if (!e) { | |
var caller = arguments.callee.caller; | |
while (caller) { | |
e = caller['arguments'][0]; | |
if (e && window.Event === e.constructor) { | |
break; | |
} | |
caller = caller.caller; | |
} | |
} | |
return e; | |
}, | |
// this is a horrible workaround for a bug in Android where a single touch triggers two click events | |
_filterClick: function (e, handler) { | |
var timeStamp = (e.timeStamp || e.originalEvent.timeStamp), | |
elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick); | |
// are they closer together than 500ms yet more than 100ms? | |
// Android typically triggers them ~300ms apart while multiple listeners | |
// on the same event should be triggered far faster; | |
// or check if click is simulated on the element, and if it is, reject any non-simulated events | |
if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) { | |
L.DomEvent.stop(e); | |
return; | |
} | |
L.DomEvent._lastClick = timeStamp; | |
return handler(e); | |
} | |
}; | |
L.DomEvent.on = L.DomEvent.addListener; | |
L.DomEvent.off = L.DomEvent.removeListener; | |
/* | |
* L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too. | |
*/ | |
L.Draggable = L.Class.extend({ | |
includes: L.Mixin.Events, | |
statics: { | |
START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'], | |
END: { | |
mousedown: 'mouseup', | |
touchstart: 'touchend', | |
pointerdown: 'touchend', | |
MSPointerDown: 'touchend' | |
}, | |
MOVE: { | |
mousedown: 'mousemove', | |
touchstart: 'touchmove', | |
pointerdown: 'touchmove', | |
MSPointerDown: 'touchmove' | |
} | |
}, | |
initialize: function (element, dragStartTarget) { | |
this._element = element; | |
this._dragStartTarget = dragStartTarget || element; | |
}, | |
enable: function () { | |
if (this._enabled) { return; } | |
for (var i = L.Draggable.START.length - 1; i >= 0; i--) { | |
L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this); | |
} | |
this._enabled = true; | |
}, | |
disable: function () { | |
if (!this._enabled) { return; } | |
for (var i = L.Draggable.START.length - 1; i >= 0; i--) { | |
L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this); | |
} | |
this._enabled = false; | |
this._moved = false; | |
}, | |
_onDown: function (e) { | |
this._moved = false; | |
if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; } | |
L.DomEvent.stopPropagation(e); | |
if (L.Draggable._disabled) { return; } | |
L.DomUtil.disableImageDrag(); | |
L.DomUtil.disableTextSelection(); | |
if (this._moving) { return; } | |
var first = e.touches ? e.touches[0] : e; | |
this._startPoint = new L.Point(first.clientX, first.clientY); | |
this._startPos = this._newPos = L.DomUtil.getPosition(this._element); | |
L.DomEvent | |
.on(document, L.Draggable.MOVE[e.type], this._onMove, this) | |
.on(document, L.Draggable.END[e.type], this._onUp, this); | |
}, | |
_onMove: function (e) { | |
if (e.touches && e.touches.length > 1) { | |
this._moved = true; | |
return; | |
} | |
var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e), | |
newPoint = new L.Point(first.clientX, first.clientY), | |
offset = newPoint.subtract(this._startPoint); | |
if (!offset.x && !offset.y) { return; } | |
if (L.Browser.touch && Math.abs(offset.x) + Math.abs(offset.y) < 3) { return; } | |
L.DomEvent.preventDefault(e); | |
if (!this._moved) { | |
this.fire('dragstart'); | |
this._moved = true; | |
this._startPos = L.DomUtil.getPosition(this._element).subtract(offset); | |
L.DomUtil.addClass(document.body, 'leaflet-dragging'); | |
this._lastTarget = e.target || e.srcElement; | |
L.DomUtil.addClass(this._lastTarget, 'leaflet-drag-target'); | |
} | |
this._newPos = this._startPos.add(offset); | |
this._moving = true; | |
L.Util.cancelAnimFrame(this._animRequest); | |
this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget); | |
}, | |
_updatePosition: function () { | |
this.fire('predrag'); | |
L.DomUtil.setPosition(this._element, this._newPos); | |
this.fire('drag'); | |
}, | |
_onUp: function () { | |
L.DomUtil.removeClass(document.body, 'leaflet-dragging'); | |
if (this._lastTarget) { | |
L.DomUtil.removeClass(this._lastTarget, 'leaflet-drag-target'); | |
this._lastTarget = null; | |
} | |
for (var i in L.Draggable.MOVE) { | |
L.DomEvent | |
.off(document, L.Draggable.MOVE[i], this._onMove) | |
.off(document, L.Draggable.END[i], this._onUp); | |
} | |
L.DomUtil.enableImageDrag(); | |
L.DomUtil.enableTextSelection(); | |
if (this._moved && this._moving) { | |
// ensure drag is not fired after dragend | |
L.Util.cancelAnimFrame(this._animRequest); | |
this.fire('dragend', { | |
distance: this._newPos.distanceTo(this._startPos) | |
}); | |
} | |
this._moving = false; | |
} | |
}); | |
/* | |
L.Handler is a base class for handler classes that are used internally to inject | |
interaction features like dragging to classes like Map and Marker. | |
*/ | |
L.Handler = L.Class.extend({ | |
initialize: function (map) { | |
this._map = map; | |
}, | |
enable: function () { | |
if (this._enabled) { return; } | |
this._enabled = true; | |
this.addHooks(); | |
}, | |
disable: function () { | |
if (!this._enabled) { return; } | |
this._enabled = false; | |
this.removeHooks(); | |
}, | |
enabled: function () { | |
return !!this._enabled; | |
} | |
}); | |
/* | |
* L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default. | |
*/ | |
L.Map.mergeOptions({ | |
dragging: true, | |
inertia: !L.Browser.android23, | |
inertiaDeceleration: 3400, // px/s^2 | |
inertiaMaxSpeed: Infinity, // px/s | |
inertiaThreshold: L.Browser.touch ? 32 : 18, // ms | |
easeLinearity: 0.25, | |
// TODO refactor, move to CRS | |
worldCopyJump: false | |
}); | |
L.Map.Drag = L.Handler.extend({ | |
addHooks: function () { | |
if (!this._draggable) { | |
var map = this._map; | |
this._draggable = new L.Draggable(map._mapPane, map._container); | |
this._draggable.on({ | |
'dragstart': this._onDragStart, | |
'drag': this._onDrag, | |
'dragend': this._onDragEnd | |
}, this); | |
if (map.options.worldCopyJump) { | |
this._draggable.on('predrag', this._onPreDrag, this); | |
map.on('viewreset', this._onViewReset, this); | |
map.whenReady(this._onViewReset, this); | |
} | |
} | |
this._draggable.enable(); | |
}, | |
removeHooks: function () { | |
this._draggable.disable(); | |
}, | |
moved: function () { | |
return this._draggable && this._draggable._moved; | |
}, | |
_onDragStart: function () { | |
var map = this._map; | |
if (map._panAnim) { | |
map._panAnim.stop(); | |
} | |
map | |
.fire('movestart') | |
.fire('dragstart'); | |
if (map.options.inertia) { | |
this._positions = []; | |
this._times = []; | |
} | |
}, | |
_onDrag: function () { | |
if (this._map.options.inertia) { | |
var time = this._lastTime = +new Date(), | |
pos = this._lastPos = this._draggable._newPos; | |
this._positions.push(pos); | |
this._times.push(time); | |
if (time - this._times[0] > 200) { | |
this._positions.shift(); | |
this._times.shift(); | |
} | |
} | |
this._map | |
.fire('move') | |
.fire('drag'); | |
}, | |
_onViewReset: function () { | |
// TODO fix hardcoded Earth values | |
var pxCenter = this._map.getSize()._divideBy(2), | |
pxWorldCenter = this._map.latLngToLayerPoint([0, 0]); | |
this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x; | |
this._worldWidth = this._map.project([0, 180]).x; | |
}, | |
_onPreDrag: function () { | |
// TODO refactor to be able to adjust map pane position after zoom | |
var worldWidth = this._worldWidth, | |
halfWidth = Math.round(worldWidth / 2), | |
dx = this._initialWorldOffset, | |
x = this._draggable._newPos.x, | |
newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx, | |
newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx, | |
newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2; | |
this._draggable._newPos.x = newX; | |
}, | |
_onDragEnd: function (e) { | |
var map = this._map, | |
options = map.options, | |
delay = +new Date() - this._lastTime, | |
noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0]; | |
map.fire('dragend', e); | |
if (noInertia) { | |
map.fire('moveend'); | |
} else { | |
var direction = this._lastPos.subtract(this._positions[0]), | |
duration = (this._lastTime + delay - this._times[0]) / 1000, | |
ease = options.easeLinearity, | |
speedVector = direction.multiplyBy(ease / duration), | |
speed = speedVector.distanceTo([0, 0]), | |
limitedSpeed = Math.min(options.inertiaMaxSpeed, speed), | |
limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed), | |
decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease), | |
offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round(); | |
if (!offset.x || !offset.y) { | |
map.fire('moveend'); | |
} else { | |
offset = map._limitOffset(offset, map.options.maxBounds); | |
L.Util.requestAnimFrame(function () { | |
map.panBy(offset, { | |
duration: decelerationDuration, | |
easeLinearity: ease, | |
noMoveStart: true | |
}); | |
}); | |
} | |
} | |
} | |
}); | |
L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag); | |
/* | |
* L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default. | |
*/ | |
L.Map.mergeOptions({ | |
doubleClickZoom: true | |
}); | |
L.Map.DoubleClickZoom = L.Handler.extend({ | |
addHooks: function () { | |
this._map.on('dblclick', this._onDoubleClick, this); | |
}, | |
removeHooks: function () { | |
this._map.off('dblclick', this._onDoubleClick, this); | |
}, | |
_onDoubleClick: function (e) { | |
var map = this._map, | |
zoom = map.getZoom() + (e.originalEvent.shiftKey ? -1 : 1); | |
if (map.options.doubleClickZoom === 'center') { | |
map.setZoom(zoom); | |
} else { | |
map.setZoomAround(e.containerPoint, zoom); | |
} | |
} | |
}); | |
L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom); | |
/* | |
* L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map. | |
*/ | |
L.Map.mergeOptions({ | |
scrollWheelZoom: true | |
}); | |
L.Map.ScrollWheelZoom = L.Handler.extend({ | |
addHooks: function () { | |
L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this); | |
L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault); | |
this._delta = 0; | |
}, | |
removeHooks: function () { | |
L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll); | |
L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault); | |
}, | |
_onWheelScroll: function (e) { | |
var delta = L.DomEvent.getWheelDelta(e); | |
this._delta += delta; | |
this._lastMousePos = this._map.mouseEventToContainerPoint(e); | |
if (!this._startTime) { | |
this._startTime = +new Date(); | |
} | |
var left = Math.max(40 - (+new Date() - this._startTime), 0); | |
clearTimeout(this._timer); | |
this._timer = setTimeout(L.bind(this._performZoom, this), left); | |
L.DomEvent.preventDefault(e); | |
L.DomEvent.stopPropagation(e); | |
}, | |
_performZoom: function () { | |
var map = this._map, | |
delta = this._delta, | |
zoom = map.getZoom(); | |
delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta); | |
delta = Math.max(Math.min(delta, 4), -4); | |
delta = map._limitZoom(zoom + delta) - zoom; | |
this._delta = 0; | |
this._startTime = null; | |
if (!delta) { return; } | |
if (map.options.scrollWheelZoom === 'center') { | |
map.setZoom(zoom + delta); | |
} else { | |
map.setZoomAround(this._lastMousePos, zoom + delta); | |
} | |
} | |
}); | |
L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom); | |
/* | |
* Extends the event handling code with double tap support for mobile browsers. | |
*/ | |
L.extend(L.DomEvent, { | |
_touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart', | |
_touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend', | |
// inspired by Zepto touch code by Thomas Fuchs | |
addDoubleTapListener: function (obj, handler, id) { | |
var last, | |
doubleTap = false, | |
delay = 250, | |
touch, | |
pre = '_leaflet_', | |
touchstart = this._touchstart, | |
touchend = this._touchend, | |
trackedTouches = []; | |
function onTouchStart(e) { | |
var count; | |
if (L.Browser.pointer) { | |
trackedTouches.push(e.pointerId); | |
count = trackedTouches.length; | |
} else { | |
count = e.touches.length; | |
} | |
if (count > 1) { | |
return; | |
} | |
var now = Date.now(), | |
delta = now - (last || now); | |
touch = e.touches ? e.touches[0] : e; | |
doubleTap = (delta > 0 && delta <= delay); | |
last = now; | |
} | |
function onTouchEnd(e) { | |
if (L.Browser.pointer) { | |
var idx = trackedTouches.indexOf(e.pointerId); | |
if (idx === -1) { | |
return; | |
} | |
trackedTouches.splice(idx, 1); | |
} | |
if (doubleTap) { | |
if (L.Browser.pointer) { | |
// work around .type being readonly with MSPointer* events | |
var newTouch = { }, | |
prop; | |
// jshint forin:false | |
for (var i in touch) { | |
prop = touch[i]; | |
if (typeof prop === 'function') { | |
newTouch[i] = prop.bind(touch); | |
} else { | |
newTouch[i] = prop; | |
} | |
} | |
touch = newTouch; | |
} | |
touch.type = 'dblclick'; | |
handler(touch); | |
last = null; | |
} | |
} | |
obj[pre + touchstart + id] = onTouchStart; | |
obj[pre + touchend + id] = onTouchEnd; | |
// on pointer we need to listen on the document, otherwise a drag starting on the map and moving off screen | |
// will not come through to us, so we will lose track of how many touches are ongoing | |
var endElement = L.Browser.pointer ? document.documentElement : obj; | |
obj.addEventListener(touchstart, onTouchStart, false); | |
endElement.addEventListener(touchend, onTouchEnd, false); | |
if (L.Browser.pointer) { | |
endElement.addEventListener(L.DomEvent.POINTER_CANCEL, onTouchEnd, false); | |
} | |
return this; | |
}, | |
removeDoubleTapListener: function (obj, id) { | |
var pre = '_leaflet_'; | |
obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false); | |
(L.Browser.pointer ? document.documentElement : obj).removeEventListener( | |
this._touchend, obj[pre + this._touchend + id], false); | |
if (L.Browser.pointer) { | |
document.documentElement.removeEventListener(L.DomEvent.POINTER_CANCEL, obj[pre + this._touchend + id], | |
false); | |
} | |
return this; | |
} | |
}); | |
/* | |
* Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices. | |
*/ | |
L.extend(L.DomEvent, { | |
//static | |
POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown', | |
POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove', | |
POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup', | |
POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel', | |
_pointers: [], | |
_pointerDocumentListener: false, | |
// Provides a touch events wrapper for (ms)pointer events. | |
// Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019 | |
//ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890 | |
addPointerListener: function (obj, type, handler, id) { | |
switch (type) { | |
case 'touchstart': | |
return this.addPointerListenerStart(obj, type, handler, id); | |
case 'touchend': | |
return this.addPointerListenerEnd(obj, type, handler, id); | |
case 'touchmove': | |
return this.addPointerListenerMove(obj, type, handler, id); | |
default: | |
throw 'Unknown touch event type'; | |
} | |
}, | |
addPointerListenerStart: function (obj, type, handler, id) { | |
var pre = '_leaflet_', | |
pointers = this._pointers; | |
var cb = function (e) { | |
L.DomEvent.preventDefault(e); | |
var alreadyInArray = false; | |
for (var i = 0; i < pointers.length; i++) { | |
if (pointers[i].pointerId === e.pointerId) { | |
alreadyInArray = true; | |
break; | |
} | |
} | |
if (!alreadyInArray) { | |
pointers.push(e); | |
} | |
e.touches = pointers.slice(); | |
e.changedTouches = [e]; | |
handler(e); | |
}; | |
obj[pre + 'touchstart' + id] = cb; | |
obj.addEventListener(this.POINTER_DOWN, cb, false); | |
// need to also listen for end events to keep the _pointers list accurate | |
// this needs to be on the body and never go away | |
if (!this._pointerDocumentListener) { | |
var internalCb = function (e) { | |
for (var i = 0; i < pointers.length; i++) { | |
if (pointers[i].pointerId === e.pointerId) { | |
pointers.splice(i, 1); | |
break; | |
} | |
} | |
}; | |
//We listen on the documentElement as any drags that end by moving the touch off the screen get fired there | |
document.documentElement.addEventListener(this.POINTER_UP, internalCb, false); | |
document.documentElement.addEventListener(this.POINTER_CANCEL, internalCb, false); | |
this._pointerDocumentListener = true; | |
} | |
return this; | |
}, | |
addPointerListenerMove: function (obj, type, handler, id) { | |
var pre = '_leaflet_', | |
touches = this._pointers; | |
function cb(e) { | |
// don't fire touch moves when mouse isn't down | |
if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; } | |
for (var i = 0; i < touches.length; i++) { | |
if (touches[i].pointerId === e.pointerId) { | |
touches[i] = e; | |
break; | |
} | |
} | |
e.touches = touches.slice(); | |
e.changedTouches = [e]; | |
handler(e); | |
} | |
obj[pre + 'touchmove' + id] = cb; | |
obj.addEventListener(this.POINTER_MOVE, cb, false); | |
return this; | |
}, | |
addPointerListenerEnd: function (obj, type, handler, id) { | |
var pre = '_leaflet_', | |
touches = this._pointers; | |
var cb = function (e) { | |
for (var i = 0; i < touches.length; i++) { | |
if (touches[i].pointerId === e.pointerId) { | |
touches.splice(i, 1); | |
break; | |
} | |
} | |
e.touches = touches.slice(); | |
e.changedTouches = [e]; | |
handler(e); | |
}; | |
obj[pre + 'touchend' + id] = cb; | |
obj.addEventListener(this.POINTER_UP, cb, false); | |
obj.addEventListener(this.POINTER_CANCEL, cb, false); | |
return this; | |
}, | |
removePointerListener: function (obj, type, id) { | |
var pre = '_leaflet_', | |
cb = obj[pre + type + id]; | |
switch (type) { | |
case 'touchstart': | |
obj.removeEventListener(this.POINTER_DOWN, cb, false); | |
break; | |
case 'touchmove': | |
obj.removeEventListener(this.POINTER_MOVE, cb, false); | |
break; | |
case 'touchend': | |
obj.removeEventListener(this.POINTER_UP, cb, false); | |
obj.removeEventListener(this.POINTER_CANCEL, cb, false); | |
break; | |
} | |
return this; | |
} | |
}); | |
/* | |
* L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers. | |
*/ | |
L.Map.mergeOptions({ | |
touchZoom: L.Browser.touch && !L.Browser.android23, | |
bounceAtZoomLimits: true | |
}); | |
L.Map.TouchZoom = L.Handler.extend({ | |
addHooks: function () { | |
L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this); | |
}, | |
removeHooks: function () { | |
L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this); | |
}, | |
_onTouchStart: function (e) { | |
var map = this._map; | |
if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; } | |
var p1 = map.mouseEventToLayerPoint(e.touches[0]), | |
p2 = map.mouseEventToLayerPoint(e.touches[1]), | |
viewCenter = map._getCenterLayerPoint(); | |
this._startCenter = p1.add(p2)._divideBy(2); | |
this._startDist = p1.distanceTo(p2); | |
this._moved = false; | |
this._zooming = true; | |
this._centerOffset = viewCenter.subtract(this._startCenter); | |
if (map._panAnim) { | |
map._panAnim.stop(); | |
} | |
L.DomEvent | |
.on(document, 'touchmove', this._onTouchMove, this) | |
.on(document, 'touchend', this._onTouchEnd, this); | |
L.DomEvent.preventDefault(e); | |
}, | |
_onTouchMove: function (e) { | |
var map = this._map; | |
if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; } | |
var p1 = map.mouseEventToLayerPoint(e.touches[0]), | |
p2 = map.mouseEventToLayerPoint(e.touches[1]); | |
this._scale = p1.distanceTo(p2) / this._startDist; | |
this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter); | |
if (this._scale === 1) { return; } | |
if (!map.options.bounceAtZoomLimits) { | |
if ((map.getZoom() === map.getMinZoom() && this._scale < 1) || | |
(map.getZoom() === map.getMaxZoom() && this._scale > 1)) { return; } | |
} | |
if (!this._moved) { | |
L.DomUtil.addClass(map._mapPane, 'leaflet-touching'); | |
map | |
.fire('movestart') | |
.fire('zoomstart'); | |
this._moved = true; | |
} | |
L.Util.cancelAnimFrame(this._animRequest); | |
this._animRequest = L.Util.requestAnimFrame( | |
this._updateOnMove, this, true, this._map._container); | |
L.DomEvent.preventDefault(e); | |
}, | |
_updateOnMove: function () { | |
var map = this._map, | |
origin = this._getScaleOrigin(), | |
center = map.layerPointToLatLng(origin), | |
zoom = map.getScaleZoom(this._scale); | |
map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta, false, true); | |
}, | |
_onTouchEnd: function () { | |
if (!this._moved || !this._zooming) { | |
this._zooming = false; | |
return; | |
} | |
var map = this._map; | |
this._zooming = false; | |
L.DomUtil.removeClass(map._mapPane, 'leaflet-touching'); | |
L.Util.cancelAnimFrame(this._animRequest); | |
L.DomEvent | |
.off(document, 'touchmove', this._onTouchMove) | |
.off(document, 'touchend', this._onTouchEnd); | |
var origin = this._getScaleOrigin(), | |
center = map.layerPointToLatLng(origin), | |
oldZoom = map.getZoom(), | |
floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom, | |
roundZoomDelta = (floatZoomDelta > 0 ? | |
Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)), | |
zoom = map._limitZoom(oldZoom + roundZoomDelta), | |
scale = map.getZoomScale(zoom) / this._scale; | |
map._animateZoom(center, zoom, origin, scale); | |
}, | |
_getScaleOrigin: function () { | |
var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale); | |
return this._startCenter.add(centerOffset); | |
} | |
}); | |
L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom); | |
/* | |
* L.Map.Tap is used to enable mobile hacks like quick taps and long hold. | |
*/ | |
L.Map.mergeOptions({ | |
tap: true, | |
tapTolerance: 15 | |
}); | |
L.Map.Tap = L.Handler.extend({ | |
addHooks: function () { | |
L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this); | |
}, | |
removeHooks: function () { | |
L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this); | |
}, | |
_onDown: function (e) { | |
if (!e.touches) { return; } | |
L.DomEvent.preventDefault(e); | |
this._fireClick = true; | |
// don't simulate click or track longpress if more than 1 touch | |
if (e.touches.length > 1) { | |
this._fireClick = false; | |
clearTimeout(this._holdTimeout); | |
return; | |
} | |
var first = e.touches[0], | |
el = first.target; | |
this._startPos = this._newPos = new L.Point(first.clientX, first.clientY); | |
// if touching a link, highlight it | |
if (el.tagName && el.tagName.toLowerCase() === 'a') { | |
L.DomUtil.addClass(el, 'leaflet-active'); | |
} | |
// simulate long hold but setting a timeout | |
this._holdTimeout = setTimeout(L.bind(function () { | |
if (this._isTapValid()) { | |
this._fireClick = false; | |
this._onUp(); | |
this._simulateEvent('contextmenu', first); | |
} | |
}, this), 1000); | |
L.DomEvent | |
.on(document, 'touchmove', this._onMove, this) | |
.on(document, 'touchend', this._onUp, this); | |
}, | |
_onUp: function (e) { | |
clearTimeout(this._holdTimeout); | |
L.DomEvent | |
.off(document, 'touchmove', this._onMove, this) | |
.off(document, 'touchend', this._onUp, this); | |
if (this._fireClick && e && e.changedTouches) { | |
var first = e.changedTouches[0], | |
el = first.target; | |
if (el && el.tagName && el.tagName.toLowerCase() === 'a') { | |
L.DomUtil.removeClass(el, 'leaflet-active'); | |
} | |
// simulate click if the touch didn't move too much | |
if (this._isTapValid()) { | |
this._simulateEvent('click', first); | |
} | |
} | |
}, | |
_isTapValid: function () { | |
return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance; | |
}, | |
_onMove: function (e) { | |
var first = e.touches[0]; | |
this._newPos = new L.Point(first.clientX, first.clientY); | |
}, | |
_simulateEvent: function (type, e) { | |
var simulatedEvent = document.createEvent('MouseEvents'); | |
simulatedEvent._simulated = true; | |
e.target._simulatedClick = true; | |
simulatedEvent.initMouseEvent( | |
type, true, true, window, 1, | |
e.screenX, e.screenY, | |
e.clientX, e.clientY, | |
false, false, false, false, 0, null); | |
e.target.dispatchEvent(simulatedEvent); | |
} | |
}); | |
if (L.Browser.touch && !L.Browser.pointer) { | |
L.Map.addInitHook('addHandler', 'tap', L.Map.Tap); | |
} | |
/* | |
* L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map | |
* (zoom to a selected bounding box), enabled by default. | |
*/ | |
L.Map.mergeOptions({ | |
boxZoom: true | |
}); | |
L.Map.BoxZoom = L.Handler.extend({ | |
initialize: function (map) { | |
this._map = map; | |
this._container = map._container; | |
this._pane = map._panes.overlayPane; | |
this._moved = false; | |
}, | |
addHooks: function () { | |
L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this); | |
}, | |
removeHooks: function () { | |
L.DomEvent.off(this._container, 'mousedown', this._onMouseDown); | |
this._moved = false; | |
}, | |
moved: function () { | |
return this._moved; | |
}, | |
_onMouseDown: function (e) { | |
this._moved = false; | |
if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; } | |
L.DomUtil.disableTextSelection(); | |
L.DomUtil.disableImageDrag(); | |
this._startLayerPoint = this._map.mouseEventToLayerPoint(e); | |
L.DomEvent | |
.on(document, 'mousemove', this._onMouseMove, this) | |
.on(document, 'mouseup', this._onMouseUp, this) | |
.on(document, 'keydown', this._onKeyDown, this); | |
}, | |
_onMouseMove: function (e) { | |
if (!this._moved) { | |
this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane); | |
L.DomUtil.setPosition(this._box, this._startLayerPoint); | |
//TODO refactor: move cursor to styles | |
this._container.style.cursor = 'crosshair'; | |
this._map.fire('boxzoomstart'); | |
} | |
var startPoint = this._startLayerPoint, | |
box = this._box, | |
layerPoint = this._map.mouseEventToLayerPoint(e), | |
offset = layerPoint.subtract(startPoint), | |
newPos = new L.Point( | |
Math.min(layerPoint.x, startPoint.x), | |
Math.min(layerPoint.y, startPoint.y)); | |
L.DomUtil.setPosition(box, newPos); | |
this._moved = true; | |
// TODO refactor: remove hardcoded 4 pixels | |
box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px'; | |
box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px'; | |
}, | |
_finish: function () { | |
if (this._moved) { | |
this._pane.removeChild(this._box); | |
this._container.style.cursor = ''; | |
} | |
L.DomUtil.enableTextSelection(); | |
L.DomUtil.enableImageDrag(); | |
L.DomEvent | |
.off(document, 'mousemove', this._onMouseMove) | |
.off(document, 'mouseup', this._onMouseUp) | |
.off(document, 'keydown', this._onKeyDown); | |
}, | |
_onMouseUp: function (e) { | |
this._finish(); | |
var map = this._map, | |
layerPoint = map.mouseEventToLayerPoint(e); | |
if (this._startLayerPoint.equals(layerPoint)) { return; } | |
var bounds = new L.LatLngBounds( | |
map.layerPointToLatLng(this._startLayerPoint), | |
map.layerPointToLatLng(layerPoint)); | |
map.fitBounds(bounds); | |
map.fire('boxzoomend', { | |
boxZoomBounds: bounds | |
}); | |
}, | |
_onKeyDown: function (e) { | |
if (e.keyCode === 27) { | |
this._finish(); | |
} | |
} | |
}); | |
L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom); | |
/* | |
* L.Map.Keyboard is handling keyboard interaction with the map, enabled by default. | |
*/ | |
L.Map.mergeOptions({ | |
keyboard: true, | |
keyboardPanOffset: 80, | |
keyboardZoomOffset: 1 | |
}); | |
L.Map.Keyboard = L.Handler.extend({ | |
keyCodes: { | |
left: [37], | |
right: [39], | |
down: [40], | |
up: [38], | |
zoomIn: [187, 107, 61, 171], | |
zoomOut: [189, 109, 173] | |
}, | |
initialize: function (map) { | |
this._map = map; | |
this._setPanOffset(map.options.keyboardPanOffset); | |
this._setZoomOffset(map.options.keyboardZoomOffset); | |
}, | |
addHooks: function () { | |
var container = this._map._container; | |
// make the container focusable by tabbing | |
if (container.tabIndex === -1) { | |
container.tabIndex = '0'; | |
} | |
L.DomEvent | |
.on(container, 'focus', this._onFocus, this) | |
.on(container, 'blur', this._onBlur, this) | |
.on(container, 'mousedown', this._onMouseDown, this); | |
this._map | |
.on('focus', this._addHooks, this) | |
.on('blur', this._removeHooks, this); | |
}, | |
removeHooks: function () { | |
this._removeHooks(); | |
var container = this._map._container; | |
L.DomEvent | |
.off(container, 'focus', this._onFocus, this) | |
.off(container, 'blur', this._onBlur, this) | |
.off(container, 'mousedown', this._onMouseDown, this); | |
this._map | |
.off('focus', this._addHooks, this) | |
.off('blur', this._removeHooks, this); | |
}, | |
_onMouseDown: function () { | |
if (this._focused) { return; } | |
var body = document.body, | |
docEl = document.documentElement, | |
top = body.scrollTop || docEl.scrollTop, | |
left = body.scrollLeft || docEl.scrollLeft; | |
this._map._container.focus(); | |
window.scrollTo(left, top); | |
}, | |
_onFocus: function () { | |
this._focused = true; | |
this._map.fire('focus'); | |
}, | |
_onBlur: function () { | |
this._focused = false; | |
this._map.fire('blur'); | |
}, | |
_setPanOffset: function (pan) { | |
var keys = this._panKeys = {}, | |
codes = this.keyCodes, | |
i, len; | |
for (i = 0, len = codes.left.length; i < len; i++) { | |
keys[codes.left[i]] = [-1 * pan, 0]; | |
} | |
for (i = 0, len = codes.right.length; i < len; i++) { | |
keys[codes.right[i]] = [pan, 0]; | |
} | |
for (i = 0, len = codes.down.length; i < len; i++) { | |
keys[codes.down[i]] = [0, pan]; | |
} | |
for (i = 0, len = codes.up.length; i < len; i++) { | |
keys[codes.up[i]] = [0, -1 * pan]; | |
} | |
}, | |
_setZoomOffset: function (zoom) { | |
var keys = this._zoomKeys = {}, | |
codes = this.keyCodes, | |
i, len; | |
for (i = 0, len = codes.zoomIn.length; i < len; i++) { | |
keys[codes.zoomIn[i]] = zoom; | |
} | |
for (i = 0, len = codes.zoomOut.length; i < len; i++) { | |
keys[codes.zoomOut[i]] = -zoom; | |
} | |
}, | |
_addHooks: function () { | |
L.DomEvent.on(document, 'keydown', this._onKeyDown, this); | |
}, | |
_removeHooks: function () { | |
L.DomEvent.off(document, 'keydown', this._onKeyDown, this); | |
}, | |
_onKeyDown: function (e) { | |
var key = e.keyCode, | |
map = this._map; | |
if (key in this._panKeys) { | |
if (map._panAnim && map._panAnim._inProgress) { return; } | |
map.panBy(this._panKeys[key]); | |
if (map.options.maxBounds) { | |
map.panInsideBounds(map.options.maxBounds); | |
} | |
} else if (key in this._zoomKeys) { | |
map.setZoom(map.getZoom() + this._zoomKeys[key]); | |
} else { | |
return; | |
} | |
L.DomEvent.stop(e); | |
} | |
}); | |
L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard); | |
/* | |
* L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable. | |
*/ | |
L.Handler.MarkerDrag = L.Handler.extend({ | |
initialize: function (marker) { | |
this._marker = marker; | |
}, | |
addHooks: function () { | |
var icon = this._marker._icon; | |
if (!this._draggable) { | |
this._draggable = new L.Draggable(icon, icon); | |
} | |
this._draggable | |
.on('dragstart', this._onDragStart, this) | |
.on('drag', this._onDrag, this) | |
.on('dragend', this._onDragEnd, this); | |
this._draggable.enable(); | |
L.DomUtil.addClass(this._marker._icon, 'leaflet-marker-draggable'); | |
}, | |
removeHooks: function () { | |
this._draggable | |
.off('dragstart', this._onDragStart, this) | |
.off('drag', this._onDrag, this) | |
.off('dragend', this._onDragEnd, this); | |
this._draggable.disable(); | |
L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable'); | |
}, | |
moved: function () { | |
return this._draggable && this._draggable._moved; | |
}, | |
_onDragStart: function () { | |
this._marker | |
.closePopup() | |
.fire('movestart') | |
.fire('dragstart'); | |
}, | |
_onDrag: function () { | |
var marker = this._marker, | |
shadow = marker._shadow, | |
iconPos = L.DomUtil.getPosition(marker._icon), | |
latlng = marker._map.layerPointToLatLng(iconPos); | |
// update shadow position | |
if (shadow) { | |
L.DomUtil.setPosition(shadow, iconPos); | |
} | |
marker._latlng = latlng; | |
marker | |
.fire('move', {latlng: latlng}) | |
.fire('drag'); | |
}, | |
_onDragEnd: function (e) { | |
this._marker | |
.fire('moveend') | |
.fire('dragend', e); | |
} | |
}); | |
/* | |
* L.Control is a base class for implementing map controls. Handles positioning. | |
* All other controls extend from this class. | |
*/ | |
L.Control = L.Class.extend({ | |
options: { | |
position: 'topright' | |
}, | |
initialize: function (options) { | |
L.setOptions(this, options); | |
}, | |
getPosition: function () { | |
return this.options.position; | |
}, | |
setPosition: function (position) { | |
var map = this._map; | |
if (map) { | |
map.removeControl(this); | |
} | |
this.options.position = position; | |
if (map) { | |
map.addControl(this); | |
} | |
return this; | |
}, | |
getContainer: function () { | |
return this._container; | |
}, | |
addTo: function (map) { | |
this._map = map; | |
var container = this._container = this.onAdd(map), | |
pos = this.getPosition(), | |
corner = map._controlCorners[pos]; | |
L.DomUtil.addClass(container, 'leaflet-control'); | |
if (pos.indexOf('bottom') !== -1) { | |
corner.insertBefore(container, corner.firstChild); | |
} else { | |
corner.appendChild(container); | |
} | |
return this; | |
}, | |
removeFrom: function (map) { | |
var pos = this.getPosition(), | |
corner = map._controlCorners[pos]; | |
corner.removeChild(this._container); | |
this._map = null; | |
if (this.onRemove) { | |
this.onRemove(map); | |
} | |
return this; | |
}, | |
_refocusOnMap: function () { | |
if (this._map) { | |
this._map.getContainer().focus(); | |
} | |
} | |
}); | |
L.control = function (options) { | |
return new L.Control(options); | |
}; | |
// adds control-related methods to L.Map | |
L.Map.include({ | |
addControl: function (control) { | |
control.addTo(this); | |
return this; | |
}, | |
removeControl: function (control) { | |
control.removeFrom(this); | |
return this; | |
}, | |
_initControlPos: function () { | |
var corners = this._controlCorners = {}, | |
l = 'leaflet-', | |
container = this._controlContainer = | |
L.DomUtil.create('div', l + 'control-container', this._container); | |
function createCorner(vSide, hSide) { | |
var className = l + vSide + ' ' + l + hSide; | |
corners[vSide + hSide] = L.DomUtil.create('div', className, container); | |
} | |
createCorner('top', 'left'); | |
createCorner('top', 'right'); | |
createCorner('bottom', 'left'); | |
createCorner('bottom', 'right'); | |
}, | |
_clearControlPos: function () { | |
this._container.removeChild(this._controlContainer); | |
} | |
}); | |
/* | |
* L.Control.Zoom is used for the default zoom buttons on the map. | |
*/ | |
L.Control.Zoom = L.Control.extend({ | |
options: { | |
position: 'topleft', | |
zoomInText: '+', | |
zoomInTitle: 'Zoom in', | |
zoomOutText: '-', | |
zoomOutTitle: 'Zoom out' | |
}, | |
onAdd: function (map) { | |
var zoomName = 'leaflet-control-zoom', | |
container = L.DomUtil.create('div', zoomName + ' leaflet-bar'); | |
this._map = map; | |
this._zoomInButton = this._createButton( | |
this.options.zoomInText, this.options.zoomInTitle, | |
zoomName + '-in', container, this._zoomIn, this); | |
this._zoomOutButton = this._createButton( | |
this.options.zoomOutText, this.options.zoomOutTitle, | |
zoomName + '-out', container, this._zoomOut, this); | |
this._updateDisabled(); | |
map.on('zoomend zoomlevelschange', this._updateDisabled, this); | |
return container; | |
}, | |
onRemove: function (map) { | |
map.off('zoomend zoomlevelschange', this._updateDisabled, this); | |
}, | |
_zoomIn: function (e) { | |
this._map.zoomIn(e.shiftKey ? 3 : 1); | |
}, | |
_zoomOut: function (e) { | |
this._map.zoomOut(e.shiftKey ? 3 : 1); | |
}, | |
_createButton: function (html, title, className, container, fn, context) { | |
var link = L.DomUtil.create('a', className, container); | |
link.innerHTML = html; | |
link.href = '#'; | |
link.title = title; | |
var stop = L.DomEvent.stopPropagation; | |
L.DomEvent | |
.on(link, 'click', stop) | |
.on(link, 'mousedown', stop) | |
.on(link, 'dblclick', stop) | |
.on(link, 'click', L.DomEvent.preventDefault) | |
.on(link, 'click', fn, context) | |
.on(link, 'click', this._refocusOnMap, context); | |
return link; | |
}, | |
_updateDisabled: function () { | |
var map = this._map, | |
className = 'leaflet-disabled'; | |
L.DomUtil.removeClass(this._zoomInButton, className); | |
L.DomUtil.removeClass(this._zoomOutButton, className); | |
if (map._zoom === map.getMinZoom()) { | |
L.DomUtil.addClass(this._zoomOutButton, className); | |
} | |
if (map._zoom === map.getMaxZoom()) { | |
L.DomUtil.addClass(this._zoomInButton, className); | |
} | |
} | |
}); | |
L.Map.mergeOptions({ | |
zoomControl: true | |
}); | |
L.Map.addInitHook(function () { | |
if (this.options.zoomControl) { | |
this.zoomControl = new L.Control.Zoom(); | |
this.addControl(this.zoomControl); | |
} | |
}); | |
L.control.zoom = function (options) { | |
return new L.Control.Zoom(options); | |
}; | |
/* | |
* L.Control.Attribution is used for displaying attribution on the map (added by default). | |
*/ | |
L.Control.Attribution = L.Control.extend({ | |
options: { | |
position: 'bottomright', | |
prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>' | |
}, | |
initialize: function (options) { | |
L.setOptions(this, options); | |
this._attributions = {}; | |
}, | |
onAdd: function (map) { | |
this._container = L.DomUtil.create('div', 'leaflet-control-attribution'); | |
L.DomEvent.disableClickPropagation(this._container); | |
for (var i in map._layers) { | |
if (map._layers[i].getAttribution) { | |
this.addAttribution(map._layers[i].getAttribution()); | |
} | |
} | |
map | |
.on('layeradd', this._onLayerAdd, this) | |
.on('layerremove', this._onLayerRemove, this); | |
this._update(); | |
return this._container; | |
}, | |
onRemove: function (map) { | |
map | |
.off('layeradd', this._onLayerAdd) | |
.off('layerremove', this._onLayerRemove); | |
}, | |
setPrefix: function (prefix) { | |
this.options.prefix = prefix; | |
this._update(); | |
return this; | |
}, | |
addAttribution: function (text) { | |
if (!text) { return; } | |
if (!this._attributions[text]) { | |
this._attributions[text] = 0; | |
} | |
this._attributions[text]++; | |
this._update(); | |
return this; | |
}, | |
removeAttribution: function (text) { | |
if (!text) { return; } | |
if (this._attributions[text]) { | |
this._attributions[text]--; | |
this._update(); | |
} | |
return this; | |
}, | |
_update: function () { | |
if (!this._map) { return; } | |
var attribs = []; | |
for (var i in this._attributions) { | |
if (this._attributions[i]) { | |
attribs.push(i); | |
} | |
} | |
var prefixAndAttribs = []; | |
if (this.options.prefix) { | |
prefixAndAttribs.push(this.options.prefix); | |
} | |
if (attribs.length) { | |
prefixAndAttribs.push(attribs.join(', ')); | |
} | |
this._container.innerHTML = prefixAndAttribs.join(' | '); | |
}, | |
_onLayerAdd: function (e) { | |
if (e.layer.getAttribution) { | |
this.addAttribution(e.layer.getAttribution()); | |
} | |
}, | |
_onLayerRemove: function (e) { | |
if (e.layer.getAttribution) { | |
this.removeAttribution(e.layer.getAttribution()); | |
} | |
} | |
}); | |
L.Map.mergeOptions({ | |
attributionControl: true | |
}); | |
L.Map.addInitHook(function () { | |
if (this.options.attributionControl) { | |
this.attributionControl = (new L.Control.Attribution()).addTo(this); | |
} | |
}); | |
L.control.attribution = function (options) { | |
return new L.Control.Attribution(options); | |
}; | |
/* | |
* L.Control.Scale is used for displaying metric/imperial scale on the map. | |
*/ | |
L.Control.Scale = L.Control.extend({ | |
options: { | |
position: 'bottomleft', | |
maxWidth: 100, | |
metric: true, | |
imperial: true, | |
updateWhenIdle: false | |
}, | |
onAdd: function (map) { | |
this._map = map; | |
var className = 'leaflet-control-scale', | |
container = L.DomUtil.create('div', className), | |
options = this.options; | |
this._addScales(options, className, container); | |
map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this); | |
map.whenReady(this._update, this); | |
return container; | |
}, | |
onRemove: function (map) { | |
map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this); | |
}, | |
_addScales: function (options, className, container) { | |
if (options.metric) { | |
this._mScale = L.DomUtil.create('div', className + '-line', container); | |
} | |
if (options.imperial) { | |
this._iScale = L.DomUtil.create('div', className + '-line', container); | |
} | |
}, | |
_update: function () { | |
var bounds = this._map.getBounds(), | |
centerLat = bounds.getCenter().lat, | |
halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180), | |
dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180, | |
size = this._map.getSize(), | |
options = this.options, | |
maxMeters = 0; | |
if (size.x > 0) { | |
maxMeters = dist * (options.maxWidth / size.x); | |
} | |
this._updateScales(options, maxMeters); | |
}, | |
_updateScales: function (options, maxMeters) { | |
if (options.metric && maxMeters) { | |
this._updateMetric(maxMeters); | |
} | |
if (options.imperial && maxMeters) { | |
this._updateImperial(maxMeters); | |
} | |
}, | |
_updateMetric: function (maxMeters) { | |
var meters = this._getRoundNum(maxMeters); | |
this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px'; | |
this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km'; | |
}, | |
_updateImperial: function (maxMeters) { | |
var maxFeet = maxMeters * 3.2808399, | |
scale = this._iScale, | |
maxMiles, miles, feet; | |
if (maxFeet > 5280) { | |
maxMiles = maxFeet / 5280; | |
miles = this._getRoundNum(maxMiles); | |
scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px'; | |
scale.innerHTML = miles + ' mi'; | |
} else { | |
feet = this._getRoundNum(maxFeet); | |
scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px'; | |
scale.innerHTML = feet + ' ft'; | |
} | |
}, | |
_getScaleWidth: function (ratio) { | |
return Math.round(this.options.maxWidth * ratio) - 10; | |
}, | |
_getRoundNum: function (num) { | |
var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1), | |
d = num / pow10; | |
d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1; | |
return pow10 * d; | |
} | |
}); | |
L.control.scale = function (options) { | |
return new L.Control.Scale(options); | |
}; | |
/* | |
* L.Control.Layers is a control to allow users to switch between different layers on the map. | |
*/ | |
L.Control.Layers = L.Control.extend({ | |
options: { | |
collapsed: true, | |
position: 'topright', | |
autoZIndex: true | |
}, | |
initialize: function (baseLayers, overlays, options) { | |
L.setOptions(this, options); | |
this._layers = {}; | |
this._lastZIndex = 0; | |
this._handlingClick = false; | |
for (var i in baseLayers) { | |
this._addLayer(baseLayers[i], i); | |
} | |
for (i in overlays) { | |
this._addLayer(overlays[i], i, true); | |
} | |
}, | |
onAdd: function (map) { | |
this._initLayout(); | |
this._update(); | |
map | |
.on('layeradd', this._onLayerChange, this) | |
.on('layerremove', this._onLayerChange, this); | |
return this._container; | |
}, | |
onRemove: function (map) { | |
map | |
.off('layeradd', this._onLayerChange, this) | |
.off('layerremove', this._onLayerChange, this); | |
}, | |
addBaseLayer: function (layer, name) { | |
this._addLayer(layer, name); | |
this._update(); | |
return this; | |
}, | |
addOverlay: function (layer, name) { | |
this._addLayer(layer, name, true); | |
this._update(); | |
return this; | |
}, | |
removeLayer: function (layer) { | |
var id = L.stamp(layer); | |
delete this._layers[id]; | |
this._update(); | |
return this; | |
}, | |
_initLayout: function () { | |
var className = 'leaflet-control-layers', | |
container = this._container = L.DomUtil.create('div', className); | |
//Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released | |
container.setAttribute('aria-haspopup', true); | |
if (!L.Browser.touch) { | |
L.DomEvent | |
.disableClickPropagation(container) | |
.disableScrollPropagation(container); | |
} else { | |
L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation); | |
} | |
var form = this._form = L.DomUtil.create('form', className + '-list'); | |
if (this.options.collapsed) { | |
if (!L.Browser.android) { | |
L.DomEvent | |
.on(container, 'mouseover', this._expand, this) | |
.on(container, 'mouseout', this._collapse, this); | |
} | |
var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container); | |
link.href = '#'; | |
link.title = 'Layers'; | |
if (L.Browser.touch) { | |
L.DomEvent | |
.on(link, 'click', L.DomEvent.stop) | |
.on(link, 'click', this._expand, this); | |
} | |
else { | |
L.DomEvent.on(link, 'focus', this._expand, this); | |
} | |
//Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033 | |
L.DomEvent.on(form, 'click', function () { | |
setTimeout(L.bind(this._onInputClick, this), 0); | |
}, this); | |
this._map.on('click', this._collapse, this); | |
// TODO keyboard accessibility | |
} else { | |
this._expand(); | |
} | |
this._baseLayersList = L.DomUtil.create('div', className + '-base', form); | |
this._separator = L.DomUtil.create('div', className + '-separator', form); | |
this._overlaysList = L.DomUtil.create('div', className + '-overlays', form); | |
container.appendChild(form); | |
}, | |
_addLayer: function (layer, name, overlay) { | |
var id = L.stamp(layer); | |
this._layers[id] = { | |
layer: layer, | |
name: name, | |
overlay: overlay | |
}; | |
if (this.options.autoZIndex && layer.setZIndex) { | |
this._lastZIndex++; | |
layer.setZIndex(this._lastZIndex); | |
} | |
}, | |
_update: function () { | |
if (!this._container) { | |
return; | |
} | |
this._baseLayersList.innerHTML = ''; | |
this._overlaysList.innerHTML = ''; | |
var baseLayersPresent = false, | |
overlaysPresent = false, | |
i, obj; | |
for (i in this._layers) { | |
obj = this._layers[i]; | |
this._addItem(obj); | |
overlaysPresent = overlaysPresent || obj.overlay; | |
baseLayersPresent = baseLayersPresent || !obj.overlay; | |
} | |
this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none'; | |
}, | |
_onLayerChange: function (e) { | |
var obj = this._layers[L.stamp(e.layer)]; | |
if (!obj) { return; } | |
if (!this._handlingClick) { | |
this._update(); | |
} | |
var type = obj.overlay ? | |
(e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') : | |
(e.type === 'layeradd' ? 'baselayerchange' : null); | |
if (type) { | |
this._map.fire(type, obj); | |
} | |
}, | |
// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe) | |
_createRadioElement: function (name, checked) { | |
var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"'; | |
if (checked) { | |
radioHtml += ' checked="checked"'; | |
} | |
radioHtml += '/>'; | |
var radioFragment = document.createElement('div'); | |
radioFragment.innerHTML = radioHtml; | |
return radioFragment.firstChild; | |
}, | |
_addItem: function (obj) { | |
var label = document.createElement('label'), | |
input, | |
checked = this._map.hasLayer(obj.layer); | |
if (obj.overlay) { | |
input = document.createElement('input'); | |
input.type = 'checkbox'; | |
input.className = 'leaflet-control-layers-selector'; | |
input.defaultChecked = checked; | |
} else { | |
input = this._createRadioElement('leaflet-base-layers', checked); | |
} | |
input.layerId = L.stamp(obj.layer); | |
L.DomEvent.on(input, 'click', this._onInputClick, this); | |
var name = document.createElement('span'); | |
name.innerHTML = ' ' + obj.name; | |
label.appendChild(input); | |
label.appendChild(name); | |
var container = obj.overlay ? this._overlaysList : this._baseLayersList; | |
container.appendChild(label); | |
return label; | |
}, | |
_onInputClick: function () { | |
var i, input, obj, | |
inputs = this._form.getElementsByTagName('input'), | |
inputsLen = inputs.length; | |
this._handlingClick = true; | |
for (i = 0; i < inputsLen; i++) { | |
input = inputs[i]; | |
obj = this._layers[input.layerId]; | |
if (input.checked && !this._map.hasLayer(obj.layer)) { | |
this._map.addLayer(obj.layer); | |
} else if (!input.checked && this._map.hasLayer(obj.layer)) { | |
this._map.removeLayer(obj.layer); | |
} | |
} | |
this._handlingClick = false; | |
this._refocusOnMap(); | |
}, | |
_expand: function () { | |
L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded'); | |
}, | |
_collapse: function () { | |
this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', ''); | |
} | |
}); | |
L.control.layers = function (baseLayers, overlays, options) { | |
return new L.Control.Layers(baseLayers, overlays, options); | |
}; | |
/* | |
* L.PosAnimation is used by Leaflet internally for pan animations. | |
*/ | |
L.PosAnimation = L.Class.extend({ | |
includes: L.Mixin.Events, | |
run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number]) | |
this.stop(); | |
this._el = el; | |
this._inProgress = true; | |
this._newPos = newPos; | |
this.fire('start'); | |
el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) + | |
's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)'; | |
L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this); | |
L.DomUtil.setPosition(el, newPos); | |
// toggle reflow, Chrome flickers for some reason if you don't do this | |
L.Util.falseFn(el.offsetWidth); | |
// there's no native way to track value updates of transitioned properties, so we imitate this | |
this._stepTimer = setInterval(L.bind(this._onStep, this), 50); | |
}, | |
stop: function () { | |
if (!this._inProgress) { return; } | |
// if we just removed the transition property, the element would jump to its final position, | |
// so we need to make it stay at the current position | |
L.DomUtil.setPosition(this._el, this._getPos()); | |
this._onTransitionEnd(); | |
L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation | |
}, | |
_onStep: function () { | |
var stepPos = this._getPos(); | |
if (!stepPos) { | |
this._onTransitionEnd(); | |
return; | |
} | |
// jshint camelcase: false | |
// make L.DomUtil.getPosition return intermediate position value during animation | |
this._el._leaflet_pos = stepPos; | |
this.fire('step'); | |
}, | |
// you can't easily get intermediate values of properties animated with CSS3 Transitions, | |
// we need to parse computed style (in case of transform it returns matrix string) | |
_transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/, | |
_getPos: function () { | |
var left, top, matches, | |
el = this._el, | |
style = window.getComputedStyle(el); | |
if (L.Browser.any3d) { | |
matches = style[L.DomUtil.TRANSFORM].match(this._transformRe); | |
if (!matches) { return; } | |
left = parseFloat(matches[1]); | |
top = parseFloat(matches[2]); | |
} else { | |
left = parseFloat(style.left); | |
top = parseFloat(style.top); | |
} | |
return new L.Point(left, top, true); | |
}, | |
_onTransitionEnd: function () { | |
L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this); | |
if (!this._inProgress) { return; } | |
this._inProgress = false; | |
this._el.style[L.DomUtil.TRANSITION] = ''; | |
// jshint camelcase: false | |
// make sure L.DomUtil.getPosition returns the final position value after animation | |
this._el._leaflet_pos = this._newPos; | |
clearInterval(this._stepTimer); | |
this.fire('step').fire('end'); | |
} | |
}); | |
/* | |
* Extends L.Map to handle panning animations. | |
*/ | |
L.Map.include({ | |
setView: function (center, zoom, options) { | |
zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom); | |
center = this._limitCenter(L.latLng(center), zoom, this.options.maxBounds); | |
options = options || {}; | |
if (this._panAnim) { | |
this._panAnim.stop(); | |
} | |
if (this._loaded && !options.reset && options !== true) { | |
if (options.animate !== undefined) { | |
options.zoom = L.extend({animate: options.animate}, options.zoom); | |
options.pan = L.extend({animate: options.animate}, options.pan); | |
} | |
// try animating pan or zoom | |
var animated = (this._zoom !== zoom) ? | |
this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) : | |
this._tryAnimatedPan(center, options.pan); | |
if (animated) { | |
// prevent resize handler call, the view will refresh after animation anyway | |
clearTimeout(this._sizeTimer); | |
return this; | |
} | |
} | |
// animation didn't start, just reset the map view | |
this._resetView(center, zoom); | |
return this; | |
}, | |
panBy: function (offset, options) { | |
offset = L.point(offset).round(); | |
options = options || {}; | |
if (!offset.x && !offset.y) { | |
return this; | |
} | |
if (!this._panAnim) { | |
this._panAnim = new L.PosAnimation(); | |
this._panAnim.on({ | |
'step': this._onPanTransitionStep, | |
'end': this._onPanTransitionEnd | |
}, this); | |
} | |
// don't fire movestart if animating inertia | |
if (!options.noMoveStart) { | |
this.fire('movestart'); | |
} | |
// animate pan unless animate: false specified | |
if (options.animate !== false) { | |
L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim'); | |
var newPos = this._getMapPanePos().subtract(offset); | |
this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity); | |
} else { | |
this._rawPanBy(offset); | |
this.fire('move').fire('moveend'); | |
} | |
return this; | |
}, | |
_onPanTransitionStep: function () { | |
this.fire('move'); | |
}, | |
_onPanTransitionEnd: function () { | |
L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim'); | |
this.fire('moveend'); | |
}, | |
_tryAnimatedPan: function (center, options) { | |
// difference between the new and current centers in pixels | |
var offset = this._getCenterOffset(center)._floor(); | |
// don't animate too far unless animate: true specified in options | |
if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; } | |
this.panBy(offset, options); | |
return true; | |
} | |
}); | |
/* | |
* L.PosAnimation fallback implementation that powers Leaflet pan animations | |
* in browsers that don't support CSS3 Transitions. | |
*/ | |
L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({ | |
run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number]) | |
this.stop(); | |
this._el = el; | |
this._inProgress = true; | |
this._duration = duration || 0.25; | |
this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2); | |
this._startPos = L.DomUtil.getPosition(el); | |
this._offset = newPos.subtract(this._startPos); | |
this._startTime = +new Date(); | |
this.fire('start'); | |
this._animate(); | |
}, | |
stop: function () { | |
if (!this._inProgress) { return; } | |
this._step(); | |
this._complete(); | |
}, | |
_animate: function () { | |
// animation loop | |
this._animId = L.Util.requestAnimFrame(this._animate, this); | |
this._step(); | |
}, | |
_step: function () { | |
var elapsed = (+new Date()) - this._startTime, | |
duration = this._duration * 1000; | |
if (elapsed < duration) { | |
this._runFrame(this._easeOut(elapsed / duration)); | |
} else { | |
this._runFrame(1); | |
this._complete(); | |
} | |
}, | |
_runFrame: function (progress) { | |
var pos = this._startPos.add(this._offset.multiplyBy(progress)); | |
L.DomUtil.setPosition(this._el, pos); | |
this.fire('step'); | |
}, | |
_complete: function () { | |
L.Util.cancelAnimFrame(this._animId); | |
this._inProgress = false; | |
this.fire('end'); | |
}, | |
_easeOut: function (t) { | |
return 1 - Math.pow(1 - t, this._easeOutPower); | |
} | |
}); | |
/* | |
* Extends L.Map to handle zoom animations. | |
*/ | |
L.Map.mergeOptions({ | |
zoomAnimation: true, | |
zoomAnimationThreshold: 4 | |
}); | |
if (L.DomUtil.TRANSITION) { | |
L.Map.addInitHook(function () { | |
// don't animate on browsers without hardware-accelerated transitions or old Android/Opera | |
this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION && | |
L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera; | |
// zoom transitions run with the same duration for all layers, so if one of transitionend events | |
// happens after starting zoom animation (propagating to the map pane), we know that it ended globally | |
if (this._zoomAnimated) { | |
L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this); | |
} | |
}); | |
} | |
L.Map.include(!L.DomUtil.TRANSITION ? {} : { | |
_catchTransitionEnd: function (e) { | |
if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) { | |
this._onZoomTransitionEnd(); | |
} | |
}, | |
_nothingToAnimate: function () { | |
return !this._container.getElementsByClassName('leaflet-zoom-animated').length; | |
}, | |
_tryAnimatedZoom: function (center, zoom, options) { | |
if (this._animatingZoom) { return true; } | |
options = options || {}; | |
// don't animate if disabled, not supported or zoom difference is too large | |
if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() || | |
Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; } | |
// offset is the pixel coords of the zoom origin relative to the current center | |
var scale = this.getZoomScale(zoom), | |
offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale), | |
origin = this._getCenterLayerPoint()._add(offset); | |
// don't animate if the zoom origin isn't within one screen from the current center, unless forced | |
if (options.animate !== true && !this.getSize().contains(offset)) { return false; } | |
this | |
.fire('movestart') | |
.fire('zoomstart'); | |
this._animateZoom(center, zoom, origin, scale, null, true); | |
return true; | |
}, | |
_animateZoom: function (center, zoom, origin, scale, delta, backwards, forTouchZoom) { | |
if (!forTouchZoom) { | |
this._animatingZoom = true; | |
} | |
// put transform transition on all layers with leaflet-zoom-animated class | |
L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim'); | |
// remember what center/zoom to set after animation | |
this._animateToCenter = center; | |
this._animateToZoom = zoom; | |
// disable any dragging during animation | |
if (L.Draggable) { | |
L.Draggable._disabled = true; | |
} | |
L.Util.requestAnimFrame(function () { | |
this.fire('zoomanim', { | |
center: center, | |
zoom: zoom, | |
origin: origin, | |
scale: scale, | |
delta: delta, | |
backwards: backwards | |
}); | |
}, this); | |
}, | |
_onZoomTransitionEnd: function () { | |
this._animatingZoom = false; | |
L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim'); | |
this._resetView(this._animateToCenter, this._animateToZoom, true, true); | |
if (L.Draggable) { | |
L.Draggable._disabled = false; | |
} | |
} | |
}); | |
/* | |
Zoom animation logic for L.TileLayer. | |
*/ | |
L.TileLayer.include({ | |
_animateZoom: function (e) { | |
if (!this._animating) { | |
this._animating = true; | |
this._prepareBgBuffer(); | |
} | |
var bg = this._bgBuffer, | |
transform = L.DomUtil.TRANSFORM, | |
initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform], | |
scaleStr = L.DomUtil.getScaleString(e.scale, e.origin); | |
bg.style[transform] = e.backwards ? | |
scaleStr + ' ' + initialTransform : | |
initialTransform + ' ' + scaleStr; | |
}, | |
_endZoomAnim: function () { | |
var front = this._tileContainer, | |
bg = this._bgBuffer; | |
front.style.visibility = ''; | |
front.parentNode.appendChild(front); // Bring to fore | |
// force reflow | |
L.Util.falseFn(bg.offsetWidth); | |
this._animating = false; | |
}, | |
_clearBgBuffer: function () { | |
var map = this._map; | |
if (map && !map._animatingZoom && !map.touchZoom._zooming) { | |
this._bgBuffer.innerHTML = ''; | |
this._bgBuffer.style[L.DomUtil.TRANSFORM] = ''; | |
} | |
}, | |
_prepareBgBuffer: function () { | |
var front = this._tileContainer, | |
bg = this._bgBuffer; | |
// if foreground layer doesn't have many tiles but bg layer does, | |
// keep the existing bg layer and just zoom it some more | |
var bgLoaded = this._getLoadedTilesPercentage(bg), | |
frontLoaded = this._getLoadedTilesPercentage(front); | |
if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) { | |
front.style.visibility = 'hidden'; | |
this._stopLoadingImages(front); | |
return; | |
} | |
// prepare the buffer to become the front tile pane | |
bg.style.visibility = 'hidden'; | |
bg.style[L.DomUtil.TRANSFORM] = ''; | |
// switch out the current layer to be the new bg layer (and vice-versa) | |
this._tileContainer = bg; | |
bg = this._bgBuffer = front; | |
this._stopLoadingImages(bg); | |
//prevent bg buffer from clearing right after zoom | |
clearTimeout(this._clearBgBufferTimer); | |
}, | |
_getLoadedTilesPercentage: function (container) { | |
var tiles = container.getElementsByTagName('img'), | |
i, len, count = 0; | |
for (i = 0, len = tiles.length; i < len; i++) { | |
if (tiles[i].complete) { | |
count++; | |
} | |
} | |
return count / len; | |
}, | |
// stops loading all tiles in the background layer | |
_stopLoadingImages: function (container) { | |
var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')), | |
i, len, tile; | |
for (i = 0, len = tiles.length; i < len; i++) { | |
tile = tiles[i]; | |
if (!tile.complete) { | |
tile.onload = L.Util.falseFn; | |
tile.onerror = L.Util.falseFn; | |
tile.src = L.Util.emptyImageUrl; | |
tile.parentNode.removeChild(tile); | |
} | |
} | |
} | |
}); | |
/* | |
* Provides L.Map with convenient shortcuts for using browser geolocation features. | |
*/ | |
L.Map.include({ | |
_defaultLocateOptions: { | |
watch: false, | |
setView: false, | |
maxZoom: Infinity, | |
timeout: 10000, | |
maximumAge: 0, | |
enableHighAccuracy: false | |
}, | |
locate: function (/*Object*/ options) { | |
options = this._locateOptions = L.extend(this._defaultLocateOptions, options); | |
if (!navigator.geolocation) { | |
this._handleGeolocationError({ | |
code: 0, | |
message: 'Geolocation not supported.' | |
}); | |
return this; | |
} | |
var onResponse = L.bind(this._handleGeolocationResponse, this), | |
onError = L.bind(this._handleGeolocationError, this); | |
if (options.watch) { | |
this._locationWatchId = | |
navigator.geolocation.watchPosition(onResponse, onError, options); | |
} else { | |
navigator.geolocation.getCurrentPosition(onResponse, onError, options); | |
} | |
return this; | |
}, | |
stopLocate: function () { | |
if (navigator.geolocation) { | |
navigator.geolocation.clearWatch(this._locationWatchId); | |
} | |
if (this._locateOptions) { | |
this._locateOptions.setView = false; | |
} | |
return this; | |
}, | |
_handleGeolocationError: function (error) { | |
var c = error.code, | |
message = error.message || | |
(c === 1 ? 'permission denied' : | |
(c === 2 ? 'position unavailable' : 'timeout')); | |
if (this._locateOptions.setView && !this._loaded) { | |
this.fitWorld(); | |
} | |
this.fire('locationerror', { | |
code: c, | |
message: 'Geolocation error: ' + message + '.' | |
}); | |
}, | |
_handleGeolocationResponse: function (pos) { | |
var lat = pos.coords.latitude, | |
lng = pos.coords.longitude, | |
latlng = new L.LatLng(lat, lng), | |
latAccuracy = 180 * pos.coords.accuracy / 40075017, | |
lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat), | |
bounds = L.latLngBounds( | |
[lat - latAccuracy, lng - lngAccuracy], | |
[lat + latAccuracy, lng + lngAccuracy]), | |
options = this._locateOptions; | |
if (options.setView) { | |
var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom); | |
this.setView(latlng, zoom); | |
} | |
var data = { | |
latlng: latlng, | |
bounds: bounds, | |
timestamp: pos.timestamp | |
}; | |
for (var i in pos.coords) { | |
if (typeof pos.coords[i] === 'number') { | |
data[i] = pos.coords[i]; | |
} | |
} | |
this.fire('locationfound', data); | |
} | |
}); | |
}(window, document)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* required styles */ | |
.leaflet-map-pane, | |
.leaflet-tile, | |
.leaflet-marker-icon, | |
.leaflet-marker-shadow, | |
.leaflet-tile-pane, | |
.leaflet-tile-container, | |
.leaflet-overlay-pane, | |
.leaflet-shadow-pane, | |
.leaflet-marker-pane, | |
.leaflet-popup-pane, | |
.leaflet-overlay-pane svg, | |
.leaflet-zoom-box, | |
.leaflet-image-layer, | |
.leaflet-layer { | |
position: absolute; | |
left: 0; | |
top: 0; | |
} | |
.leaflet-container { | |
overflow: hidden; | |
-ms-touch-action: none; | |
} | |
.leaflet-tile, | |
.leaflet-marker-icon, | |
.leaflet-marker-shadow { | |
-webkit-user-select: none; | |
-moz-user-select: none; | |
user-select: none; | |
-webkit-user-drag: none; | |
} | |
.leaflet-marker-icon, | |
.leaflet-marker-shadow { | |
display: block; | |
} | |
/* map is broken in FF if you have max-width: 100% on tiles */ | |
.leaflet-container img { | |
max-width: none !important; | |
} | |
/* stupid Android 2 doesn't understand "max-width: none" properly */ | |
.leaflet-container img.leaflet-image-layer { | |
max-width: 15000px !important; | |
} | |
.leaflet-tile { | |
filter: inherit; | |
visibility: hidden; | |
} | |
.leaflet-tile-loaded { | |
visibility: inherit; | |
} | |
.leaflet-zoom-box { | |
width: 0; | |
height: 0; | |
} | |
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */ | |
.leaflet-overlay-pane svg { | |
-moz-user-select: none; | |
} | |
.leaflet-tile-pane { z-index: 2; } | |
.leaflet-objects-pane { z-index: 3; } | |
.leaflet-overlay-pane { z-index: 4; } | |
.leaflet-shadow-pane { z-index: 5; } | |
.leaflet-marker-pane { z-index: 6; } | |
.leaflet-popup-pane { z-index: 7; } | |
.leaflet-vml-shape { | |
width: 1px; | |
height: 1px; | |
} | |
.lvml { | |
behavior: url(#default#VML); | |
display: inline-block; | |
position: absolute; | |
} | |
/* control positioning */ | |
.leaflet-control { | |
position: relative; | |
z-index: 7; | |
pointer-events: auto; | |
} | |
.leaflet-top, | |
.leaflet-bottom { | |
position: absolute; | |
z-index: 1000; | |
pointer-events: none; | |
} | |
.leaflet-top { | |
top: 0; | |
} | |
.leaflet-right { | |
right: 0; | |
} | |
.leaflet-bottom { | |
bottom: 0; | |
} | |
.leaflet-left { | |
left: 0; | |
} | |
.leaflet-control { | |
float: left; | |
clear: both; | |
} | |
.leaflet-right .leaflet-control { | |
float: right; | |
} | |
.leaflet-top .leaflet-control { | |
margin-top: 10px; | |
} | |
.leaflet-bottom .leaflet-control { | |
margin-bottom: 10px; | |
} | |
.leaflet-left .leaflet-control { | |
margin-left: 10px; | |
} | |
.leaflet-right .leaflet-control { | |
margin-right: 10px; | |
} | |
/* zoom and fade animations */ | |
.leaflet-fade-anim .leaflet-tile, | |
.leaflet-fade-anim .leaflet-popup { | |
opacity: 0; | |
-webkit-transition: opacity 0.2s linear; | |
-moz-transition: opacity 0.2s linear; | |
-o-transition: opacity 0.2s linear; | |
transition: opacity 0.2s linear; | |
} | |
.leaflet-fade-anim .leaflet-tile-loaded, | |
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup { | |
opacity: 1; | |
} | |
.leaflet-zoom-anim .leaflet-zoom-animated { | |
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1); | |
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1); | |
-o-transition: -o-transform 0.25s cubic-bezier(0,0,0.25,1); | |
transition: transform 0.25s cubic-bezier(0,0,0.25,1); | |
} | |
.leaflet-zoom-anim .leaflet-tile, | |
.leaflet-pan-anim .leaflet-tile, | |
.leaflet-touching .leaflet-zoom-animated { | |
-webkit-transition: none; | |
-moz-transition: none; | |
-o-transition: none; | |
transition: none; | |
} | |
.leaflet-zoom-anim .leaflet-zoom-hide { | |
visibility: hidden; | |
} | |
/* cursors */ | |
.leaflet-clickable { | |
cursor: pointer; | |
} | |
.leaflet-container { | |
cursor: -webkit-grab; | |
cursor: -moz-grab; | |
} | |
.leaflet-popup-pane, | |
.leaflet-control { | |
cursor: auto; | |
} | |
.leaflet-dragging .leaflet-container, | |
.leaflet-dragging .leaflet-clickable { | |
cursor: move; | |
cursor: -webkit-grabbing; | |
cursor: -moz-grabbing; | |
} | |
/* visual tweaks */ | |
.leaflet-container { | |
background: #ddd; | |
outline: 0; | |
} | |
.leaflet-container a { | |
color: #0078A8; | |
} | |
.leaflet-container a.leaflet-active { | |
outline: 2px solid orange; | |
} | |
.leaflet-zoom-box { | |
border: 2px dotted #38f; | |
background: rgba(255,255,255,0.5); | |
} | |
/* general typography */ | |
.leaflet-container { | |
font: 12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif; | |
} | |
/* general toolbar styles */ | |
.leaflet-bar { | |
box-shadow: 0 1px 5px rgba(0,0,0,0.65); | |
border-radius: 4px; | |
} | |
.leaflet-bar a, | |
.leaflet-bar a:hover { | |
background-color: #fff; | |
border-bottom: 1px solid #ccc; | |
width: 26px; | |
height: 26px; | |
line-height: 26px; | |
display: block; | |
text-align: center; | |
text-decoration: none; | |
color: black; | |
} | |
.leaflet-bar a, | |
.leaflet-control-layers-toggle { | |
background-position: 50% 50%; | |
background-repeat: no-repeat; | |
display: block; | |
} | |
.leaflet-bar a:hover { | |
background-color: #f4f4f4; | |
} | |
.leaflet-bar a:first-child { | |
border-top-left-radius: 4px; | |
border-top-right-radius: 4px; | |
} | |
.leaflet-bar a:last-child { | |
border-bottom-left-radius: 4px; | |
border-bottom-right-radius: 4px; | |
border-bottom: none; | |
} | |
.leaflet-bar a.leaflet-disabled { | |
cursor: default; | |
background-color: #f4f4f4; | |
color: #bbb; | |
} | |
.leaflet-touch .leaflet-bar a { | |
width: 30px; | |
height: 30px; | |
line-height: 30px; | |
} | |
/* zoom control */ | |
.leaflet-control-zoom-in, | |
.leaflet-control-zoom-out { | |
font: bold 18px 'Lucida Console', Monaco, monospace; | |
text-indent: 1px; | |
} | |
.leaflet-control-zoom-out { | |
font-size: 20px; | |
} | |
.leaflet-touch .leaflet-control-zoom-in { | |
font-size: 22px; | |
} | |
.leaflet-touch .leaflet-control-zoom-out { | |
font-size: 24px; | |
} | |
/* layers control */ | |
.leaflet-control-layers { | |
box-shadow: 0 1px 5px rgba(0,0,0,0.4); | |
background: #fff; | |
border-radius: 5px; | |
} | |
.leaflet-control-layers-toggle { | |
background-image: url(images/layers.png); | |
width: 36px; | |
height: 36px; | |
} | |
.leaflet-retina .leaflet-control-layers-toggle { | |
background-image: url(images/layers-2x.png); | |
background-size: 26px 26px; | |
} | |
.leaflet-touch .leaflet-control-layers-toggle { | |
width: 44px; | |
height: 44px; | |
} | |
.leaflet-control-layers .leaflet-control-layers-list, | |
.leaflet-control-layers-expanded .leaflet-control-layers-toggle { | |
display: none; | |
} | |
.leaflet-control-layers-expanded .leaflet-control-layers-list { | |
display: block; | |
position: relative; | |
} | |
.leaflet-control-layers-expanded { | |
padding: 6px 10px 6px 6px; | |
color: #333; | |
background: #fff; | |
} | |
.leaflet-control-layers-selector { | |
margin-top: 2px; | |
position: relative; | |
top: 1px; | |
} | |
.leaflet-control-layers label { | |
display: block; | |
} | |
.leaflet-control-layers-separator { | |
height: 0; | |
border-top: 1px solid #ddd; | |
margin: 5px -10px 5px -6px; | |
} | |
/* attribution and scale controls */ | |
.leaflet-container .leaflet-control-attribution { | |
background: #fff; | |
background: rgba(255, 255, 255, 0.7); | |
margin: 0; | |
} | |
.leaflet-control-attribution, | |
.leaflet-control-scale-line { | |
padding: 0 5px; | |
color: #333; | |
} | |
.leaflet-control-attribution a { | |
text-decoration: none; | |
} | |
.leaflet-control-attribution a:hover { | |
text-decoration: underline; | |
} | |
.leaflet-container .leaflet-control-attribution, | |
.leaflet-container .leaflet-control-scale { | |
font-size: 11px; | |
} | |
.leaflet-left .leaflet-control-scale { | |
margin-left: 5px; | |
} | |
.leaflet-bottom .leaflet-control-scale { | |
margin-bottom: 5px; | |
} | |
.leaflet-control-scale-line { | |
border: 2px solid #777; | |
border-top: none; | |
line-height: 1.1; | |
padding: 2px 5px 1px; | |
font-size: 11px; | |
white-space: nowrap; | |
overflow: hidden; | |
-moz-box-sizing: content-box; | |
box-sizing: content-box; | |
background: #fff; | |
background: rgba(255, 255, 255, 0.5); | |
} | |
.leaflet-control-scale-line:not(:first-child) { | |
border-top: 2px solid #777; | |
border-bottom: none; | |
margin-top: -2px; | |
} | |
.leaflet-control-scale-line:not(:first-child):not(:last-child) { | |
border-bottom: 2px solid #777; | |
} | |
.leaflet-touch .leaflet-control-attribution, | |
.leaflet-touch .leaflet-control-layers, | |
.leaflet-touch .leaflet-bar { | |
box-shadow: none; | |
} | |
.leaflet-touch .leaflet-control-layers, | |
.leaflet-touch .leaflet-bar { | |
border: 2px solid rgba(0,0,0,0.2); | |
background-clip: padding-box; | |
} | |
/* popup */ | |
.leaflet-popup { | |
position: absolute; | |
text-align: center; | |
} | |
.leaflet-popup-content-wrapper { | |
padding: 1px; | |
text-align: left; | |
border-radius: 12px; | |
} | |
.leaflet-popup-content { | |
margin: 13px 19px; | |
line-height: 1.4; | |
} | |
.leaflet-popup-content p { | |
margin: 18px 0; | |
} | |
.leaflet-popup-tip-container { | |
margin: 0 auto; | |
width: 40px; | |
height: 20px; | |
position: relative; | |
overflow: hidden; | |
} | |
.leaflet-popup-tip { | |
width: 17px; | |
height: 17px; | |
padding: 1px; | |
margin: -10px auto 0; | |
-webkit-transform: rotate(45deg); | |
-moz-transform: rotate(45deg); | |
-ms-transform: rotate(45deg); | |
-o-transform: rotate(45deg); | |
transform: rotate(45deg); | |
} | |
.leaflet-popup-content-wrapper, | |
.leaflet-popup-tip { | |
background: white; | |
box-shadow: 0 3px 14px rgba(0,0,0,0.4); | |
} | |
.leaflet-container a.leaflet-popup-close-button { | |
position: absolute; | |
top: 0; | |
right: 0; | |
padding: 4px 4px 0 0; | |
text-align: center; | |
width: 18px; | |
height: 14px; | |
font: 16px/14px Tahoma, Verdana, sans-serif; | |
color: #c3c3c3; | |
text-decoration: none; | |
font-weight: bold; | |
background: transparent; | |
} | |
.leaflet-container a.leaflet-popup-close-button:hover { | |
color: #999; | |
} | |
.leaflet-popup-scrolled { | |
overflow: auto; | |
border-bottom: 1px solid #ddd; | |
border-top: 1px solid #ddd; | |
} | |
.leaflet-oldie .leaflet-popup-content-wrapper { | |
zoom: 1; | |
} | |
.leaflet-oldie .leaflet-popup-tip { | |
width: 24px; | |
margin: 0 auto; | |
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)"; | |
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678); | |
} | |
.leaflet-oldie .leaflet-popup-tip-container { | |
margin-top: -1px; | |
} | |
.leaflet-oldie .leaflet-control-zoom, | |
.leaflet-oldie .leaflet-control-layers, | |
.leaflet-oldie .leaflet-popup-content-wrapper, | |
.leaflet-oldie .leaflet-popup-tip { | |
border: 1px solid #999; | |
} | |
/* div icon */ | |
.leaflet-div-icon { | |
background: #fff; | |
border: 1px solid #666; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author qiao / https://github.com/qiao | |
* @author mrdoob / http://mrdoob.com | |
* @author alteredq / http://alteredqualia.com/ | |
* @author WestLangley / http://github.com/WestLangley | |
* @author erich666 / http://erichaines.com | |
*/ | |
/*global THREE, console */ | |
// This set of controls performs orbiting, dollying (zooming), and panning. It maintains | |
// the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is | |
// supported. | |
// | |
// Orbit - left mouse / touch: one finger move | |
// Zoom - middle mouse, or mousewheel / touch: two finger spread or squish | |
// Pan - right mouse, or arrow keys / touch: three finter swipe | |
// | |
// This is a drop-in replacement for (most) TrackballControls used in examples. | |
// That is, include this js file and wherever you see: | |
// controls = new THREE.TrackballControls( camera ); | |
// controls.target.z = 150; | |
// Simple substitute "OrbitControls" and the control should work as-is. | |
THREE.OrbitControls = function ( object, domElement ) { | |
this.object = object; | |
this.domElement = ( domElement !== undefined ) ? domElement : document; | |
// API | |
// Set to false to disable this control | |
this.enabled = true; | |
// "target" sets the location of focus, where the control orbits around | |
// and where it pans with respect to. | |
this.target = new THREE.Vector3(); | |
// center is old, deprecated; use "target" instead | |
this.center = this.target; | |
// This option actually enables dollying in and out; left as "zoom" for | |
// backwards compatibility | |
this.noZoom = false; | |
this.zoomSpeed = 1.0; | |
// Limits to how far you can dolly in and out | |
this.minDistance = 0; | |
this.maxDistance = Infinity; | |
// Set to true to disable this control | |
this.noRotate = false; | |
this.rotateSpeed = 1.0; | |
// Set to true to disable this control | |
this.noPan = false; | |
this.keyPanSpeed = 7.0; // pixels moved per arrow key push | |
// Set to true to automatically rotate around the target | |
this.autoRotate = false; | |
this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 | |
// How far you can orbit vertically, upper and lower limits. | |
// Range is 0 to Math.PI radians. | |
this.minPolarAngle = 0; // radians | |
this.maxPolarAngle = Math.PI; // radians | |
// Set to true to disable use of the keys | |
this.noKeys = false; | |
// The four arrow keys | |
this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; | |
//////////// | |
// internals | |
var scope = this; | |
var EPS = 0.000001; | |
var rotateStart = new THREE.Vector2(); | |
var rotateEnd = new THREE.Vector2(); | |
var rotateDelta = new THREE.Vector2(); | |
var panStart = new THREE.Vector2(); | |
var panEnd = new THREE.Vector2(); | |
var panDelta = new THREE.Vector2(); | |
var panOffset = new THREE.Vector3(); | |
var offset = new THREE.Vector3(); | |
var dollyStart = new THREE.Vector2(); | |
var dollyEnd = new THREE.Vector2(); | |
var dollyDelta = new THREE.Vector2(); | |
var phiDelta = 0; | |
var thetaDelta = 0; | |
var scale = 1; | |
var pan = new THREE.Vector3(); | |
var lastPosition = new THREE.Vector3(); | |
var STATE = { NONE : -1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; | |
var state = STATE.NONE; | |
// for reset | |
this.target0 = this.target.clone(); | |
this.position0 = this.object.position.clone(); | |
// so camera.up is the orbit axis | |
var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); | |
var quatInverse = quat.clone().inverse(); | |
// events | |
var changeEvent = { type: 'change' }; | |
var startEvent = { type: 'start'}; | |
var endEvent = { type: 'end'}; | |
this.rotateLeft = function ( angle ) { | |
if ( angle === undefined ) { | |
angle = getAutoRotationAngle(); | |
} | |
thetaDelta -= angle; | |
}; | |
this.rotateUp = function ( angle ) { | |
if ( angle === undefined ) { | |
angle = getAutoRotationAngle(); | |
} | |
phiDelta -= angle; | |
}; | |
// pass in distance in world space to move left | |
this.panLeft = function ( distance ) { | |
var te = this.object.matrix.elements; | |
// get X column of matrix | |
panOffset.set( te[ 0 ], te[ 1 ], te[ 2 ] ); | |
panOffset.multiplyScalar( - distance ); | |
pan.add( panOffset ); | |
}; | |
// pass in distance in world space to move up | |
this.panUp = function ( distance ) { | |
var te = this.object.matrix.elements; | |
// get Y column of matrix | |
panOffset.set( te[ 4 ], te[ 5 ], te[ 6 ] ); | |
panOffset.multiplyScalar( distance ); | |
pan.add( panOffset ); | |
}; | |
// pass in x,y of change desired in pixel space, | |
// right and down are positive | |
this.pan = function ( deltaX, deltaY ) { | |
var element = scope.domElement === document ? scope.domElement.body : scope.domElement; | |
if ( scope.object.fov !== undefined ) { | |
// perspective | |
var position = scope.object.position; | |
var offset = position.clone().sub( scope.target ); | |
var targetDistance = offset.length(); | |
// half of the fov is center to top of screen | |
targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); | |
// we actually don't use screenWidth, since perspective camera is fixed to screen height | |
scope.panLeft( 2 * deltaX * targetDistance / element.clientHeight ); | |
scope.panUp( 2 * deltaY * targetDistance / element.clientHeight ); | |
} else if ( scope.object.top !== undefined ) { | |
// orthographic | |
scope.panLeft( deltaX * (scope.object.right - scope.object.left) / element.clientWidth ); | |
scope.panUp( deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight ); | |
} else { | |
// camera neither orthographic or perspective | |
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); | |
} | |
}; | |
this.dollyIn = function ( dollyScale ) { | |
if ( dollyScale === undefined ) { | |
dollyScale = getZoomScale(); | |
} | |
scale /= dollyScale; | |
}; | |
this.dollyOut = function ( dollyScale ) { | |
if ( dollyScale === undefined ) { | |
dollyScale = getZoomScale(); | |
} | |
scale *= dollyScale; | |
}; | |
this.update = function () { | |
var position = this.object.position; | |
offset.copy( position ).sub( this.target ); | |
// rotate offset to "y-axis-is-up" space | |
offset.applyQuaternion( quat ); | |
// angle from z-axis around y-axis | |
var theta = Math.atan2( offset.x, offset.z ); | |
// angle from y-axis | |
var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y ); | |
if ( this.autoRotate ) { | |
this.rotateLeft( getAutoRotationAngle() ); | |
} | |
theta += thetaDelta; | |
phi += phiDelta; | |
// restrict phi to be between desired limits | |
phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); | |
// restrict phi to be betwee EPS and PI-EPS | |
phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) ); | |
var radius = offset.length() * scale; | |
// restrict radius to be between desired limits | |
radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) ); | |
// move target to panned location | |
this.target.add( pan ); | |
offset.x = radius * Math.sin( phi ) * Math.sin( theta ); | |
offset.y = radius * Math.cos( phi ); | |
offset.z = radius * Math.sin( phi ) * Math.cos( theta ); | |
// rotate offset back to "camera-up-vector-is-up" space | |
offset.applyQuaternion( quatInverse ); | |
position.copy( this.target ).add( offset ); | |
this.object.lookAt( this.target ); | |
thetaDelta = 0; | |
phiDelta = 0; | |
scale = 1; | |
pan.set( 0, 0, 0 ); | |
if ( lastPosition.distanceToSquared( this.object.position ) > EPS ) { | |
this.dispatchEvent( changeEvent ); | |
lastPosition.copy( this.object.position ); | |
} | |
}; | |
this.reset = function () { | |
state = STATE.NONE; | |
this.target.copy( this.target0 ); | |
this.object.position.copy( this.position0 ); | |
this.update(); | |
}; | |
function getAutoRotationAngle() { | |
return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; | |
} | |
function getZoomScale() { | |
return Math.pow( 0.95, scope.zoomSpeed ); | |
} | |
function onMouseDown( event ) { | |
if ( scope.enabled === false ) return; | |
event.preventDefault(); | |
if ( event.button === 0 ) { | |
if ( scope.noRotate === true ) return; | |
state = STATE.ROTATE; | |
rotateStart.set( event.clientX, event.clientY ); | |
} else if ( event.button === 1 ) { | |
if ( scope.noZoom === true ) return; | |
state = STATE.DOLLY; | |
dollyStart.set( event.clientX, event.clientY ); | |
} else if ( event.button === 2 ) { | |
if ( scope.noPan === true ) return; | |
state = STATE.PAN; | |
panStart.set( event.clientX, event.clientY ); | |
} | |
scope.domElement.addEventListener( 'mousemove', onMouseMove, false ); | |
scope.domElement.addEventListener( 'mouseup', onMouseUp, false ); | |
scope.dispatchEvent( startEvent ); | |
} | |
function onMouseMove( event ) { | |
if ( scope.enabled === false ) return; | |
event.preventDefault(); | |
var element = scope.domElement === document ? scope.domElement.body : scope.domElement; | |
if ( state === STATE.ROTATE ) { | |
if ( scope.noRotate === true ) return; | |
rotateEnd.set( event.clientX, event.clientY ); | |
rotateDelta.subVectors( rotateEnd, rotateStart ); | |
// rotating across whole screen goes 360 degrees around | |
scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); | |
// rotating up and down along whole screen attempts to go 360, but limited to 180 | |
scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); | |
rotateStart.copy( rotateEnd ); | |
} else if ( state === STATE.DOLLY ) { | |
if ( scope.noZoom === true ) return; | |
dollyEnd.set( event.clientX, event.clientY ); | |
dollyDelta.subVectors( dollyEnd, dollyStart ); | |
if ( dollyDelta.y > 0 ) { | |
scope.dollyIn(); | |
} else { | |
scope.dollyOut(); | |
} | |
dollyStart.copy( dollyEnd ); | |
} else if ( state === STATE.PAN ) { | |
if ( scope.noPan === true ) return; | |
panEnd.set( event.clientX, event.clientY ); | |
panDelta.subVectors( panEnd, panStart ); | |
scope.pan( panDelta.x, panDelta.y ); | |
panStart.copy( panEnd ); | |
} | |
scope.update(); | |
} | |
function onMouseUp( /* event */ ) { | |
if ( scope.enabled === false ) return; | |
scope.domElement.removeEventListener( 'mousemove', onMouseMove, false ); | |
scope.domElement.removeEventListener( 'mouseup', onMouseUp, false ); | |
scope.dispatchEvent( endEvent ); | |
state = STATE.NONE; | |
} | |
function onMouseWheel( event ) { | |
if ( scope.enabled === false || scope.noZoom === true ) return; | |
event.preventDefault(); | |
event.stopPropagation(); | |
var delta = 0; | |
if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9 | |
delta = event.wheelDelta; | |
} else if ( event.detail !== undefined ) { // Firefox | |
delta = - event.detail; | |
} | |
if ( delta > 0 ) { | |
scope.dollyOut(); | |
} else { | |
scope.dollyIn(); | |
} | |
scope.update(); | |
scope.dispatchEvent( startEvent ); | |
scope.dispatchEvent( endEvent ); | |
} | |
function onKeyDown( event ) { | |
if ( scope.enabled === false || scope.noKeys === true || scope.noPan === true ) return; | |
switch ( event.keyCode ) { | |
case scope.keys.UP: | |
scope.pan( 0, scope.keyPanSpeed ); | |
scope.update(); | |
break; | |
case scope.keys.BOTTOM: | |
scope.pan( 0, - scope.keyPanSpeed ); | |
scope.update(); | |
break; | |
case scope.keys.LEFT: | |
scope.pan( scope.keyPanSpeed, 0 ); | |
scope.update(); | |
break; | |
case scope.keys.RIGHT: | |
scope.pan( - scope.keyPanSpeed, 0 ); | |
scope.update(); | |
break; | |
} | |
} | |
function touchstart( event ) { | |
if ( scope.enabled === false ) return; | |
switch ( event.touches.length ) { | |
case 1: // one-fingered touch: rotate | |
if ( scope.noRotate === true ) return; | |
state = STATE.TOUCH_ROTATE; | |
rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); | |
break; | |
case 2: // two-fingered touch: dolly | |
if ( scope.noZoom === true ) return; | |
state = STATE.TOUCH_DOLLY; | |
var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; | |
var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; | |
var distance = Math.sqrt( dx * dx + dy * dy ); | |
dollyStart.set( 0, distance ); | |
break; | |
case 3: // three-fingered touch: pan | |
if ( scope.noPan === true ) return; | |
state = STATE.TOUCH_PAN; | |
panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); | |
break; | |
default: | |
state = STATE.NONE; | |
} | |
scope.dispatchEvent( startEvent ); | |
} | |
function touchmove( event ) { | |
if ( scope.enabled === false ) return; | |
event.preventDefault(); | |
event.stopPropagation(); | |
var element = scope.domElement === document ? scope.domElement.body : scope.domElement; | |
switch ( event.touches.length ) { | |
case 1: // one-fingered touch: rotate | |
if ( scope.noRotate === true ) return; | |
if ( state !== STATE.TOUCH_ROTATE ) return; | |
rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); | |
rotateDelta.subVectors( rotateEnd, rotateStart ); | |
// rotating across whole screen goes 360 degrees around | |
scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); | |
// rotating up and down along whole screen attempts to go 360, but limited to 180 | |
scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); | |
rotateStart.copy( rotateEnd ); | |
scope.update(); | |
break; | |
case 2: // two-fingered touch: dolly | |
if ( scope.noZoom === true ) return; | |
if ( state !== STATE.TOUCH_DOLLY ) return; | |
var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; | |
var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; | |
var distance = Math.sqrt( dx * dx + dy * dy ); | |
dollyEnd.set( 0, distance ); | |
dollyDelta.subVectors( dollyEnd, dollyStart ); | |
if ( dollyDelta.y > 0 ) { | |
scope.dollyOut(); | |
} else { | |
scope.dollyIn(); | |
} | |
dollyStart.copy( dollyEnd ); | |
scope.update(); | |
break; | |
case 3: // three-fingered touch: pan | |
if ( scope.noPan === true ) return; | |
if ( state !== STATE.TOUCH_PAN ) return; | |
panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); | |
panDelta.subVectors( panEnd, panStart ); | |
scope.pan( panDelta.x, panDelta.y ); | |
panStart.copy( panEnd ); | |
scope.update(); | |
break; | |
default: | |
state = STATE.NONE; | |
} | |
} | |
function touchend( /* event */ ) { | |
if ( scope.enabled === false ) return; | |
scope.dispatchEvent( endEvent ); | |
state = STATE.NONE; | |
} | |
this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); | |
this.domElement.addEventListener( 'mousedown', onMouseDown, false ); | |
this.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); | |
this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox | |
this.domElement.addEventListener( 'touchstart', touchstart, false ); | |
this.domElement.addEventListener( 'touchend', touchend, false ); | |
this.domElement.addEventListener( 'touchmove', touchmove, false ); | |
window.addEventListener( 'keydown', onKeyDown, false ); | |
// force an update at start | |
this.update(); | |
}; | |
THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author alteredq / http://alteredqualia.com/ | |
* @authod mrdoob / http://mrdoob.com/ | |
* @authod arodic / http://aleksandarrodic.com/ | |
*/ | |
THREE.StereoEffect = function ( renderer ) { | |
// API | |
this.separation = 3; | |
// internals | |
var _width, _height; | |
var _position = new THREE.Vector3(); | |
var _quaternion = new THREE.Quaternion(); | |
var _scale = new THREE.Vector3(); | |
var _cameraL = new THREE.PerspectiveCamera(); | |
var _cameraR = new THREE.PerspectiveCamera(); | |
// initialization | |
renderer.autoClear = false; | |
this.setSize = function ( width, height ) { | |
_width = width / 2; | |
_height = height; | |
renderer.setSize( width, height ); | |
}; | |
this.render = function ( scene, camera ) { | |
scene.updateMatrixWorld(); | |
if ( camera.parent === undefined ) camera.updateMatrixWorld(); | |
camera.matrixWorld.decompose( _position, _quaternion, _scale ); | |
// left | |
_cameraL.fov = camera.fov; | |
_cameraL.aspect = 0.5 * camera.aspect; | |
_cameraL.near = camera.near; | |
_cameraL.far = camera.far; | |
_cameraL.updateProjectionMatrix(); | |
_cameraL.position.copy( _position ); | |
_cameraL.quaternion.copy( _quaternion ); | |
_cameraL.translateX( - this.separation ); | |
_cameraL.updateMatrixWorld(); | |
// right | |
_cameraR.near = camera.near; | |
_cameraR.far = camera.far; | |
_cameraR.projectionMatrix = _cameraL.projectionMatrix; | |
_cameraR.position.copy( _position ); | |
_cameraR.quaternion.copy( _quaternion ); | |
_cameraR.translateX( this.separation ); | |
_cameraR.updateMatrixWorld(); | |
// | |
renderer.setViewport( 0, 0, _width * 2, _height ); | |
renderer.clear(); | |
renderer.setViewport( 0, 0, _width, _height ); | |
renderer.render( scene, _cameraL ); | |
renderer.setViewport( _width, 0, _width, _height ); | |
renderer.render( scene, _cameraR ); | |
}; | |
}; |
This file has been truncated, but you can view the full file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// File:src/Three.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
var THREE = { REVISION: '69' }; | |
// browserify support | |
if ( typeof module === 'object' ) { | |
module.exports = THREE; | |
} | |
// polyfills | |
if ( Math.sign === undefined ) { | |
Math.sign = function ( x ) { | |
return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0; | |
}; | |
} | |
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button | |
THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; | |
// GL STATE CONSTANTS | |
THREE.CullFaceNone = 0; | |
THREE.CullFaceBack = 1; | |
THREE.CullFaceFront = 2; | |
THREE.CullFaceFrontBack = 3; | |
THREE.FrontFaceDirectionCW = 0; | |
THREE.FrontFaceDirectionCCW = 1; | |
// SHADOWING TYPES | |
THREE.BasicShadowMap = 0; | |
THREE.PCFShadowMap = 1; | |
THREE.PCFSoftShadowMap = 2; | |
// 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; | |
THREE.MinEquation = 103; | |
THREE.MaxEquation = 104; | |
// 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; | |
THREE.AddOperation = 2; | |
// 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; | |
// DDS / ST3C 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; | |
// 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; | |
// File:src/math/Color.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Color = function ( color ) { | |
if ( arguments.length === 3 ) { | |
return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] ); | |
} | |
return this.set( color ) | |
}; | |
THREE.Color.prototype = { | |
constructor: THREE.Color, | |
r: 1, g: 1, b: 1, | |
set: function ( value ) { | |
if ( value instanceof THREE.Color ) { | |
this.copy( value ); | |
} else if ( typeof value === 'number' ) { | |
this.setHex( value ); | |
} else if ( typeof value === 'string' ) { | |
this.setStyle( value ); | |
} | |
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; | |
}, | |
setRGB: function ( r, g, b ) { | |
this.r = r; | |
this.g = g; | |
this.b = b; | |
return this; | |
}, | |
setHSL: function ( h, s, l ) { | |
// h,s,l ranges are in 0.0 - 1.0 | |
if ( s === 0 ) { | |
this.r = this.g = this.b = l; | |
} else { | |
var hue2rgb = function ( p, q, t ) { | |
if ( t < 0 ) t += 1; | |
if ( t > 1 ) t -= 1; | |
if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; | |
if ( t < 1 / 2 ) return q; | |
if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); | |
return p; | |
}; | |
var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); | |
var q = ( 2 * l ) - p; | |
this.r = hue2rgb( q, p, h + 1 / 3 ); | |
this.g = hue2rgb( q, p, h ); | |
this.b = hue2rgb( q, p, h - 1 / 3 ); | |
} | |
return this; | |
}, | |
setStyle: function ( style ) { | |
// rgb(255,0,0) | |
if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) { | |
var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style ); | |
this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; | |
this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; | |
this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; | |
return this; | |
} | |
// rgb(100%,0%,0%) | |
if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) { | |
var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style ); | |
this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; | |
this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; | |
this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; | |
return this; | |
} | |
// #ff0000 | |
if ( /^\#([0-9a-f]{6})$/i.test( style ) ) { | |
var color = /^\#([0-9a-f]{6})$/i.exec( style ); | |
this.setHex( parseInt( color[ 1 ], 16 ) ); | |
return this; | |
} | |
// #f00 | |
if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) { | |
var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style ); | |
this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) ); | |
return this; | |
} | |
// red | |
if ( /^(\w+)$/i.test( style ) ) { | |
this.setHex( THREE.ColorKeywords[ style ] ); | |
return this; | |
} | |
}, | |
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; | |
}, | |
getHex: function () { | |
return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; | |
}, | |
getHexString: function () { | |
return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); | |
}, | |
getHSL: function ( optionalTarget ) { | |
// h,s,l ranges are in 0.0 - 1.0 | |
var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; | |
var r = this.r, g = this.g, b = this.b; | |
var max = Math.max( r, g, b ); | |
var min = Math.min( r, g, b ); | |
var hue, saturation; | |
var lightness = ( min + max ) / 2.0; | |
if ( min === max ) { | |
hue = 0; | |
saturation = 0; | |
} else { | |
var delta = max - min; | |
saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); | |
switch ( max ) { | |
case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; | |
case g: hue = ( b - r ) / delta + 2; break; | |
case b: hue = ( r - g ) / delta + 4; break; | |
} | |
hue /= 6; | |
} | |
hsl.h = hue; | |
hsl.s = saturation; | |
hsl.l = lightness; | |
return hsl; | |
}, | |
getStyle: function () { | |
return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; | |
}, | |
offsetHSL: function ( h, s, l ) { | |
var hsl = this.getHSL(); | |
hsl.h += h; hsl.s += s; hsl.l += l; | |
this.setHSL( hsl.h, hsl.s, hsl.l ); | |
return this; | |
}, | |
add: function ( color ) { | |
this.r += color.r; | |
this.g += color.g; | |
this.b += color.b; | |
return this; | |
}, | |
addColors: function ( color1, color2 ) { | |
this.r = color1.r + color2.r; | |
this.g = color1.g + color2.g; | |
this.b = color1.b + color2.b; | |
return this; | |
}, | |
addScalar: function ( s ) { | |
this.r += s; | |
this.g += s; | |
this.b += s; | |
return this; | |
}, | |
multiply: function ( color ) { | |
this.r *= color.r; | |
this.g *= color.g; | |
this.b *= color.b; | |
return this; | |
}, | |
multiplyScalar: function ( s ) { | |
this.r *= s; | |
this.g *= s; | |
this.b *= s; | |
return this; | |
}, | |
lerp: 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; | |
}, | |
equals: function ( c ) { | |
return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); | |
}, | |
fromArray: function ( array ) { | |
this.r = array[ 0 ]; | |
this.g = array[ 1 ]; | |
this.b = array[ 2 ]; | |
return this; | |
}, | |
toArray: function () { | |
return [ this.r, this.g, this.b ]; | |
}, | |
clone: function () { | |
return new THREE.Color().setRGB( this.r, this.g, this.b ); | |
} | |
}; | |
THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, | |
'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, | |
'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, | |
'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, | |
'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, | |
'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, | |
'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, | |
'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, | |
'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, | |
'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, | |
'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, | |
'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, | |
'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, | |
'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, | |
'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, | |
'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, | |
'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, | |
'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, | |
'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, | |
'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, | |
'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, | |
'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, | |
'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, | |
'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; | |
// File:src/math/Quaternion.js | |
/** | |
* @author mikael emtinger / http://gomo.se/ | |
* @author alteredq / http://alteredqualia.com/ | |
* @author WestLangley / http://github.com/WestLangley | |
* @author bhouston / http://exocortex.com | |
*/ | |
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, | |
_x: 0,_y: 0, _z: 0, _w: 0, | |
get x () { | |
return this._x; | |
}, | |
set x ( value ) { | |
this._x = value; | |
this.onChangeCallback(); | |
}, | |
get y () { | |
return this._y; | |
}, | |
set y ( value ) { | |
this._y = value; | |
this.onChangeCallback(); | |
}, | |
get z () { | |
return this._z; | |
}, | |
set z ( value ) { | |
this._z = value; | |
this.onChangeCallback(); | |
}, | |
get w () { | |
return this._w; | |
}, | |
set w ( value ) { | |
this._w = value; | |
this.onChangeCallback(); | |
}, | |
set: function ( x, y, z, w ) { | |
this._x = x; | |
this._y = y; | |
this._z = z; | |
this._w = w; | |
this.onChangeCallback(); | |
return this; | |
}, | |
copy: function ( quaternion ) { | |
this._x = quaternion.x; | |
this._y = quaternion.y; | |
this._z = quaternion.z; | |
this._w = quaternion.w; | |
this.onChangeCallback(); | |
return this; | |
}, | |
setFromEuler: function ( euler, update ) { | |
if ( euler instanceof THREE.Euler === false ) { | |
throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and 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( euler._x / 2 ); | |
var c2 = Math.cos( euler._y / 2 ); | |
var c3 = Math.cos( euler._z / 2 ); | |
var s1 = Math.sin( euler._x / 2 ); | |
var s2 = Math.sin( euler._y / 2 ); | |
var s3 = Math.sin( euler._z / 2 ); | |
if ( euler.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 ( euler.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 ( euler.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 ( euler.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 ( euler.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 ( euler.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; | |
} | |
if ( update !== false ) this.onChangeCallback(); | |
return this; | |
}, | |
setFromAxisAngle: function ( axis, angle ) { | |
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm | |
// assumes axis is 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 ); | |
this.onChangeCallback(); | |
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; | |
} | |
this.onChangeCallback(); | |
return this; | |
}, | |
setFromUnitVectors: function () { | |
// http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final | |
// assumes direction vectors vFrom and vTo are normalized | |
var v1, r; | |
var EPS = 0.000001; | |
return function ( vFrom, vTo ) { | |
if ( v1 === undefined ) v1 = new THREE.Vector3(); | |
r = vFrom.dot( vTo ) + 1; | |
if ( r < EPS ) { | |
r = 0; | |
if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { | |
v1.set( - vFrom.y, vFrom.x, 0 ); | |
} else { | |
v1.set( 0, - vFrom.z, vFrom.y ); | |
} | |
} else { | |
v1.crossVectors( vFrom, vTo ); | |
} | |
this._x = v1.x; | |
this._y = v1.y; | |
this._z = v1.z; | |
this._w = r; | |
this.normalize(); | |
return this; | |
} | |
}(), | |
inverse: function () { | |
this.conjugate().normalize(); | |
return this; | |
}, | |
conjugate: function () { | |
this._x *= - 1; | |
this._y *= - 1; | |
this._z *= - 1; | |
this.onChangeCallback(); | |
return this; | |
}, | |
dot: function ( v ) { | |
return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; | |
}, | |
lengthSq: function () { | |
return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; | |
}, | |
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 = this.length(); | |
if ( l === 0 ) { | |
this._x = 0; | |
this._y = 0; | |
this._z = 0; | |
this._w = 1; | |
} else { | |
l = 1 / l; | |
this._x = this._x * l; | |
this._y = this._y * l; | |
this._z = this._z * l; | |
this._w = this._w * l; | |
} | |
this.onChangeCallback(); | |
return this; | |
}, | |
multiply: function ( q, p ) { | |
if ( p !== undefined ) { | |
console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); | |
return this.multiplyQuaternions( q, p ); | |
} | |
return this.multiplyQuaternions( this, q ); | |
}, | |
multiplyQuaternions: 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; | |
var 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; | |
this.onChangeCallback(); | |
return this; | |
}, | |
multiplyVector3: function ( vector ) { | |
console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); | |
return vector.applyQuaternion( this ); | |
}, | |
slerp: function ( qb, t ) { | |
if ( t === 0 ) return this; | |
if ( t === 1 ) return this.copy( qb ); | |
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 ); | |
this.onChangeCallback(); | |
return this; | |
}, | |
equals: function ( quaternion ) { | |
return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); | |
}, | |
fromArray: function ( array, offset ) { | |
if ( offset === undefined ) offset = 0; | |
this._x = array[ offset ]; | |
this._y = array[ offset + 1 ]; | |
this._z = array[ offset + 2 ]; | |
this._w = array[ offset + 3 ]; | |
this.onChangeCallback(); | |
return this; | |
}, | |
toArray: function ( array, offset ) { | |
if ( array === undefined ) array = []; | |
if ( offset === undefined ) offset = 0; | |
array[ offset ] = this._x; | |
array[ offset + 1 ] = this._y; | |
array[ offset + 2 ] = this._z; | |
array[ offset + 3 ] = this._w; | |
return array; | |
}, | |
onChange: function ( callback ) { | |
this.onChangeCallback = callback; | |
return this; | |
}, | |
onChangeCallback: function () {}, | |
clone: function () { | |
return new THREE.Quaternion( this._x, this._y, this._z, this._w ); | |
} | |
}; | |
THREE.Quaternion.slerp = function ( qa, qb, qm, t ) { | |
return qm.copy( qa ).slerp( qb, t ); | |
} | |
// File:src/math/Vector2.js | |
/** | |
* @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; | |
}, | |
setX: function ( x ) { | |
this.x = x; | |
return this; | |
}, | |
setY: function ( y ) { | |
this.y = y; | |
return this; | |
}, | |
setComponent: function ( index, value ) { | |
switch ( index ) { | |
case 0: this.x = value; break; | |
case 1: this.y = value; break; | |
default: throw new Error( 'index is out of range: ' + index ); | |
} | |
}, | |
getComponent: function ( index ) { | |
switch ( index ) { | |
case 0: return this.x; | |
case 1: return this.y; | |
default: throw new Error( 'index is out of range: ' + index ); | |
} | |
}, | |
copy: function ( v ) { | |
this.x = v.x; | |
this.y = v.y; | |
return this; | |
}, | |
add: function ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); | |
return this.addVectors( v, w ); | |
} | |
this.x += v.x; | |
this.y += v.y; | |
return this; | |
}, | |
addVectors: function ( a, b ) { | |
this.x = a.x + b.x; | |
this.y = a.y + b.y; | |
return this; | |
}, | |
addScalar: function ( s ) { | |
this.x += s; | |
this.y += s; | |
return this; | |
}, | |
sub: function ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); | |
return this.subVectors( v, w ); | |
} | |
this.x -= v.x; | |
this.y -= v.y; | |
return this; | |
}, | |
subVectors: function ( a, b ) { | |
this.x = a.x - b.x; | |
this.y = a.y - b.y; | |
return this; | |
}, | |
multiply: function ( v ) { | |
this.x *= v.x; | |
this.y *= v.y; | |
return this; | |
}, | |
multiplyScalar: function ( s ) { | |
this.x *= s; | |
this.y *= s; | |
return this; | |
}, | |
divide: function ( v ) { | |
this.x /= v.x; | |
this.y /= v.y; | |
return this; | |
}, | |
divideScalar: function ( scalar ) { | |
if ( scalar !== 0 ) { | |
var invScalar = 1 / scalar; | |
this.x *= invScalar; | |
this.y *= invScalar; | |
} else { | |
this.x = 0; | |
this.y = 0; | |
} | |
return this; | |
}, | |
min: function ( v ) { | |
if ( this.x > v.x ) { | |
this.x = v.x; | |
} | |
if ( this.y > v.y ) { | |
this.y = v.y; | |
} | |
return this; | |
}, | |
max: function ( v ) { | |
if ( this.x < v.x ) { | |
this.x = v.x; | |
} | |
if ( this.y < v.y ) { | |
this.y = v.y; | |
} | |
return this; | |
}, | |
clamp: function ( min, max ) { | |
// This function assumes min < max, if this assumption isn't true it will not operate correctly | |
if ( this.x < min.x ) { | |
this.x = min.x; | |
} else if ( this.x > max.x ) { | |
this.x = max.x; | |
} | |
if ( this.y < min.y ) { | |
this.y = min.y; | |
} else if ( this.y > max.y ) { | |
this.y = max.y; | |
} | |
return this; | |
}, | |
clampScalar: ( function () { | |
var min, max; | |
return function ( minVal, maxVal ) { | |
if ( min === undefined ) { | |
min = new THREE.Vector2(); | |
max = new THREE.Vector2(); | |
} | |
min.set( minVal, minVal ); | |
max.set( maxVal, maxVal ); | |
return this.clamp( min, max ); | |
}; | |
} )(), | |
floor: function () { | |
this.x = Math.floor( this.x ); | |
this.y = Math.floor( this.y ); | |
return this; | |
}, | |
ceil: function () { | |
this.x = Math.ceil( this.x ); | |
this.y = Math.ceil( this.y ); | |
return this; | |
}, | |
round: function () { | |
this.x = Math.round( this.x ); | |
this.y = Math.round( this.y ); | |
return this; | |
}, | |
roundToZero: function () { | |
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); | |
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); | |
return this; | |
}, | |
negate: function () { | |
this.x = - this.x; | |
this.y = - this.y; | |
return this; | |
}, | |
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.x * this.x + this.y * this.y ); | |
}, | |
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 ) { | |
var oldLength = this.length(); | |
if ( oldLength !== 0 && l !== oldLength ) { | |
this.multiplyScalar( l / oldLength ); | |
} | |
return this; | |
}, | |
lerp: 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 ) ); | |
}, | |
fromArray: function ( array, offset ) { | |
if ( offset === undefined ) offset = 0; | |
this.x = array[ offset ]; | |
this.y = array[ offset + 1 ]; | |
return this; | |
}, | |
toArray: function ( array, offset ) { | |
if ( array === undefined ) array = []; | |
if ( offset === undefined ) offset = 0; | |
array[ offset ] = this.x; | |
array[ offset + 1 ] = this.y; | |
return array; | |
}, | |
clone: function () { | |
return new THREE.Vector2( this.x, this.y ); | |
} | |
}; | |
// File:src/math/Vector3.js | |
/** | |
* @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; | |
}, | |
setComponent: function ( index, value ) { | |
switch ( index ) { | |
case 0: this.x = value; break; | |
case 1: this.y = value; break; | |
case 2: this.z = value; break; | |
default: throw new Error( 'index is out of range: ' + index ); | |
} | |
}, | |
getComponent: function ( index ) { | |
switch ( index ) { | |
case 0: return this.x; | |
case 1: return this.y; | |
case 2: return this.z; | |
default: throw new Error( 'index is out of range: ' + index ); | |
} | |
}, | |
copy: function ( v ) { | |
this.x = v.x; | |
this.y = v.y; | |
this.z = v.z; | |
return this; | |
}, | |
add: function ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); | |
return this.addVectors( v, w ); | |
} | |
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; | |
}, | |
addVectors: function ( a, b ) { | |
this.x = a.x + b.x; | |
this.y = a.y + b.y; | |
this.z = a.z + b.z; | |
return this; | |
}, | |
sub: function ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); | |
return this.subVectors( v, w ); | |
} | |
this.x -= v.x; | |
this.y -= v.y; | |
this.z -= v.z; | |
return this; | |
}, | |
subVectors: function ( a, b ) { | |
this.x = a.x - b.x; | |
this.y = a.y - b.y; | |
this.z = a.z - b.z; | |
return this; | |
}, | |
multiply: function ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); | |
return this.multiplyVectors( v, w ); | |
} | |
this.x *= v.x; | |
this.y *= v.y; | |
this.z *= v.z; | |
return this; | |
}, | |
multiplyScalar: function ( scalar ) { | |
this.x *= scalar; | |
this.y *= scalar; | |
this.z *= scalar; | |
return this; | |
}, | |
multiplyVectors: function ( a, b ) { | |
this.x = a.x * b.x; | |
this.y = a.y * b.y; | |
this.z = a.z * b.z; | |
return this; | |
}, | |
applyEuler: function () { | |
var quaternion; | |
return function ( euler ) { | |
if ( euler instanceof THREE.Euler === false ) { | |
console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' ); | |
} | |
if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); | |
this.applyQuaternion( quaternion.setFromEuler( euler ) ); | |
return this; | |
}; | |
}(), | |
applyAxisAngle: function () { | |
var quaternion; | |
return function ( axis, angle ) { | |
if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); | |
this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); | |
return this; | |
}; | |
}(), | |
applyMatrix3: function ( m ) { | |
var x = this.x; | |
var y = this.y; | |
var z = this.z; | |
var e = m.elements; | |
this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; | |
this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; | |
this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; | |
return this; | |
}, | |
applyMatrix4: function ( m ) { | |
// input: THREE.Matrix4 affine matrix | |
var x = this.x, y = this.y, z = this.z; | |
var e = m.elements; | |
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; | |
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; | |
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; | |
return this; | |
}, | |
applyProjection: function ( m ) { | |
// input: THREE.Matrix4 projection matrix | |
var x = this.x, y = this.y, z = this.z; | |
var e = m.elements; | |
var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide | |
this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; | |
this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; | |
this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; | |
return this; | |
}, | |
applyQuaternion: function ( q ) { | |
var x = this.x; | |
var y = this.y; | |
var z = this.z; | |
var qx = q.x; | |
var qy = q.y; | |
var qz = q.z; | |
var qw = q.w; | |
// calculate quat * vector | |
var ix = qw * x + qy * z - qz * y; | |
var iy = qw * y + qz * x - qx * z; | |
var iz = qw * z + qx * y - qy * x; | |
var iw = - qx * x - qy * y - qz * z; | |
// calculate result * inverse quat | |
this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; | |
this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; | |
this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; | |
return this; | |
}, | |
project: function () { | |
var matrix; | |
return function ( camera ) { | |
if ( matrix === undefined ) matrix = new THREE.Matrix4(); | |
matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); | |
return this.applyProjection( matrix ); | |
}; | |
}(), | |
unproject: function () { | |
var matrix; | |
return function ( camera ) { | |
if ( matrix === undefined ) matrix = new THREE.Matrix4(); | |
matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); | |
return this.applyProjection( matrix ); | |
}; | |
}(), | |
transformDirection: function ( m ) { | |
// input: THREE.Matrix4 affine matrix | |
// vector interpreted as a direction | |
var x = this.x, y = this.y, z = this.z; | |
var e = m.elements; | |
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; | |
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; | |
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; | |
this.normalize(); | |
return this; | |
}, | |
divide: function ( v ) { | |
this.x /= v.x; | |
this.y /= v.y; | |
this.z /= v.z; | |
return this; | |
}, | |
divideScalar: function ( scalar ) { | |
if ( scalar !== 0 ) { | |
var invScalar = 1 / scalar; | |
this.x *= invScalar; | |
this.y *= invScalar; | |
this.z *= invScalar; | |
} else { | |
this.x = 0; | |
this.y = 0; | |
this.z = 0; | |
} | |
return this; | |
}, | |
min: function ( v ) { | |
if ( this.x > v.x ) { | |
this.x = v.x; | |
} | |
if ( this.y > v.y ) { | |
this.y = v.y; | |
} | |
if ( this.z > v.z ) { | |
this.z = v.z; | |
} | |
return this; | |
}, | |
max: function ( v ) { | |
if ( this.x < v.x ) { | |
this.x = v.x; | |
} | |
if ( this.y < v.y ) { | |
this.y = v.y; | |
} | |
if ( this.z < v.z ) { | |
this.z = v.z; | |
} | |
return this; | |
}, | |
clamp: function ( min, max ) { | |
// This function assumes min < max, if this assumption isn't true it will not operate correctly | |
if ( this.x < min.x ) { | |
this.x = min.x; | |
} else if ( this.x > max.x ) { | |
this.x = max.x; | |
} | |
if ( this.y < min.y ) { | |
this.y = min.y; | |
} else if ( this.y > max.y ) { | |
this.y = max.y; | |
} | |
if ( this.z < min.z ) { | |
this.z = min.z; | |
} else if ( this.z > max.z ) { | |
this.z = max.z; | |
} | |
return this; | |
}, | |
clampScalar: ( function () { | |
var min, max; | |
return function ( minVal, maxVal ) { | |
if ( min === undefined ) { | |
min = new THREE.Vector3(); | |
max = new THREE.Vector3(); | |
} | |
min.set( minVal, minVal, minVal ); | |
max.set( maxVal, maxVal, maxVal ); | |
return this.clamp( min, max ); | |
}; | |
} )(), | |
floor: function () { | |
this.x = Math.floor( this.x ); | |
this.y = Math.floor( this.y ); | |
this.z = Math.floor( this.z ); | |
return this; | |
}, | |
ceil: function () { | |
this.x = Math.ceil( this.x ); | |
this.y = Math.ceil( this.y ); | |
this.z = Math.ceil( this.z ); | |
return this; | |
}, | |
round: function () { | |
this.x = Math.round( this.x ); | |
this.y = Math.round( this.y ); | |
this.z = Math.round( this.z ); | |
return this; | |
}, | |
roundToZero: function () { | |
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); | |
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); | |
this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); | |
return this; | |
}, | |
negate: function () { | |
this.x = - this.x; | |
this.y = - this.y; | |
this.z = - this.z; | |
return this; | |
}, | |
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.x * this.x + this.y * this.y + this.z * this.z ); | |
}, | |
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 ) { | |
var oldLength = this.length(); | |
if ( oldLength !== 0 && l !== oldLength ) { | |
this.multiplyScalar( l / oldLength ); | |
} | |
return this; | |
}, | |
lerp: 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 ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); | |
return this.crossVectors( v, w ); | |
} | |
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; | |
}, | |
crossVectors: function ( a, b ) { | |
var ax = a.x, ay = a.y, az = a.z; | |
var bx = b.x, by = b.y, bz = b.z; | |
this.x = ay * bz - az * by; | |
this.y = az * bx - ax * bz; | |
this.z = ax * by - ay * bx; | |
return this; | |
}, | |
projectOnVector: function () { | |
var v1, dot; | |
return function ( vector ) { | |
if ( v1 === undefined ) v1 = new THREE.Vector3(); | |
v1.copy( vector ).normalize(); | |
dot = this.dot( v1 ); | |
return this.copy( v1 ).multiplyScalar( dot ); | |
}; | |
}(), | |
projectOnPlane: function () { | |
var v1; | |
return function ( planeNormal ) { | |
if ( v1 === undefined ) v1 = new THREE.Vector3(); | |
v1.copy( this ).projectOnVector( planeNormal ); | |
return this.sub( v1 ); | |
} | |
}(), | |
reflect: function () { | |
// reflect incident vector off plane orthogonal to normal | |
// normal is assumed to have unit length | |
var v1; | |
return function ( normal ) { | |
if ( v1 === undefined ) v1 = new THREE.Vector3(); | |
return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); | |
} | |
}(), | |
angleTo: function ( v ) { | |
var theta = this.dot( v ) / ( this.length() * v.length() ); | |
// clamp, to handle numerical problems | |
return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); | |
}, | |
distanceTo: function ( v ) { | |
return Math.sqrt( this.distanceToSquared( v ) ); | |
}, | |
distanceToSquared: function ( v ) { | |
var dx = this.x - v.x; | |
var dy = this.y - v.y; | |
var dz = this.z - v.z; | |
return dx * dx + dy * dy + dz * dz; | |
}, | |
setEulerFromRotationMatrix: function ( m, order ) { | |
console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); | |
}, | |
setEulerFromQuaternion: function ( q, order ) { | |
console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); | |
}, | |
getPositionFromMatrix: function ( m ) { | |
console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); | |
return this.setFromMatrixPosition( m ); | |
}, | |
getScaleFromMatrix: function ( m ) { | |
console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); | |
return this.setFromMatrixScale( m ); | |
}, | |
getColumnFromMatrix: function ( index, matrix ) { | |
console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); | |
return this.setFromMatrixColumn( index, matrix ); | |
}, | |
setFromMatrixPosition: function ( m ) { | |
this.x = m.elements[ 12 ]; | |
this.y = m.elements[ 13 ]; | |
this.z = m.elements[ 14 ]; | |
return this; | |
}, | |
setFromMatrixScale: 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; | |
}, | |
setFromMatrixColumn: function ( index, matrix ) { | |
var offset = index * 4; | |
var me = matrix.elements; | |
this.x = me[ offset ]; | |
this.y = me[ offset + 1 ]; | |
this.z = me[ offset + 2 ]; | |
return this; | |
}, | |
equals: function ( v ) { | |
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); | |
}, | |
fromArray: function ( array, offset ) { | |
if ( offset === undefined ) offset = 0; | |
this.x = array[ offset ]; | |
this.y = array[ offset + 1 ]; | |
this.z = array[ offset + 2 ]; | |
return this; | |
}, | |
toArray: function ( array, offset ) { | |
if ( array === undefined ) array = []; | |
if ( offset === undefined ) offset = 0; | |
array[ offset ] = this.x; | |
array[ offset + 1 ] = this.y; | |
array[ offset + 2 ] = this.z; | |
return array; | |
}, | |
clone: function () { | |
return new THREE.Vector3( this.x, this.y, this.z ); | |
} | |
}; | |
// File:src/math/Vector4.js | |
/** | |
* @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; | |
}, | |
setX: function ( x ) { | |
this.x = x; | |
return this; | |
}, | |
setY: function ( y ) { | |
this.y = y; | |
return this; | |
}, | |
setZ: function ( z ) { | |
this.z = z; | |
return this; | |
}, | |
setW: function ( w ) { | |
this.w = w; | |
return this; | |
}, | |
setComponent: function ( index, value ) { | |
switch ( index ) { | |
case 0: this.x = value; break; | |
case 1: this.y = value; break; | |
case 2: this.z = value; break; | |
case 3: this.w = value; break; | |
default: throw new Error( 'index is out of range: ' + index ); | |
} | |
}, | |
getComponent: function ( index ) { | |
switch ( index ) { | |
case 0: return this.x; | |
case 1: return this.y; | |
case 2: return this.z; | |
case 3: return this.w; | |
default: throw new Error( 'index is out of range: ' + index ); | |
} | |
}, | |
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 ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); | |
return this.addVectors( v, w ); | |
} | |
this.x += v.x; | |
this.y += v.y; | |
this.z += v.z; | |
this.w += v.w; | |
return this; | |
}, | |
addScalar: function ( s ) { | |
this.x += s; | |
this.y += s; | |
this.z += s; | |
this.w += s; | |
return this; | |
}, | |
addVectors: 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; | |
}, | |
sub: function ( v, w ) { | |
if ( w !== undefined ) { | |
console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); | |
return this.subVectors( v, w ); | |
} | |
this.x -= v.x; | |
this.y -= v.y; | |
this.z -= v.z; | |
this.w -= v.w; | |
return this; | |
}, | |
subVectors: 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; | |
}, | |
multiplyScalar: function ( scalar ) { | |
this.x *= scalar; | |
this.y *= scalar; | |
this.z *= scalar; | |
this.w *= scalar; | |
return this; | |
}, | |
applyMatrix4: function ( m ) { | |
var x = this.x; | |
var y = this.y; | |
var z = this.z; | |
var w = this.w; | |
var e = m.elements; | |
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; | |
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; | |
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; | |
this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; | |
return this; | |
}, | |
divideScalar: function ( scalar ) { | |
if ( scalar !== 0 ) { | |
var invScalar = 1 / scalar; | |
this.x *= invScalar; | |
this.y *= invScalar; | |
this.z *= invScalar; | |
this.w *= invScalar; | |
} else { | |
this.x = 0; | |
this.y = 0; | |
this.z = 0; | |
this.w = 1; | |
} | |
return this; | |
}, | |
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; | |
}, | |
min: function ( v ) { | |
if ( this.x > v.x ) { | |
this.x = v.x; | |
} | |
if ( this.y > v.y ) { | |
this.y = v.y; | |
} | |
if ( this.z > v.z ) { | |
this.z = v.z; | |
} | |
if ( this.w > v.w ) { | |
this.w = v.w; | |
} | |
return this; | |
}, | |
max: function ( v ) { | |
if ( this.x < v.x ) { | |
this.x = v.x; | |
} | |
if ( this.y < v.y ) { | |
this.y = v.y; | |
} | |
if ( this.z < v.z ) { | |
this.z = v.z; | |
} | |
if ( this.w < v.w ) { | |
this.w = v.w; | |
} | |
return this; | |
}, | |
clamp: function ( min, max ) { | |
// This function assumes min < max, if this assumption isn't true it will not operate correctly | |
if ( this.x < min.x ) { | |
this.x = min.x; | |
} else if ( this.x > max.x ) { | |
this.x = max.x; | |
} | |
if ( this.y < min.y ) { | |
this.y = min.y; | |
} else if ( this.y > max.y ) { | |
this.y = max.y; | |
} | |
if ( this.z < min.z ) { | |
this.z = min.z; | |
} else if ( this.z > max.z ) { | |
this.z = max.z; | |
} | |
if ( this.w < min.w ) { | |
this.w = min.w; | |
} else if ( this.w > max.w ) { | |
this.w = max.w; | |
} | |
return this; | |
}, | |
clampScalar: ( function () { | |
var min, max; | |
return function ( minVal, maxVal ) { | |
if ( min === undefined ) { | |
min = new THREE.Vector4(); | |
max = new THREE.Vector4(); | |
} | |
min.set( minVal, minVal, minVal, minVal ); | |
max.set( maxVal, maxVal, maxVal, maxVal ); | |
return this.clamp( min, max ); | |
}; | |
} )(), | |
floor: function () { | |
this.x = Math.floor( this.x ); | |
this.y = Math.floor( this.y ); | |
this.z = Math.floor( this.z ); | |
this.w = Math.floor( this.w ); | |
return this; | |
}, | |
ceil: function () { | |
this.x = Math.ceil( this.x ); | |
this.y = Math.ceil( this.y ); | |
this.z = Math.ceil( this.z ); | |
this.w = Math.ceil( this.w ); | |
return this; | |
}, | |
round: function () { | |
this.x = Math.round( this.x ); | |
this.y = Math.round( this.y ); | |
this.z = Math.round( this.z ); | |
this.w = Math.round( this.w ); | |
return this; | |
}, | |
roundToZero: function () { | |
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); | |
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); | |
this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); | |
this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); | |
return this; | |
}, | |
negate: function () { | |
this.x = - this.x; | |
this.y = - this.y; | |
this.z = - this.z; | |
this.w = - this.w; | |
return this; | |
}, | |
dot: function ( v ) { | |
return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; | |
}, | |
lengthSq: function () { | |
return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; | |
}, | |
length: function () { | |
return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); | |
}, | |
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 ) { | |
var oldLength = this.length(); | |
if ( oldLength !== 0 && l !== oldLength ) { | |
this.multiplyScalar( l / oldLength ); | |
} | |
return this; | |
}, | |
lerp: 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; | |
}, | |
equals: function ( v ) { | |
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); | |
}, | |
fromArray: function ( array, offset ) { | |
if ( offset === undefined ) offset = 0; | |
this.x = array[ offset ]; | |
this.y = array[ offset + 1 ]; | |
this.z = array[ offset + 2 ]; | |
this.w = array[ offset + 3 ]; | |
return this; | |
}, | |
toArray: function ( array, offset ) { | |
if ( array === undefined ) array = []; | |
if ( offset === undefined ) offset = 0; | |
array[ offset ] = this.x; | |
array[ offset + 1 ] = this.y; | |
array[ offset + 2 ] = this.z; | |
array[ offset + 3 ] = this.w; | |
return array; | |
}, | |
clone: function () { | |
return new THREE.Vector4( this.x, this.y, this.z, this.w ); | |
} | |
}; | |
// File:src/math/Euler.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author WestLangley / http://github.com/WestLangley | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Euler = function ( x, y, z, order ) { | |
this._x = x || 0; | |
this._y = y || 0; | |
this._z = z || 0; | |
this._order = order || THREE.Euler.DefaultOrder; | |
}; | |
THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; | |
THREE.Euler.DefaultOrder = 'XYZ'; | |
THREE.Euler.prototype = { | |
constructor: THREE.Euler, | |
_x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder, | |
get x () { | |
return this._x; | |
}, | |
set x ( value ) { | |
this._x = value; | |
this.onChangeCallback(); | |
}, | |
get y () { | |
return this._y; | |
}, | |
set y ( value ) { | |
this._y = value; | |
this.onChangeCallback(); | |
}, | |
get z () { | |
return this._z; | |
}, | |
set z ( value ) { | |
this._z = value; | |
this.onChangeCallback(); | |
}, | |
get order () { | |
return this._order; | |
}, | |
set order ( value ) { | |
this._order = value; | |
this.onChangeCallback(); | |
}, | |
set: function ( x, y, z, order ) { | |
this._x = x; | |
this._y = y; | |
this._z = z; | |
this._order = order || this._order; | |
this.onChangeCallback(); | |
return this; | |
}, | |
copy: function ( euler ) { | |
this._x = euler._x; | |
this._y = euler._y; | |
this._z = euler._z; | |
this._order = euler._order; | |
this.onChangeCallback(); | |
return this; | |
}, | |
setFromRotationMatrix: function ( m, order ) { | |
var clamp = THREE.Math.clamp; | |
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) | |
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 ]; | |
order = order || this._order; | |
if ( order === 'XYZ' ) { | |
this._y = Math.asin( clamp( m13, - 1, 1 ) ); | |
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, - 1, 1 ) ); | |
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, - 1, 1 ) ); | |
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, - 1, 1 ) ); | |
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, - 1, 1 ) ); | |
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, - 1, 1 ) ); | |
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; | |
} | |
} else { | |
console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ) | |
} | |
this._order = order; | |
this.onChangeCallback(); | |
return this; | |
}, | |
setFromQuaternion: function ( q, order, update ) { | |
var clamp = THREE.Math.clamp; | |
// q is assumed to be normalized | |
// 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; | |
order = order || this._order; | |
if ( 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 ), - 1, 1 ) ); | |
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 ), - 1, 1 ) ); | |
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 ), - 1, 1 ) ); | |
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 ), - 1, 1 ) ); | |
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 ), - 1, 1 ) ); | |
} 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 ), - 1, 1 ) ); | |
} else { | |
console.warn( 'THREE.Euler: .setFromQuaternion() given unsupported order: ' + order ) | |
} | |
this._order = order; | |
if ( update !== false ) this.onChangeCallback(); | |
return this; | |
}, | |
reorder: function () { | |
// WARNING: this discards revolution information -bhouston | |
var q = new THREE.Quaternion(); | |
return function ( newOrder ) { | |
q.setFromEuler( this ); | |
this.setFromQuaternion( q, newOrder ); | |
}; | |
}(), | |
equals: function ( euler ) { | |
return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); | |
}, | |
fromArray: function ( array ) { | |
this._x = array[ 0 ]; | |
this._y = array[ 1 ]; | |
this._z = array[ 2 ]; | |
if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; | |
this.onChangeCallback(); | |
return this; | |
}, | |
toArray: function () { | |
return [ this._x, this._y, this._z, this._order ]; | |
}, | |
onChange: function ( callback ) { | |
this.onChangeCallback = callback; | |
return this; | |
}, | |
onChangeCallback: function () {}, | |
clone: function () { | |
return new THREE.Euler( this._x, this._y, this._z, this._order ); | |
} | |
}; | |
// File:src/math/Line3.js | |
/** | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Line3 = function ( start, end ) { | |
this.start = ( start !== undefined ) ? start : new THREE.Vector3(); | |
this.end = ( end !== undefined ) ? end : new THREE.Vector3(); | |
}; | |
THREE.Line3.prototype = { | |
constructor: THREE.Line3, | |
set: function ( start, end ) { | |
this.start.copy( start ); | |
this.end.copy( end ); | |
return this; | |
}, | |
copy: function ( line ) { | |
this.start.copy( line.start ); | |
this.end.copy( line.end ); | |
return this; | |
}, | |
center: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); | |
}, | |
delta: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.subVectors( this.end, this.start ); | |
}, | |
distanceSq: function () { | |
return this.start.distanceToSquared( this.end ); | |
}, | |
distance: function () { | |
return this.start.distanceTo( this.end ); | |
}, | |
at: function ( t, optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return this.delta( result ).multiplyScalar( t ).add( this.start ); | |
}, | |
closestPointToPointParameter: function () { | |
var startP = new THREE.Vector3(); | |
var startEnd = new THREE.Vector3(); | |
return function ( point, clampToLine ) { | |
startP.subVectors( point, this.start ); | |
startEnd.subVectors( this.end, this.start ); | |
var startEnd2 = startEnd.dot( startEnd ); | |
var startEnd_startP = startEnd.dot( startP ); | |
var t = startEnd_startP / startEnd2; | |
if ( clampToLine ) { | |
t = THREE.Math.clamp( t, 0, 1 ); | |
} | |
return t; | |
}; | |
}(), | |
closestPointToPoint: function ( point, clampToLine, optionalTarget ) { | |
var t = this.closestPointToPointParameter( point, clampToLine ); | |
var result = optionalTarget || new THREE.Vector3(); | |
return this.delta( result ).multiplyScalar( t ).add( this.start ); | |
}, | |
applyMatrix4: function ( matrix ) { | |
this.start.applyMatrix4( matrix ); | |
this.end.applyMatrix4( matrix ); | |
return this; | |
}, | |
equals: function ( line ) { | |
return line.start.equals( this.start ) && line.end.equals( this.end ); | |
}, | |
clone: function () { | |
return new THREE.Line3().copy( this ); | |
} | |
}; | |
// File:src/math/Box2.js | |
/** | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Box2 = function ( min, max ) { | |
this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity ); | |
this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); | |
}; | |
THREE.Box2.prototype = { | |
constructor: THREE.Box2, | |
set: function ( min, max ) { | |
this.min.copy( min ); | |
this.max.copy( max ); | |
return this; | |
}, | |
setFromPoints: function ( points ) { | |
this.makeEmpty(); | |
for ( var i = 0, il = points.length; i < il; i ++ ) { | |
this.expandByPoint( points[ i ] ) | |
} | |
return this; | |
}, | |
setFromCenterAndSize: function () { | |
var v1 = new THREE.Vector2(); | |
return function ( center, size ) { | |
var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); | |
this.min.copy( center ).sub( halfSize ); | |
this.max.copy( center ).add( halfSize ); | |
return this; | |
}; | |
}(), | |
copy: function ( box ) { | |
this.min.copy( box.min ); | |
this.max.copy( box.max ); | |
return this; | |
}, | |
makeEmpty: function () { | |
this.min.x = this.min.y = Infinity; | |
this.max.x = this.max.y = - Infinity; | |
return this; | |
}, | |
empty: function () { | |
// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes | |
return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); | |
}, | |
center: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector2(); | |
return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); | |
}, | |
size: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector2(); | |
return result.subVectors( this.max, this.min ); | |
}, | |
expandByPoint: function ( point ) { | |
this.min.min( point ); | |
this.max.max( point ); | |
return this; | |
}, | |
expandByVector: function ( vector ) { | |
this.min.sub( vector ); | |
this.max.add( vector ); | |
return this; | |
}, | |
expandByScalar: function ( scalar ) { | |
this.min.addScalar( - scalar ); | |
this.max.addScalar( scalar ); | |
return this; | |
}, | |
containsPoint: function ( point ) { | |
if ( point.x < this.min.x || point.x > this.max.x || | |
point.y < this.min.y || point.y > this.max.y ) { | |
return false; | |
} | |
return true; | |
}, | |
containsBox: function ( box ) { | |
if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && | |
( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) { | |
return true; | |
} | |
return false; | |
}, | |
getParameter: function ( point, optionalTarget ) { | |
// This can potentially have a divide by zero if the box | |
// has a size dimension of 0. | |
var result = optionalTarget || new THREE.Vector2(); | |
return result.set( | |
( point.x - this.min.x ) / ( this.max.x - this.min.x ), | |
( point.y - this.min.y ) / ( this.max.y - this.min.y ) | |
); | |
}, | |
isIntersectionBox: function ( box ) { | |
// using 6 splitting planes to rule out intersections. | |
if ( box.max.x < this.min.x || box.min.x > this.max.x || | |
box.max.y < this.min.y || box.min.y > this.max.y ) { | |
return false; | |
} | |
return true; | |
}, | |
clampPoint: function ( point, optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector2(); | |
return result.copy( point ).clamp( this.min, this.max ); | |
}, | |
distanceToPoint: function () { | |
var v1 = new THREE.Vector2(); | |
return function ( point ) { | |
var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); | |
return clampedPoint.sub( point ).length(); | |
}; | |
}(), | |
intersect: function ( box ) { | |
this.min.max( box.min ); | |
this.max.min( box.max ); | |
return this; | |
}, | |
union: function ( box ) { | |
this.min.min( box.min ); | |
this.max.max( box.max ); | |
return this; | |
}, | |
translate: function ( offset ) { | |
this.min.add( offset ); | |
this.max.add( offset ); | |
return this; | |
}, | |
equals: function ( box ) { | |
return box.min.equals( this.min ) && box.max.equals( this.max ); | |
}, | |
clone: function () { | |
return new THREE.Box2().copy( this ); | |
} | |
}; | |
// File:src/math/Box3.js | |
/** | |
* @author bhouston / http://exocortex.com | |
* @author WestLangley / http://github.com/WestLangley | |
*/ | |
THREE.Box3 = function ( min, max ) { | |
this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity ); | |
this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); | |
}; | |
THREE.Box3.prototype = { | |
constructor: THREE.Box3, | |
set: function ( min, max ) { | |
this.min.copy( min ); | |
this.max.copy( max ); | |
return this; | |
}, | |
setFromPoints: function ( points ) { | |
this.makeEmpty(); | |
for ( var i = 0, il = points.length; i < il; i ++ ) { | |
this.expandByPoint( points[ i ] ) | |
} | |
return this; | |
}, | |
setFromCenterAndSize: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( center, size ) { | |
var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); | |
this.min.copy( center ).sub( halfSize ); | |
this.max.copy( center ).add( halfSize ); | |
return this; | |
}; | |
}(), | |
setFromObject: function () { | |
// Computes the world-axis-aligned bounding box of an object (including its children), | |
// accounting for both the object's, and childrens', world transforms | |
var v1 = new THREE.Vector3(); | |
return function ( object ) { | |
var scope = this; | |
object.updateMatrixWorld( true ); | |
this.makeEmpty(); | |
object.traverse( function ( node ) { | |
var geometry = node.geometry; | |
if ( geometry !== undefined ) { | |
if ( geometry instanceof THREE.Geometry ) { | |
var vertices = geometry.vertices; | |
for ( var i = 0, il = vertices.length; i < il; i ++ ) { | |
v1.copy( vertices[ i ] ); | |
v1.applyMatrix4( node.matrixWorld ); | |
scope.expandByPoint( v1 ); | |
} | |
} else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) { | |
var positions = geometry.attributes[ 'position' ].array; | |
for ( var i = 0, il = positions.length; i < il; i += 3 ) { | |
v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); | |
v1.applyMatrix4( node.matrixWorld ); | |
scope.expandByPoint( v1 ); | |
} | |
} | |
} | |
} ); | |
return this; | |
}; | |
}(), | |
copy: function ( box ) { | |
this.min.copy( box.min ); | |
this.max.copy( box.max ); | |
return this; | |
}, | |
makeEmpty: function () { | |
this.min.x = this.min.y = this.min.z = Infinity; | |
this.max.x = this.max.y = this.max.z = - Infinity; | |
return this; | |
}, | |
empty: function () { | |
// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes | |
return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); | |
}, | |
center: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); | |
}, | |
size: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.subVectors( this.max, this.min ); | |
}, | |
expandByPoint: function ( point ) { | |
this.min.min( point ); | |
this.max.max( point ); | |
return this; | |
}, | |
expandByVector: function ( vector ) { | |
this.min.sub( vector ); | |
this.max.add( vector ); | |
return this; | |
}, | |
expandByScalar: function ( scalar ) { | |
this.min.addScalar( - scalar ); | |
this.max.addScalar( scalar ); | |
return this; | |
}, | |
containsPoint: function ( point ) { | |
if ( point.x < this.min.x || point.x > this.max.x || | |
point.y < this.min.y || point.y > this.max.y || | |
point.z < this.min.z || point.z > this.max.z ) { | |
return false; | |
} | |
return true; | |
}, | |
containsBox: function ( box ) { | |
if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && | |
( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) && | |
( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) { | |
return true; | |
} | |
return false; | |
}, | |
getParameter: function ( point, optionalTarget ) { | |
// This can potentially have a divide by zero if the box | |
// has a size dimension of 0. | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.set( | |
( point.x - this.min.x ) / ( this.max.x - this.min.x ), | |
( point.y - this.min.y ) / ( this.max.y - this.min.y ), | |
( point.z - this.min.z ) / ( this.max.z - this.min.z ) | |
); | |
}, | |
isIntersectionBox: function ( box ) { | |
// using 6 splitting planes to rule out intersections. | |
if ( box.max.x < this.min.x || box.min.x > this.max.x || | |
box.max.y < this.min.y || box.min.y > this.max.y || | |
box.max.z < this.min.z || box.min.z > this.max.z ) { | |
return false; | |
} | |
return true; | |
}, | |
clampPoint: function ( point, optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.copy( point ).clamp( this.min, this.max ); | |
}, | |
distanceToPoint: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( point ) { | |
var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); | |
return clampedPoint.sub( point ).length(); | |
}; | |
}(), | |
getBoundingSphere: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Sphere(); | |
result.center = this.center(); | |
result.radius = this.size( v1 ).length() * 0.5; | |
return result; | |
}; | |
}(), | |
intersect: function ( box ) { | |
this.min.max( box.min ); | |
this.max.min( box.max ); | |
return this; | |
}, | |
union: function ( box ) { | |
this.min.min( box.min ); | |
this.max.max( box.max ); | |
return this; | |
}, | |
applyMatrix4: function () { | |
var points = [ | |
new THREE.Vector3(), | |
new THREE.Vector3(), | |
new THREE.Vector3(), | |
new THREE.Vector3(), | |
new THREE.Vector3(), | |
new THREE.Vector3(), | |
new THREE.Vector3(), | |
new THREE.Vector3() | |
]; | |
return function ( matrix ) { | |
// NOTE: I am using a binary pattern to specify all 2^3 combinations below | |
points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 | |
points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 | |
points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 | |
points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 | |
points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 | |
points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 | |
points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 | |
points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 | |
this.makeEmpty(); | |
this.setFromPoints( points ); | |
return this; | |
}; | |
}(), | |
translate: function ( offset ) { | |
this.min.add( offset ); | |
this.max.add( offset ); | |
return this; | |
}, | |
equals: function ( box ) { | |
return box.min.equals( this.min ) && box.max.equals( this.max ); | |
}, | |
clone: function () { | |
return new THREE.Box3().copy( this ); | |
} | |
}; | |
// File:src/math/Matrix3.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
* @author WestLangley / http://github.com/WestLangley | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Matrix3 = function () { | |
this.elements = new Float32Array( [ | |
1, 0, 0, | |
0, 1, 0, | |
0, 0, 1 | |
] ); | |
if ( arguments.length > 0 ) { | |
console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); | |
} | |
}; | |
THREE.Matrix3.prototype = { | |
constructor: THREE.Matrix3, | |
set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { | |
var te = this.elements; | |
te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13; | |
te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23; | |
te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33; | |
return this; | |
}, | |
identity: function () { | |
this.set( | |
1, 0, 0, | |
0, 1, 0, | |
0, 0, 1 | |
); | |
return this; | |
}, | |
copy: function ( m ) { | |
var me = m.elements; | |
this.set( | |
me[ 0 ], me[ 3 ], me[ 6 ], | |
me[ 1 ], me[ 4 ], me[ 7 ], | |
me[ 2 ], me[ 5 ], me[ 8 ] | |
); | |
return this; | |
}, | |
multiplyVector3: function ( vector ) { | |
console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); | |
return vector.applyMatrix3( this ); | |
}, | |
multiplyVector3Array: function ( a ) { | |
console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); | |
return this.applyToVector3Array( a ); | |
}, | |
applyToVector3Array: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( array, offset, length ) { | |
if ( offset === undefined ) offset = 0; | |
if ( length === undefined ) length = array.length; | |
for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) { | |
v1.x = array[ j ]; | |
v1.y = array[ j + 1 ]; | |
v1.z = array[ j + 2 ]; | |
v1.applyMatrix3( this ); | |
array[ j ] = v1.x; | |
array[ j + 1 ] = v1.y; | |
array[ j + 2 ] = v1.z; | |
} | |
return array; | |
}; | |
}(), | |
multiplyScalar: function ( s ) { | |
var te = this.elements; | |
te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; | |
te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; | |
te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; | |
return this; | |
}, | |
determinant: function () { | |
var te = this.elements; | |
var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], | |
d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], | |
g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; | |
return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; | |
}, | |
getInverse: function ( matrix, throwOnInvertible ) { | |
// input: THREE.Matrix4 | |
// ( based on http://code.google.com/p/webgl-mjs/ ) | |
var me = matrix.elements; | |
var te = this.elements; | |
te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ]; | |
te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ]; | |
te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ]; | |
te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ]; | |
te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ]; | |
te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ]; | |
te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ]; | |
te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ]; | |
te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ]; | |
var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ]; | |
// no inverse | |
if ( det === 0 ) { | |
var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0"; | |
if ( throwOnInvertible || false ) { | |
throw new Error( msg ); | |
} else { | |
console.warn( msg ); | |
} | |
this.identity(); | |
return this; | |
} | |
this.multiplyScalar( 1.0 / det ); | |
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; | |
}, | |
flattenToArrayOffset: function ( array, offset ) { | |
var te = this.elements; | |
array[ offset ] = te[ 0 ]; | |
array[ offset + 1 ] = te[ 1 ]; | |
array[ offset + 2 ] = te[ 2 ]; | |
array[ offset + 3 ] = te[ 3 ]; | |
array[ offset + 4 ] = te[ 4 ]; | |
array[ offset + 5 ] = te[ 5 ]; | |
array[ offset + 6 ] = te[ 6 ]; | |
array[ offset + 7 ] = te[ 7 ]; | |
array[ offset + 8 ] = te[ 8 ]; | |
return array; | |
}, | |
getNormalMatrix: function ( m ) { | |
// input: THREE.Matrix4 | |
this.getInverse( m ).transpose(); | |
return this; | |
}, | |
transposeIntoArray: function ( r ) { | |
var m = this.elements; | |
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; | |
}, | |
fromArray: function ( array ) { | |
this.elements.set( array ); | |
return this; | |
}, | |
toArray: function () { | |
var te = this.elements; | |
return [ | |
te[ 0 ], te[ 1 ], te[ 2 ], | |
te[ 3 ], te[ 4 ], te[ 5 ], | |
te[ 6 ], te[ 7 ], te[ 8 ] | |
]; | |
}, | |
clone: function () { | |
return new THREE.Matrix3().fromArray( this.elements ); | |
} | |
}; | |
// File:src/math/Matrix4.js | |
/** | |
* @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/ | |
* @author bhouston / http://exocortex.com | |
* @author WestLangley / http://github.com/WestLangley | |
*/ | |
THREE.Matrix4 = function () { | |
this.elements = new Float32Array( [ | |
1, 0, 0, 0, | |
0, 1, 0, 0, | |
0, 0, 1, 0, | |
0, 0, 0, 1 | |
] ); | |
if ( arguments.length > 0 ) { | |
console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); | |
} | |
}; | |
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 ) { | |
this.elements.set( m.elements ); | |
return this; | |
}, | |
extractPosition: function ( m ) { | |
console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); | |
return this.copyPosition( m ); | |
}, | |
copyPosition: 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 () { | |
var v1 = new THREE.Vector3(); | |
return function ( m ) { | |
var te = this.elements; | |
var me = m.elements; | |
var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length(); | |
var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length(); | |
var scaleZ = 1 / v1.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; | |
}; | |
}(), | |
makeRotationFromEuler: function ( euler ) { | |
if ( euler instanceof THREE.Euler === false ) { | |
console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); | |
} | |
var te = this.elements; | |
var x = euler.x, y = euler.y, z = euler.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 ( euler.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 ( euler.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 ( euler.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 ( euler.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 ( euler.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 ( euler.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; | |
} | |
// last column | |
te[ 3 ] = 0; | |
te[ 7 ] = 0; | |
te[ 11 ] = 0; | |
// bottom row | |
te[ 12 ] = 0; | |
te[ 13 ] = 0; | |
te[ 14 ] = 0; | |
te[ 15 ] = 1; | |
return this; | |
}, | |
setRotationFromQuaternion: function ( q ) { | |
console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); | |
return this.makeRotationFromQuaternion( q ); | |
}, | |
makeRotationFromQuaternion: 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 ); | |
// last column | |
te[ 3 ] = 0; | |
te[ 7 ] = 0; | |
te[ 11 ] = 0; | |
// bottom row | |
te[ 12 ] = 0; | |
te[ 13 ] = 0; | |
te[ 14 ] = 0; | |
te[ 15 ] = 1; | |
return this; | |
}, | |
lookAt: function () { | |
var x = new THREE.Vector3(); | |
var y = new THREE.Vector3(); | |
var z = new THREE.Vector3(); | |
return function ( eye, target, up ) { | |
var te = this.elements; | |
z.subVectors( eye, target ).normalize(); | |
if ( z.length() === 0 ) { | |
z.z = 1; | |
} | |
x.crossVectors( up, z ).normalize(); | |
if ( x.length() === 0 ) { | |
z.x += 0.0001; | |
x.crossVectors( up, z ).normalize(); | |
} | |
y.crossVectors( 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 ( m, n ) { | |
if ( n !== undefined ) { | |
console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); | |
return this.multiplyMatrices( m, n ); | |
} | |
return this.multiplyMatrices( this, m ); | |
}, | |
multiplyMatrices: 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; | |
}, | |
multiplyToArray: function ( a, b, r ) { | |
var te = this.elements; | |
this.multiplyMatrices( 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 ( vector ) { | |
console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); | |
return vector.applyProjection( this ); | |
}, | |
multiplyVector4: function ( vector ) { | |
console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); | |
return vector.applyMatrix4( this ); | |
}, | |
multiplyVector3Array: function ( a ) { | |
console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); | |
return this.applyToVector3Array( a ); | |
}, | |
applyToVector3Array: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( array, offset, length ) { | |
if ( offset === undefined ) offset = 0; | |
if ( length === undefined ) length = array.length; | |
for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) { | |
v1.x = array[ j ]; | |
v1.y = array[ j + 1 ]; | |
v1.z = array[ j + 2 ]; | |
v1.applyMatrix4( this ); | |
array[ j ] = v1.x; | |
array[ j + 1 ] = v1.y; | |
array[ j + 2 ] = v1.z; | |
} | |
return array; | |
}; | |
}(), | |
rotateAxis: function ( v ) { | |
console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); | |
v.transformDirection( this ); | |
}, | |
crossVector: function ( vector ) { | |
console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); | |
return vector.applyMatrix4( this ); | |
}, | |
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 ( | |
n41 * ( | |
+ n14 * n23 * n32 | |
- n13 * n24 * n32 | |
- n14 * n22 * n33 | |
+ n12 * n24 * n33 | |
+ n13 * n22 * n34 | |
- n12 * n23 * n34 | |
) + | |
n42 * ( | |
+ n11 * n23 * n34 | |
- n11 * n24 * n33 | |
+ n14 * n21 * n33 | |
- n13 * n21 * n34 | |
+ n13 * n24 * n31 | |
- n14 * n23 * n31 | |
) + | |
n43 * ( | |
+ n11 * n24 * n32 | |
- n11 * n22 * n34 | |
- n14 * n21 * n32 | |
+ n12 * n21 * n34 | |
+ n14 * n22 * n31 | |
- n12 * n24 * n31 | |
) + | |
n44 * ( | |
- n13 * n22 * n31 | |
- n11 * n23 * n32 | |
+ n11 * n22 * n33 | |
+ n13 * n21 * n32 | |
- n12 * n21 * n33 | |
+ n12 * n23 * n31 | |
) | |
); | |
}, | |
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; | |
}, | |
flattenToArrayOffset: function ( array, offset ) { | |
var te = this.elements; | |
array[ offset ] = te[ 0 ]; | |
array[ offset + 1 ] = te[ 1 ]; | |
array[ offset + 2 ] = te[ 2 ]; | |
array[ offset + 3 ] = te[ 3 ]; | |
array[ offset + 4 ] = te[ 4 ]; | |
array[ offset + 5 ] = te[ 5 ]; | |
array[ offset + 6 ] = te[ 6 ]; | |
array[ offset + 7 ] = te[ 7 ]; | |
array[ offset + 8 ] = te[ 8 ]; | |
array[ offset + 9 ] = te[ 9 ]; | |
array[ offset + 10 ] = te[ 10 ]; | |
array[ offset + 11 ] = te[ 11 ]; | |
array[ offset + 12 ] = te[ 12 ]; | |
array[ offset + 13 ] = te[ 13 ]; | |
array[ offset + 14 ] = te[ 14 ]; | |
array[ offset + 15 ] = te[ 15 ]; | |
return array; | |
}, | |
getPosition: function () { | |
var v1 = new THREE.Vector3(); | |
return function () { | |
console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); | |
var te = this.elements; | |
return 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; | |
}, | |
getInverse: function ( m, throwOnInvertible ) { | |
// 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; | |
var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ]; | |
if ( det == 0 ) { | |
var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0"; | |
if ( throwOnInvertible || false ) { | |
throw new Error( msg ); | |
} else { | |
console.warn( msg ); | |
} | |
this.identity(); | |
return this; | |
} | |
this.multiplyScalar( 1 / det ); | |
return this; | |
}, | |
translate: function ( v ) { | |
console.warn( 'THREE.Matrix4: .translate() has been removed.' ); | |
}, | |
rotateX: function ( angle ) { | |
console.warn( 'THREE.Matrix4: .rotateX() has been removed.' ); | |
}, | |
rotateY: function ( angle ) { | |
console.warn( 'THREE.Matrix4: .rotateY() has been removed.' ); | |
}, | |
rotateZ: function ( angle ) { | |
console.warn( 'THREE.Matrix4: .rotateZ() has been removed.' ); | |
}, | |
rotateByAxis: function ( axis, angle ) { | |
console.warn( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); | |
}, | |
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; | |
}, | |
compose: function ( position, quaternion, scale ) { | |
this.makeRotationFromQuaternion( quaternion ); | |
this.scale( scale ); | |
this.setPosition( position ); | |
return this; | |
}, | |
decompose: function () { | |
var vector = new THREE.Vector3(); | |
var matrix = new THREE.Matrix4(); | |
return function ( position, quaternion, scale ) { | |
var te = this.elements; | |
var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); | |
var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); | |
var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); | |
// if determine is negative, we need to invert one scale | |
var det = this.determinant(); | |
if ( det < 0 ) { | |
sx = - sx; | |
} | |
position.x = te[ 12 ]; | |
position.y = te[ 13 ]; | |
position.z = te[ 14 ]; | |
// scale the rotation part | |
matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() | |
var invSX = 1 / sx; | |
var invSY = 1 / sy; | |
var invSZ = 1 / sz; | |
matrix.elements[ 0 ] *= invSX; | |
matrix.elements[ 1 ] *= invSX; | |
matrix.elements[ 2 ] *= invSX; | |
matrix.elements[ 4 ] *= invSY; | |
matrix.elements[ 5 ] *= invSY; | |
matrix.elements[ 6 ] *= invSY; | |
matrix.elements[ 8 ] *= invSZ; | |
matrix.elements[ 9 ] *= invSZ; | |
matrix.elements[ 10 ] *= invSZ; | |
quaternion.setFromRotationMatrix( matrix ); | |
scale.x = sx; | |
scale.y = sy; | |
scale.z = sz; | |
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( THREE.Math.degToRad( fov * 0.5 ) ); | |
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; | |
}, | |
fromArray: function ( array ) { | |
this.elements.set( array ); | |
return this; | |
}, | |
toArray: function () { | |
var te = this.elements; | |
return [ | |
te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ], | |
te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ], | |
te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ], | |
te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ] | |
]; | |
}, | |
clone: function () { | |
return new THREE.Matrix4().fromArray( this.elements ); | |
} | |
}; | |
// File:src/math/Ray.js | |
/** | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Ray = function ( origin, direction ) { | |
this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); | |
this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); | |
}; | |
THREE.Ray.prototype = { | |
constructor: THREE.Ray, | |
set: function ( origin, direction ) { | |
this.origin.copy( origin ); | |
this.direction.copy( direction ); | |
return this; | |
}, | |
copy: function ( ray ) { | |
this.origin.copy( ray.origin ); | |
this.direction.copy( ray.direction ); | |
return this; | |
}, | |
at: function ( t, optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); | |
}, | |
recast: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( t ) { | |
this.origin.copy( this.at( t, v1 ) ); | |
return this; | |
}; | |
}(), | |
closestPointToPoint: function ( point, optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
result.subVectors( point, this.origin ); | |
var directionDistance = result.dot( this.direction ); | |
if ( directionDistance < 0 ) { | |
return result.copy( this.origin ); | |
} | |
return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); | |
}, | |
distanceToPoint: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( point ) { | |
var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); | |
// point behind the ray | |
if ( directionDistance < 0 ) { | |
return this.origin.distanceTo( point ); | |
} | |
v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); | |
return v1.distanceTo( point ); | |
}; | |
}(), | |
distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { | |
// from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp | |
// It returns the min distance between the ray and the segment | |
// defined by v0 and v1 | |
// It can also set two optional targets : | |
// - The closest point on the ray | |
// - The closest point on the segment | |
var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 ); | |
var segDir = v1.clone().sub( v0 ).normalize(); | |
var segExtent = v0.distanceTo( v1 ) * 0.5; | |
var diff = this.origin.clone().sub( segCenter ); | |
var a01 = - this.direction.dot( segDir ); | |
var b0 = diff.dot( this.direction ); | |
var b1 = - diff.dot( segDir ); | |
var c = diff.lengthSq(); | |
var det = Math.abs( 1 - a01 * a01 ); | |
var s0, s1, sqrDist, extDet; | |
if ( det >= 0 ) { | |
// The ray and segment are not parallel. | |
s0 = a01 * b1 - b0; | |
s1 = a01 * b0 - b1; | |
extDet = segExtent * det; | |
if ( s0 >= 0 ) { | |
if ( s1 >= - extDet ) { | |
if ( s1 <= extDet ) { | |
// region 0 | |
// Minimum at interior points of ray and segment. | |
var invDet = 1 / det; | |
s0 *= invDet; | |
s1 *= invDet; | |
sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; | |
} else { | |
// region 1 | |
s1 = segExtent; | |
s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); | |
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; | |
} | |
} else { | |
// region 5 | |
s1 = - segExtent; | |
s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); | |
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; | |
} | |
} else { | |
if ( s1 <= - extDet ) { | |
// region 4 | |
s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); | |
s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); | |
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; | |
} else if ( s1 <= extDet ) { | |
// region 3 | |
s0 = 0; | |
s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); | |
sqrDist = s1 * ( s1 + 2 * b1 ) + c; | |
} else { | |
// region 2 | |
s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); | |
s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); | |
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; | |
} | |
} | |
} else { | |
// Ray and segment are parallel. | |
s1 = ( a01 > 0 ) ? - segExtent : segExtent; | |
s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); | |
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; | |
} | |
if ( optionalPointOnRay ) { | |
optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) ); | |
} | |
if ( optionalPointOnSegment ) { | |
optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) ); | |
} | |
return sqrDist; | |
}, | |
isIntersectionSphere: function ( sphere ) { | |
return this.distanceToPoint( sphere.center ) <= sphere.radius; | |
}, | |
intersectSphere: function () { | |
// from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/ | |
var v1 = new THREE.Vector3(); | |
return function ( sphere, optionalTarget ) { | |
v1.subVectors( sphere.center, this.origin ); | |
var tca = v1.dot( this.direction ); | |
var d2 = v1.dot( v1 ) - tca * tca; | |
var radius2 = sphere.radius * sphere.radius; | |
if ( d2 > radius2 ) return null; | |
var thc = Math.sqrt( radius2 - d2 ); | |
// t0 = first intersect point - entrance on front of sphere | |
var t0 = tca - thc; | |
// t1 = second intersect point - exit point on back of sphere | |
var t1 = tca + thc; | |
// test to see if both t0 and t1 are behind the ray - if so, return null | |
if ( t0 < 0 && t1 < 0 ) return null; | |
// test to see if t0 is behind the ray: | |
// if it is, the ray is inside the sphere, so return the second exit point scaled by t1, | |
// in order to always return an intersect point that is in front of the ray. | |
if ( t0 < 0 ) return this.at( t1, optionalTarget ); | |
// else t0 is in front of the ray, so return the first collision point scaled by t0 | |
return this.at( t0, optionalTarget ); | |
} | |
}(), | |
isIntersectionPlane: function ( plane ) { | |
// check if the ray lies on the plane first | |
var distToPoint = plane.distanceToPoint( this.origin ); | |
if ( distToPoint === 0 ) { | |
return true; | |
} | |
var denominator = plane.normal.dot( this.direction ); | |
if ( denominator * distToPoint < 0 ) { | |
return true; | |
} | |
// ray origin is behind the plane (and is pointing behind it) | |
return false; | |
}, | |
distanceToPlane: function ( plane ) { | |
var denominator = plane.normal.dot( this.direction ); | |
if ( denominator == 0 ) { | |
// line is coplanar, return origin | |
if ( plane.distanceToPoint( this.origin ) == 0 ) { | |
return 0; | |
} | |
// Null is preferable to undefined since undefined means.... it is undefined | |
return null; | |
} | |
var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; | |
// Return if the ray never intersects the plane | |
return t >= 0 ? t : null; | |
}, | |
intersectPlane: function ( plane, optionalTarget ) { | |
var t = this.distanceToPlane( plane ); | |
if ( t === null ) { | |
return null; | |
} | |
return this.at( t, optionalTarget ); | |
}, | |
isIntersectionBox: function () { | |
var v = new THREE.Vector3(); | |
return function ( box ) { | |
return this.intersectBox( box, v ) !== null; | |
}; | |
}(), | |
intersectBox: function ( box , optionalTarget ) { | |
// http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/ | |
var tmin,tmax,tymin,tymax,tzmin,tzmax; | |
var invdirx = 1 / this.direction.x, | |
invdiry = 1 / this.direction.y, | |
invdirz = 1 / this.direction.z; | |
var origin = this.origin; | |
if ( invdirx >= 0 ) { | |
tmin = ( box.min.x - origin.x ) * invdirx; | |
tmax = ( box.max.x - origin.x ) * invdirx; | |
} else { | |
tmin = ( box.max.x - origin.x ) * invdirx; | |
tmax = ( box.min.x - origin.x ) * invdirx; | |
} | |
if ( invdiry >= 0 ) { | |
tymin = ( box.min.y - origin.y ) * invdiry; | |
tymax = ( box.max.y - origin.y ) * invdiry; | |
} else { | |
tymin = ( box.max.y - origin.y ) * invdiry; | |
tymax = ( box.min.y - origin.y ) * invdiry; | |
} | |
if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; | |
// These lines also handle the case where tmin or tmax is NaN | |
// (result of 0 * Infinity). x !== x returns true if x is NaN | |
if ( tymin > tmin || tmin !== tmin ) tmin = tymin; | |
if ( tymax < tmax || tmax !== tmax ) tmax = tymax; | |
if ( invdirz >= 0 ) { | |
tzmin = ( box.min.z - origin.z ) * invdirz; | |
tzmax = ( box.max.z - origin.z ) * invdirz; | |
} else { | |
tzmin = ( box.max.z - origin.z ) * invdirz; | |
tzmax = ( box.min.z - origin.z ) * invdirz; | |
} | |
if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; | |
if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; | |
if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; | |
//return point closest to the ray (positive side) | |
if ( tmax < 0 ) return null; | |
return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); | |
}, | |
intersectTriangle: function () { | |
// Compute the offset origin, edges, and normal. | |
var diff = new THREE.Vector3(); | |
var edge1 = new THREE.Vector3(); | |
var edge2 = new THREE.Vector3(); | |
var normal = new THREE.Vector3(); | |
return function ( a, b, c, backfaceCulling, optionalTarget ) { | |
// from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp | |
edge1.subVectors( b, a ); | |
edge2.subVectors( c, a ); | |
normal.crossVectors( edge1, edge2 ); | |
// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, | |
// E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by | |
// |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) | |
// |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) | |
// |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) | |
var DdN = this.direction.dot( normal ); | |
var sign; | |
if ( DdN > 0 ) { | |
if ( backfaceCulling ) return null; | |
sign = 1; | |
} else if ( DdN < 0 ) { | |
sign = - 1; | |
DdN = - DdN; | |
} else { | |
return null; | |
} | |
diff.subVectors( this.origin, a ); | |
var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); | |
// b1 < 0, no intersection | |
if ( DdQxE2 < 0 ) { | |
return null; | |
} | |
var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); | |
// b2 < 0, no intersection | |
if ( DdE1xQ < 0 ) { | |
return null; | |
} | |
// b1+b2 > 1, no intersection | |
if ( DdQxE2 + DdE1xQ > DdN ) { | |
return null; | |
} | |
// Line intersects triangle, check if ray does. | |
var QdN = - sign * diff.dot( normal ); | |
// t < 0, no intersection | |
if ( QdN < 0 ) { | |
return null; | |
} | |
// Ray intersects triangle. | |
return this.at( QdN / DdN, optionalTarget ); | |
}; | |
}(), | |
applyMatrix4: function ( matrix4 ) { | |
this.direction.add( this.origin ).applyMatrix4( matrix4 ); | |
this.origin.applyMatrix4( matrix4 ); | |
this.direction.sub( this.origin ); | |
this.direction.normalize(); | |
return this; | |
}, | |
equals: function ( ray ) { | |
return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); | |
}, | |
clone: function () { | |
return new THREE.Ray().copy( this ); | |
} | |
}; | |
// File:src/math/Sphere.js | |
/** | |
* @author bhouston / http://exocortex.com | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Sphere = function ( center, radius ) { | |
this.center = ( center !== undefined ) ? center : new THREE.Vector3(); | |
this.radius = ( radius !== undefined ) ? radius : 0; | |
}; | |
THREE.Sphere.prototype = { | |
constructor: THREE.Sphere, | |
set: function ( center, radius ) { | |
this.center.copy( center ); | |
this.radius = radius; | |
return this; | |
}, | |
setFromPoints: function () { | |
var box = new THREE.Box3(); | |
return function ( points, optionalCenter ) { | |
var center = this.center; | |
if ( optionalCenter !== undefined ) { | |
center.copy( optionalCenter ); | |
} else { | |
box.setFromPoints( points ).center( center ); | |
} | |
var maxRadiusSq = 0; | |
for ( var i = 0, il = points.length; i < il; i ++ ) { | |
maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); | |
} | |
this.radius = Math.sqrt( maxRadiusSq ); | |
return this; | |
}; | |
}(), | |
copy: function ( sphere ) { | |
this.center.copy( sphere.center ); | |
this.radius = sphere.radius; | |
return this; | |
}, | |
empty: function () { | |
return ( this.radius <= 0 ); | |
}, | |
containsPoint: function ( point ) { | |
return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); | |
}, | |
distanceToPoint: function ( point ) { | |
return ( point.distanceTo( this.center ) - this.radius ); | |
}, | |
intersectsSphere: function ( sphere ) { | |
var radiusSum = this.radius + sphere.radius; | |
return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); | |
}, | |
clampPoint: function ( point, optionalTarget ) { | |
var deltaLengthSq = this.center.distanceToSquared( point ); | |
var result = optionalTarget || new THREE.Vector3(); | |
result.copy( point ); | |
if ( deltaLengthSq > ( this.radius * this.radius ) ) { | |
result.sub( this.center ).normalize(); | |
result.multiplyScalar( this.radius ).add( this.center ); | |
} | |
return result; | |
}, | |
getBoundingBox: function ( optionalTarget ) { | |
var box = optionalTarget || new THREE.Box3(); | |
box.set( this.center, this.center ); | |
box.expandByScalar( this.radius ); | |
return box; | |
}, | |
applyMatrix4: function ( matrix ) { | |
this.center.applyMatrix4( matrix ); | |
this.radius = this.radius * matrix.getMaxScaleOnAxis(); | |
return this; | |
}, | |
translate: function ( offset ) { | |
this.center.add( offset ); | |
return this; | |
}, | |
equals: function ( sphere ) { | |
return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); | |
}, | |
clone: function () { | |
return new THREE.Sphere().copy( this ); | |
} | |
}; | |
// File:src/math/Frustum.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { | |
this.planes = [ | |
( p0 !== undefined ) ? p0 : new THREE.Plane(), | |
( p1 !== undefined ) ? p1 : new THREE.Plane(), | |
( p2 !== undefined ) ? p2 : new THREE.Plane(), | |
( p3 !== undefined ) ? p3 : new THREE.Plane(), | |
( p4 !== undefined ) ? p4 : new THREE.Plane(), | |
( p5 !== undefined ) ? p5 : new THREE.Plane() | |
]; | |
}; | |
THREE.Frustum.prototype = { | |
constructor: THREE.Frustum, | |
set: function ( p0, p1, p2, p3, p4, p5 ) { | |
var planes = this.planes; | |
planes[ 0 ].copy( p0 ); | |
planes[ 1 ].copy( p1 ); | |
planes[ 2 ].copy( p2 ); | |
planes[ 3 ].copy( p3 ); | |
planes[ 4 ].copy( p4 ); | |
planes[ 5 ].copy( p5 ); | |
return this; | |
}, | |
copy: function ( frustum ) { | |
var planes = this.planes; | |
for ( var i = 0; i < 6; i ++ ) { | |
planes[ i ].copy( frustum.planes[ i ] ); | |
} | |
return this; | |
}, | |
setFromMatrix: function ( m ) { | |
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 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); | |
planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); | |
planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); | |
planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); | |
planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); | |
planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); | |
return this; | |
}, | |
intersectsObject: function () { | |
var sphere = new THREE.Sphere(); | |
return function ( object ) { | |
var geometry = object.geometry; | |
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); | |
sphere.copy( geometry.boundingSphere ); | |
sphere.applyMatrix4( object.matrixWorld ); | |
return this.intersectsSphere( sphere ); | |
}; | |
}(), | |
intersectsSphere: function ( sphere ) { | |
var planes = this.planes; | |
var center = sphere.center; | |
var negRadius = - sphere.radius; | |
for ( var i = 0; i < 6; i ++ ) { | |
var distance = planes[ i ].distanceToPoint( center ); | |
if ( distance < negRadius ) { | |
return false; | |
} | |
} | |
return true; | |
}, | |
intersectsBox: function () { | |
var p1 = new THREE.Vector3(), | |
p2 = new THREE.Vector3(); | |
return function ( box ) { | |
var planes = this.planes; | |
for ( var i = 0; i < 6 ; i ++ ) { | |
var plane = planes[ i ]; | |
p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; | |
p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; | |
p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; | |
p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; | |
p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; | |
p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; | |
var d1 = plane.distanceToPoint( p1 ); | |
var d2 = plane.distanceToPoint( p2 ); | |
// if both outside plane, no intersection | |
if ( d1 < 0 && d2 < 0 ) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
}(), | |
containsPoint: function ( point ) { | |
var planes = this.planes; | |
for ( var i = 0; i < 6; i ++ ) { | |
if ( planes[ i ].distanceToPoint( point ) < 0 ) { | |
return false; | |
} | |
} | |
return true; | |
}, | |
clone: function () { | |
return new THREE.Frustum().copy( this ); | |
} | |
}; | |
// File:src/math/Plane.js | |
/** | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Plane = function ( normal, constant ) { | |
this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); | |
this.constant = ( constant !== undefined ) ? constant : 0; | |
}; | |
THREE.Plane.prototype = { | |
constructor: THREE.Plane, | |
set: function ( normal, constant ) { | |
this.normal.copy( normal ); | |
this.constant = constant; | |
return this; | |
}, | |
setComponents: function ( x, y, z, w ) { | |
this.normal.set( x, y, z ); | |
this.constant = w; | |
return this; | |
}, | |
setFromNormalAndCoplanarPoint: function ( normal, point ) { | |
this.normal.copy( normal ); | |
this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized | |
return this; | |
}, | |
setFromCoplanarPoints: function () { | |
var v1 = new THREE.Vector3(); | |
var v2 = new THREE.Vector3(); | |
return function ( a, b, c ) { | |
var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); | |
// Q: should an error be thrown if normal is zero (e.g. degenerate plane)? | |
this.setFromNormalAndCoplanarPoint( normal, a ); | |
return this; | |
}; | |
}(), | |
copy: function ( plane ) { | |
this.normal.copy( plane.normal ); | |
this.constant = plane.constant; | |
return this; | |
}, | |
normalize: function () { | |
// Note: will lead to a divide by zero if the plane is invalid. | |
var inverseNormalLength = 1.0 / this.normal.length(); | |
this.normal.multiplyScalar( inverseNormalLength ); | |
this.constant *= inverseNormalLength; | |
return this; | |
}, | |
negate: function () { | |
this.constant *= - 1; | |
this.normal.negate(); | |
return this; | |
}, | |
distanceToPoint: function ( point ) { | |
return this.normal.dot( point ) + this.constant; | |
}, | |
distanceToSphere: function ( sphere ) { | |
return this.distanceToPoint( sphere.center ) - sphere.radius; | |
}, | |
projectPoint: function ( point, optionalTarget ) { | |
return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); | |
}, | |
orthoPoint: function ( point, optionalTarget ) { | |
var perpendicularMagnitude = this.distanceToPoint( point ); | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); | |
}, | |
isIntersectionLine: function ( line ) { | |
// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. | |
var startSign = this.distanceToPoint( line.start ); | |
var endSign = this.distanceToPoint( line.end ); | |
return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); | |
}, | |
intersectLine: function () { | |
var v1 = new THREE.Vector3(); | |
return function ( line, optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
var direction = line.delta( v1 ); | |
var denominator = this.normal.dot( direction ); | |
if ( denominator == 0 ) { | |
// line is coplanar, return origin | |
if ( this.distanceToPoint( line.start ) == 0 ) { | |
return result.copy( line.start ); | |
} | |
// Unsure if this is the correct method to handle this case. | |
return undefined; | |
} | |
var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; | |
if ( t < 0 || t > 1 ) { | |
return undefined; | |
} | |
return result.copy( direction ).multiplyScalar( t ).add( line.start ); | |
}; | |
}(), | |
coplanarPoint: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.copy( this.normal ).multiplyScalar( - this.constant ); | |
}, | |
applyMatrix4: function () { | |
var v1 = new THREE.Vector3(); | |
var v2 = new THREE.Vector3(); | |
var m1 = new THREE.Matrix3(); | |
return function ( matrix, optionalNormalMatrix ) { | |
// compute new normal based on theory here: | |
// http://www.songho.ca/opengl/gl_normaltransform.html | |
var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); | |
var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix ); | |
var newCoplanarPoint = this.coplanarPoint( v2 ); | |
newCoplanarPoint.applyMatrix4( matrix ); | |
this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint ); | |
return this; | |
}; | |
}(), | |
translate: function ( offset ) { | |
this.constant = this.constant - offset.dot( this.normal ); | |
return this; | |
}, | |
equals: function ( plane ) { | |
return plane.normal.equals( this.normal ) && ( plane.constant == this.constant ); | |
}, | |
clone: function () { | |
return new THREE.Plane().copy( this ); | |
} | |
}; | |
// File:src/math/Math.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Math = { | |
generateUUID: function () { | |
// http://www.broofa.com/Tools/Math.uuid.htm | |
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); | |
var uuid = new Array( 36 ); | |
var rnd = 0, r; | |
return function () { | |
for ( var i = 0; i < 36; i ++ ) { | |
if ( i == 8 || i == 13 || i == 18 || i == 23 ) { | |
uuid[ i ] = '-'; | |
} else if ( i == 14 ) { | |
uuid[ i ] = '4'; | |
} else { | |
if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; | |
r = rnd & 0xf; | |
rnd = rnd >> 4; | |
uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ]; | |
} | |
} | |
return uuid.join( '' ); | |
}; | |
}(), | |
// 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 ); | |
}, | |
// http://en.wikipedia.org/wiki/Smoothstep | |
smoothstep: function ( x, min, max ) { | |
if ( x <= min ) return 0; | |
if ( x >= max ) return 1; | |
x = ( x - min ) / ( max - min ); | |
return x * x * ( 3 - 2 * x ); | |
}, | |
smootherstep: function ( x, min, max ) { | |
if ( x <= min ) return 0; | |
if ( x >= max ) return 1; | |
x = ( x - min ) / ( max - min ); | |
return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); | |
}, | |
// 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() ); | |
}, | |
degToRad: function () { | |
var degreeToRadiansFactor = Math.PI / 180; | |
return function ( degrees ) { | |
return degrees * degreeToRadiansFactor; | |
}; | |
}(), | |
radToDeg: function () { | |
var radianToDegreesFactor = 180 / Math.PI; | |
return function ( radians ) { | |
return radians * radianToDegreesFactor; | |
}; | |
}(), | |
isPowerOfTwo: function ( value ) { | |
return ( value & ( value - 1 ) ) === 0 && value !== 0; | |
} | |
}; | |
// File:src/math/Spline.js | |
/** | |
* 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; | |
}; | |
}; | |
// File:src/math/Triangle.js | |
/** | |
* @author bhouston / http://exocortex.com | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Triangle = function ( a, b, c ) { | |
this.a = ( a !== undefined ) ? a : new THREE.Vector3(); | |
this.b = ( b !== undefined ) ? b : new THREE.Vector3(); | |
this.c = ( c !== undefined ) ? c : new THREE.Vector3(); | |
}; | |
THREE.Triangle.normal = function () { | |
var v0 = new THREE.Vector3(); | |
return function ( a, b, c, optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
result.subVectors( c, b ); | |
v0.subVectors( a, b ); | |
result.cross( v0 ); | |
var resultLengthSq = result.lengthSq(); | |
if ( resultLengthSq > 0 ) { | |
return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); | |
} | |
return result.set( 0, 0, 0 ); | |
}; | |
}(); | |
// static/instance method to calculate barycoordinates | |
// based on: http://www.blackpawn.com/texts/pointinpoly/default.html | |
THREE.Triangle.barycoordFromPoint = function () { | |
var v0 = new THREE.Vector3(); | |
var v1 = new THREE.Vector3(); | |
var v2 = new THREE.Vector3(); | |
return function ( point, a, b, c, optionalTarget ) { | |
v0.subVectors( c, a ); | |
v1.subVectors( b, a ); | |
v2.subVectors( point, 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 denom = ( dot00 * dot11 - dot01 * dot01 ); | |
var result = optionalTarget || new THREE.Vector3(); | |
// colinear or singular triangle | |
if ( denom == 0 ) { | |
// arbitrary location outside of triangle? | |
// not sure if this is the best idea, maybe should be returning undefined | |
return result.set( - 2, - 1, - 1 ); | |
} | |
var invDenom = 1 / denom; | |
var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; | |
var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; | |
// barycoordinates must always sum to 1 | |
return result.set( 1 - u - v, v, u ); | |
}; | |
}(); | |
THREE.Triangle.containsPoint = function () { | |
var v1 = new THREE.Vector3(); | |
return function ( point, a, b, c ) { | |
var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); | |
return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); | |
}; | |
}(); | |
THREE.Triangle.prototype = { | |
constructor: THREE.Triangle, | |
set: function ( a, b, c ) { | |
this.a.copy( a ); | |
this.b.copy( b ); | |
this.c.copy( c ); | |
return this; | |
}, | |
setFromPointsAndIndices: function ( points, i0, i1, i2 ) { | |
this.a.copy( points[ i0 ] ); | |
this.b.copy( points[ i1 ] ); | |
this.c.copy( points[ i2 ] ); | |
return this; | |
}, | |
copy: function ( triangle ) { | |
this.a.copy( triangle.a ); | |
this.b.copy( triangle.b ); | |
this.c.copy( triangle.c ); | |
return this; | |
}, | |
area: function () { | |
var v0 = new THREE.Vector3(); | |
var v1 = new THREE.Vector3(); | |
return function () { | |
v0.subVectors( this.c, this.b ); | |
v1.subVectors( this.a, this.b ); | |
return v0.cross( v1 ).length() * 0.5; | |
}; | |
}(), | |
midpoint: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); | |
}, | |
normal: function ( optionalTarget ) { | |
return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); | |
}, | |
plane: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Plane(); | |
return result.setFromCoplanarPoints( this.a, this.b, this.c ); | |
}, | |
barycoordFromPoint: function ( point, optionalTarget ) { | |
return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); | |
}, | |
containsPoint: function ( point ) { | |
return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); | |
}, | |
equals: function ( triangle ) { | |
return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); | |
}, | |
clone: function () { | |
return new THREE.Triangle().copy( this ); | |
} | |
}; | |
// File:src/core/Clock.js | |
/** | |
* @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 = { | |
constructor: THREE.Clock, | |
start: function () { | |
this.startTime = self.performance !== undefined && self.performance.now !== undefined | |
? self.performance.now() | |
: Date.now(); | |
this.oldTime = this.startTime; | |
this.running = true; | |
}, | |
stop: function () { | |
this.getElapsedTime(); | |
this.running = false; | |
}, | |
getElapsedTime: function () { | |
this.getDelta(); | |
return this.elapsedTime; | |
}, | |
getDelta: function () { | |
var diff = 0; | |
if ( this.autoStart && ! this.running ) { | |
this.start(); | |
} | |
if ( this.running ) { | |
var newTime = self.performance !== undefined && self.performance.now !== undefined | |
? self.performance.now() | |
: Date.now(); | |
diff = 0.001 * ( newTime - this.oldTime ); | |
this.oldTime = newTime; | |
this.elapsedTime += diff; | |
} | |
return diff; | |
} | |
}; | |
// File:src/core/EventDispatcher.js | |
/** | |
* https://github.com/mrdoob/eventdispatcher.js/ | |
*/ | |
THREE.EventDispatcher = function () {} | |
THREE.EventDispatcher.prototype = { | |
constructor: THREE.EventDispatcher, | |
apply: function ( object ) { | |
object.addEventListener = THREE.EventDispatcher.prototype.addEventListener; | |
object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener; | |
object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener; | |
object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent; | |
}, | |
addEventListener: function ( type, listener ) { | |
if ( this._listeners === undefined ) this._listeners = {}; | |
var listeners = this._listeners; | |
if ( listeners[ type ] === undefined ) { | |
listeners[ type ] = []; | |
} | |
if ( listeners[ type ].indexOf( listener ) === - 1 ) { | |
listeners[ type ].push( listener ); | |
} | |
}, | |
hasEventListener: function ( type, listener ) { | |
if ( this._listeners === undefined ) return false; | |
var listeners = this._listeners; | |
if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { | |
return true; | |
} | |
return false; | |
}, | |
removeEventListener: function ( type, listener ) { | |
if ( this._listeners === undefined ) return; | |
var listeners = this._listeners; | |
var listenerArray = listeners[ type ]; | |
if ( listenerArray !== undefined ) { | |
var index = listenerArray.indexOf( listener ); | |
if ( index !== - 1 ) { | |
listenerArray.splice( index, 1 ); | |
} | |
} | |
}, | |
dispatchEvent: function ( event ) { | |
if ( this._listeners === undefined ) return; | |
var listeners = this._listeners; | |
var listenerArray = listeners[ event.type ]; | |
if ( listenerArray !== undefined ) { | |
event.target = this; | |
var array = []; | |
var length = listenerArray.length; | |
for ( var i = 0; i < length; i ++ ) { | |
array[ i ] = listenerArray[ i ]; | |
} | |
for ( var i = 0; i < length; i ++ ) { | |
array[ i ].call( this, event ); | |
} | |
} | |
} | |
}; | |
// File:src/core/Raycaster.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author bhouston / http://exocortex.com/ | |
* @author stephomi / http://stephaneginier.com/ | |
*/ | |
( function ( THREE ) { | |
THREE.Raycaster = function ( origin, direction, near, far ) { | |
this.ray = new THREE.Ray( origin, direction ); | |
// direction is assumed to be normalized (for accurate distance calculations) | |
this.near = near || 0; | |
this.far = far || Infinity; | |
this.params = { | |
Sprite: {}, | |
Mesh: {}, | |
PointCloud: { threshold: 1 }, | |
LOD: {}, | |
Line: {} | |
}; | |
}; | |
var descSort = function ( a, b ) { | |
return a.distance - b.distance; | |
}; | |
var intersectObject = function ( object, raycaster, intersects, recursive ) { | |
object.raycast( raycaster, intersects ); | |
if ( recursive === true ) { | |
var children = object.children; | |
for ( var i = 0, l = children.length; i < l; i ++ ) { | |
intersectObject( children[ i ], raycaster, intersects, true ); | |
} | |
} | |
}; | |
// | |
THREE.Raycaster.prototype = { | |
constructor: THREE.Raycaster, | |
precision: 0.0001, | |
linePrecision: 1, | |
set: function ( origin, direction ) { | |
this.ray.set( origin, direction ); | |
// direction is assumed to be normalized (for accurate distance calculations) | |
}, | |
intersectObject: function ( object, recursive ) { | |
var intersects = []; | |
intersectObject( object, this, intersects, recursive ); | |
intersects.sort( descSort ); | |
return intersects; | |
}, | |
intersectObjects: function ( objects, recursive ) { | |
var intersects = []; | |
if ( objects instanceof Array === false ) { | |
console.log( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); | |
return intersects; | |
} | |
for ( var i = 0, l = objects.length; i < l; i ++ ) { | |
intersectObject( objects[ i ], this, intersects, recursive ); | |
} | |
intersects.sort( descSort ); | |
return intersects; | |
} | |
}; | |
}( THREE ) ); | |
// File:src/core/Object3D.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author mikael emtinger / http://gomo.se/ | |
* @author alteredq / http://alteredqualia.com/ | |
* @author WestLangley / http://github.com/WestLangley | |
*/ | |
THREE.Object3D = function () { | |
Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); | |
this.uuid = THREE.Math.generateUUID(); | |
this.name = ''; | |
this.type = 'Object3D'; | |
this.parent = undefined; | |
this.children = []; | |
this.up = THREE.Object3D.DefaultUp.clone(); | |
var scope = this; | |
var position = new THREE.Vector3(); | |
var rotation = new THREE.Euler(); | |
var quaternion = new THREE.Quaternion(); | |
var scale = new THREE.Vector3( 1, 1, 1 ); | |
var onRotationChange = function () { | |
quaternion.setFromEuler( rotation, false ); | |
}; | |
var onQuaternionChange = function () { | |
rotation.setFromQuaternion( quaternion, undefined, false ); | |
}; | |
rotation.onChange( onRotationChange ); | |
quaternion.onChange( onQuaternionChange ); | |
Object.defineProperties( this, { | |
position: { | |
enumerable: true, | |
value: position | |
}, | |
rotation: { | |
enumerable: true, | |
value: rotation | |
}, | |
quaternion: { | |
enumerable: true, | |
value: quaternion | |
}, | |
scale: { | |
enumerable: true, | |
value: scale | |
}, | |
} ); | |
this.renderDepth = null; | |
this.rotationAutoUpdate = true; | |
this.matrix = new THREE.Matrix4(); | |
this.matrixWorld = new THREE.Matrix4(); | |
this.matrixAutoUpdate = true; | |
this.matrixWorldNeedsUpdate = false; | |
this.visible = true; | |
this.castShadow = false; | |
this.receiveShadow = false; | |
this.frustumCulled = true; | |
this.userData = {}; | |
}; | |
THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); | |
THREE.Object3D.prototype = { | |
constructor: THREE.Object3D, | |
get eulerOrder () { | |
console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); | |
return this.rotation.order; | |
}, | |
set eulerOrder ( value ) { | |
console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); | |
this.rotation.order = value; | |
}, | |
get useQuaternion () { | |
console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); | |
}, | |
set useQuaternion ( value ) { | |
console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); | |
}, | |
applyMatrix: function ( matrix ) { | |
this.matrix.multiplyMatrices( matrix, this.matrix ); | |
this.matrix.decompose( this.position, this.quaternion, this.scale ); | |
}, | |
setRotationFromAxisAngle: function ( axis, angle ) { | |
// assumes axis is normalized | |
this.quaternion.setFromAxisAngle( axis, angle ); | |
}, | |
setRotationFromEuler: function ( euler ) { | |
this.quaternion.setFromEuler( euler, true ); | |
}, | |
setRotationFromMatrix: function ( m ) { | |
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) | |
this.quaternion.setFromRotationMatrix( m ); | |
}, | |
setRotationFromQuaternion: function ( q ) { | |
// assumes q is normalized | |
this.quaternion.copy( q ); | |
}, | |
rotateOnAxis: function () { | |
// rotate object on axis in object space | |
// axis is assumed to be normalized | |
var q1 = new THREE.Quaternion(); | |
return function ( axis, angle ) { | |
q1.setFromAxisAngle( axis, angle ); | |
this.quaternion.multiply( q1 ); | |
return this; | |
} | |
}(), | |
rotateX: function () { | |
var v1 = new THREE.Vector3( 1, 0, 0 ); | |
return function ( angle ) { | |
return this.rotateOnAxis( v1, angle ); | |
}; | |
}(), | |
rotateY: function () { | |
var v1 = new THREE.Vector3( 0, 1, 0 ); | |
return function ( angle ) { | |
return this.rotateOnAxis( v1, angle ); | |
}; | |
}(), | |
rotateZ: function () { | |
var v1 = new THREE.Vector3( 0, 0, 1 ); | |
return function ( angle ) { | |
return this.rotateOnAxis( v1, angle ); | |
}; | |
}(), | |
translateOnAxis: function () { | |
// translate object by distance along axis in object space | |
// axis is assumed to be normalized | |
var v1 = new THREE.Vector3(); | |
return function ( axis, distance ) { | |
v1.copy( axis ).applyQuaternion( this.quaternion ); | |
this.position.add( v1.multiplyScalar( distance ) ); | |
return this; | |
} | |
}(), | |
translate: function ( distance, axis ) { | |
console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); | |
return this.translateOnAxis( axis, distance ); | |
}, | |
translateX: function () { | |
var v1 = new THREE.Vector3( 1, 0, 0 ); | |
return function ( distance ) { | |
return this.translateOnAxis( v1, distance ); | |
}; | |
}(), | |
translateY: function () { | |
var v1 = new THREE.Vector3( 0, 1, 0 ); | |
return function ( distance ) { | |
return this.translateOnAxis( v1, distance ); | |
}; | |
}(), | |
translateZ: function () { | |
var v1 = new THREE.Vector3( 0, 0, 1 ); | |
return function ( distance ) { | |
return this.translateOnAxis( v1, distance ); | |
}; | |
}(), | |
localToWorld: function ( vector ) { | |
return vector.applyMatrix4( this.matrixWorld ); | |
}, | |
worldToLocal: function () { | |
var m1 = new THREE.Matrix4(); | |
return function ( vector ) { | |
return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); | |
}; | |
}(), | |
lookAt: function () { | |
// This routine does not support objects with rotated and/or translated parent(s) | |
var m1 = new THREE.Matrix4(); | |
return function ( vector ) { | |
m1.lookAt( vector, this.position, this.up ); | |
this.quaternion.setFromRotationMatrix( m1 ); | |
}; | |
}(), | |
add: function ( object ) { | |
if ( arguments.length > 1 ) { | |
for ( var i = 0; i < arguments.length; i++ ) { | |
this.add( arguments[ i ] ); | |
} | |
return this; | |
}; | |
if ( object === this ) { | |
console.error( "THREE.Object3D.add:", object, "can't be added as a child of itself." ); | |
return this; | |
} | |
if ( object instanceof THREE.Object3D ) { | |
if ( object.parent !== undefined ) { | |
object.parent.remove( object ); | |
} | |
object.parent = this; | |
object.dispatchEvent( { type: 'added' } ); | |
this.children.push( object ); | |
} else { | |
console.error( "THREE.Object3D.add:", object, "is not an instance of THREE.Object3D." ); | |
} | |
return this; | |
}, | |
remove: function ( object ) { | |
if ( arguments.length > 1 ) { | |
for ( var i = 0; i < arguments.length; i++ ) { | |
this.remove( arguments[ i ] ); | |
} | |
}; | |
var index = this.children.indexOf( object ); | |
if ( index !== - 1 ) { | |
object.parent = undefined; | |
object.dispatchEvent( { type: 'removed' } ); | |
this.children.splice( index, 1 ); | |
} | |
}, | |
getChildByName: function ( name, recursive ) { | |
console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); | |
return this.getObjectByName( name, recursive ); | |
}, | |
getObjectById: function ( id, recursive ) { | |
if ( this.id === id ) return this; | |
for ( var i = 0, l = this.children.length; i < l; i ++ ) { | |
var child = this.children[ i ]; | |
var object = child.getObjectById( id, recursive ); | |
if ( object !== undefined ) { | |
return object; | |
} | |
} | |
return undefined; | |
}, | |
getObjectByName: function ( name, recursive ) { | |
if ( this.name === name ) return this; | |
for ( var i = 0, l = this.children.length; i < l; i ++ ) { | |
var child = this.children[ i ]; | |
var object = child.getObjectByName( name, recursive ); | |
if ( object !== undefined ) { | |
return object; | |
} | |
} | |
return undefined; | |
}, | |
getWorldPosition: function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
this.updateMatrixWorld( true ); | |
return result.setFromMatrixPosition( this.matrixWorld ); | |
}, | |
getWorldQuaternion: function () { | |
var position = new THREE.Vector3(); | |
var scale = new THREE.Vector3(); | |
return function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Quaternion(); | |
this.updateMatrixWorld( true ); | |
this.matrixWorld.decompose( position, result, scale ); | |
return result; | |
} | |
}(), | |
getWorldRotation: function () { | |
var quaternion = new THREE.Quaternion(); | |
return function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Euler(); | |
this.getWorldQuaternion( quaternion ); | |
return result.setFromQuaternion( quaternion, this.rotation.order, false ); | |
} | |
}(), | |
getWorldScale: function () { | |
var position = new THREE.Vector3(); | |
var quaternion = new THREE.Quaternion(); | |
return function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
this.updateMatrixWorld( true ); | |
this.matrixWorld.decompose( position, quaternion, result ); | |
return result; | |
} | |
}(), | |
getWorldDirection: function () { | |
var quaternion = new THREE.Quaternion(); | |
return function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
this.getWorldQuaternion( quaternion ); | |
return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); | |
} | |
}(), | |
raycast: function () {}, | |
traverse: function ( callback ) { | |
callback( this ); | |
for ( var i = 0, l = this.children.length; i < l; i ++ ) { | |
this.children[ i ].traverse( callback ); | |
} | |
}, | |
traverseVisible: function ( callback ) { | |
if ( this.visible === false ) return; | |
callback( this ); | |
for ( var i = 0, l = this.children.length; i < l; i ++ ) { | |
this.children[ i ].traverseVisible( callback ); | |
} | |
}, | |
updateMatrix: function () { | |
this.matrix.compose( this.position, this.quaternion, this.scale ); | |
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.multiplyMatrices( 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 ); | |
} | |
}, | |
toJSON: function () { | |
var output = { | |
metadata: { | |
version: 4.3, | |
type: 'Object', | |
generator: 'ObjectExporter' | |
} | |
}; | |
// | |
var geometries = {}; | |
var parseGeometry = function ( geometry ) { | |
if ( output.geometries === undefined ) { | |
output.geometries = []; | |
} | |
if ( geometries[ geometry.uuid ] === undefined ) { | |
var json = geometry.toJSON(); | |
delete json.metadata; | |
geometries[ geometry.uuid ] = json; | |
output.geometries.push( json ); | |
} | |
return geometry.uuid; | |
}; | |
// | |
var materials = {}; | |
var parseMaterial = function ( material ) { | |
if ( output.materials === undefined ) { | |
output.materials = []; | |
} | |
if ( materials[ material.uuid ] === undefined ) { | |
var json = material.toJSON(); | |
delete json.metadata; | |
materials[ material.uuid ] = json; | |
output.materials.push( json ); | |
} | |
return material.uuid; | |
}; | |
// | |
var parseObject = function ( object ) { | |
var data = {}; | |
data.uuid = object.uuid; | |
data.type = object.type; | |
if ( object.name !== '' ) data.name = object.name; | |
if ( JSON.stringify( object.userData ) !== '{}' ) data.userData = object.userData; | |
if ( object.visible !== true ) data.visible = object.visible; | |
if ( object instanceof THREE.PerspectiveCamera ) { | |
data.fov = object.fov; | |
data.aspect = object.aspect; | |
data.near = object.near; | |
data.far = object.far; | |
} else if ( object instanceof THREE.OrthographicCamera ) { | |
data.left = object.left; | |
data.right = object.right; | |
data.top = object.top; | |
data.bottom = object.bottom; | |
data.near = object.near; | |
data.far = object.far; | |
} else if ( object instanceof THREE.AmbientLight ) { | |
data.color = object.color.getHex(); | |
} else if ( object instanceof THREE.DirectionalLight ) { | |
data.color = object.color.getHex(); | |
data.intensity = object.intensity; | |
} else if ( object instanceof THREE.PointLight ) { | |
data.color = object.color.getHex(); | |
data.intensity = object.intensity; | |
data.distance = object.distance; | |
} else if ( object instanceof THREE.SpotLight ) { | |
data.color = object.color.getHex(); | |
data.intensity = object.intensity; | |
data.distance = object.distance; | |
data.angle = object.angle; | |
data.exponent = object.exponent; | |
} else if ( object instanceof THREE.HemisphereLight ) { | |
data.color = object.color.getHex(); | |
data.groundColor = object.groundColor.getHex(); | |
} else if ( object instanceof THREE.Mesh ) { | |
data.geometry = parseGeometry( object.geometry ); | |
data.material = parseMaterial( object.material ); | |
} else if ( object instanceof THREE.Line ) { | |
data.geometry = parseGeometry( object.geometry ); | |
data.material = parseMaterial( object.material ); | |
} else if ( object instanceof THREE.Sprite ) { | |
data.material = parseMaterial( object.material ); | |
} | |
data.matrix = object.matrix.toArray(); | |
if ( object.children.length > 0 ) { | |
data.children = []; | |
for ( var i = 0; i < object.children.length; i ++ ) { | |
data.children.push( parseObject( object.children[ i ] ) ); | |
} | |
} | |
return data; | |
} | |
output.object = parseObject( this ); | |
return output; | |
}, | |
clone: function ( object, recursive ) { | |
if ( object === undefined ) object = new THREE.Object3D(); | |
if ( recursive === undefined ) recursive = true; | |
object.name = this.name; | |
object.up.copy( this.up ); | |
object.position.copy( this.position ); | |
object.quaternion.copy( this.quaternion ); | |
object.scale.copy( this.scale ); | |
object.renderDepth = this.renderDepth; | |
object.rotationAutoUpdate = this.rotationAutoUpdate; | |
object.matrix.copy( this.matrix ); | |
object.matrixWorld.copy( this.matrixWorld ); | |
object.matrixAutoUpdate = this.matrixAutoUpdate; | |
object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate; | |
object.visible = this.visible; | |
object.castShadow = this.castShadow; | |
object.receiveShadow = this.receiveShadow; | |
object.frustumCulled = this.frustumCulled; | |
object.userData = JSON.parse( JSON.stringify( this.userData ) ); | |
if ( recursive === true ) { | |
for ( var i = 0; i < this.children.length; i ++ ) { | |
var child = this.children[ i ]; | |
object.add( child.clone() ); | |
} | |
} | |
return object; | |
} | |
}; | |
THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype ); | |
THREE.Object3DIdCount = 0; | |
// File:src/core/Projector.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Projector = function () { | |
console.warn( 'THREE.Projector has been moved to /examples/renderers/Projector.js.' ); | |
this.projectVector = function ( vector, camera ) { | |
console.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); | |
vector.project( camera ); | |
}; | |
this.unprojectVector = function ( vector, camera ) { | |
console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); | |
vector.unproject( camera ); | |
}; | |
this.pickingRay = function ( vector, camera ) { | |
console.error( 'THREE.Projector: .pickingRay() has been removed.' ); | |
}; | |
}; | |
// File:src/core/Face3.js | |
/** | |
* @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 !== undefined ? materialIndex : 0; | |
}; | |
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.materialIndex = this.materialIndex; | |
for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) { | |
face.vertexNormals[ i ] = this.vertexNormals[ i ].clone(); | |
} | |
for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) { | |
face.vertexColors[ i ] = this.vertexColors[ i ].clone(); | |
} | |
for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) { | |
face.vertexTangents[ i ] = this.vertexTangents[ i ].clone(); | |
} | |
return face; | |
} | |
}; | |
// File:src/core/Face4.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) { | |
console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ) | |
return new THREE.Face3( a, b, c, normal, color, materialIndex ); | |
}; | |
// File:src/core/BufferAttribute.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.BufferAttribute = function ( array, itemSize ) { | |
this.array = array; | |
this.itemSize = itemSize; | |
this.needsUpdate = false; | |
}; | |
THREE.BufferAttribute.prototype = { | |
constructor: THREE.BufferAttribute, | |
get length () { | |
return this.array.length; | |
}, | |
copyAt: function ( index1, attribute, index2 ) { | |
index1 *= this.itemSize; | |
index2 *= attribute.itemSize; | |
for ( var i = 0, l = this.itemSize; i < l; i ++ ) { | |
this.array[ index1 + i ] = attribute.array[ index2 + i ]; | |
} | |
}, | |
set: function ( value ) { | |
this.array.set( value ); | |
return this; | |
}, | |
setX: function ( index, x ) { | |
this.array[ index * this.itemSize ] = x; | |
return this; | |
}, | |
setY: function ( index, y ) { | |
this.array[ index * this.itemSize + 1 ] = y; | |
return this; | |
}, | |
setZ: function ( index, z ) { | |
this.array[ index * this.itemSize + 2 ] = z; | |
return this; | |
}, | |
setXY: function ( index, x, y ) { | |
index *= this.itemSize; | |
this.array[ index ] = x; | |
this.array[ index + 1 ] = y; | |
return this; | |
}, | |
setXYZ: function ( index, x, y, z ) { | |
index *= this.itemSize; | |
this.array[ index ] = x; | |
this.array[ index + 1 ] = y; | |
this.array[ index + 2 ] = z; | |
return this; | |
}, | |
setXYZW: function ( index, x, y, z, w ) { | |
index *= this.itemSize; | |
this.array[ index ] = x; | |
this.array[ index + 1 ] = y; | |
this.array[ index + 2 ] = z; | |
this.array[ index + 3 ] = w; | |
return this; | |
}, | |
clone: function () { | |
return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize ); | |
} | |
}; | |
// | |
THREE.Int8Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Uint8Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Uint8ClampedAttribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Int16Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Uint16Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Int32Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Uint32Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Float32Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
THREE.Float64Attribute = function ( data, itemSize ) { | |
console.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); | |
return new THREE.BufferAttribute( data, itemSize ); | |
}; | |
// File:src/core/BufferGeometry.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.BufferGeometry = function () { | |
Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); | |
this.uuid = THREE.Math.generateUUID(); | |
this.name = ''; | |
this.type = 'BufferGeometry'; | |
this.attributes = {}; | |
this.attributesKeys = []; | |
this.drawcalls = []; | |
this.offsets = this.drawcalls; // backwards compatibility | |
this.boundingBox = null; | |
this.boundingSphere = null; | |
}; | |
THREE.BufferGeometry.prototype = { | |
constructor: THREE.BufferGeometry, | |
addAttribute: function ( name, attribute ) { | |
if ( attribute instanceof THREE.BufferAttribute === false ) { | |
console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); | |
this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] }; | |
return; | |
} | |
this.attributes[ name ] = attribute; | |
this.attributesKeys = Object.keys( this.attributes ); | |
}, | |
getAttribute: function ( name ) { | |
return this.attributes[ name ]; | |
}, | |
addDrawCall: function ( start, count, indexOffset ) { | |
this.drawcalls.push( { | |
start: start, | |
count: count, | |
index: indexOffset !== undefined ? indexOffset : 0 | |
} ); | |
}, | |
applyMatrix: function ( matrix ) { | |
var position = this.attributes.position; | |
if ( position !== undefined ) { | |
matrix.applyToVector3Array( position.array ); | |
position.needsUpdate = true; | |
} | |
var normal = this.attributes.normal; | |
if ( normal !== undefined ) { | |
var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); | |
normalMatrix.applyToVector3Array( normal.array ); | |
normal.needsUpdate = true; | |
} | |
}, | |
center: function () { | |
// TODO | |
}, | |
fromGeometry: function ( geometry, settings ) { | |
settings = settings || { 'vertexColors': THREE.NoColors }; | |
var vertices = geometry.vertices; | |
var faces = geometry.faces; | |
var faceVertexUvs = geometry.faceVertexUvs; | |
var vertexColors = settings.vertexColors; | |
var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0; | |
var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3; | |
var positions = new Float32Array( faces.length * 3 * 3 ); | |
this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); | |
var normals = new Float32Array( faces.length * 3 * 3 ); | |
this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); | |
if ( vertexColors !== THREE.NoColors ) { | |
var colors = new Float32Array( faces.length * 3 * 3 ); | |
this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); | |
} | |
if ( hasFaceVertexUv === true ) { | |
var uvs = new Float32Array( faces.length * 3 * 2 ); | |
this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); | |
} | |
for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) { | |
var face = faces[ i ]; | |
var a = vertices[ face.a ]; | |
var b = vertices[ face.b ]; | |
var c = vertices[ face.c ]; | |
positions[ i3 ] = a.x; | |
positions[ i3 + 1 ] = a.y; | |
positions[ i3 + 2 ] = a.z; | |
positions[ i3 + 3 ] = b.x; | |
positions[ i3 + 4 ] = b.y; | |
positions[ i3 + 5 ] = b.z; | |
positions[ i3 + 6 ] = c.x; | |
positions[ i3 + 7 ] = c.y; | |
positions[ i3 + 8 ] = c.z; | |
if ( hasFaceVertexNormals === true ) { | |
var na = face.vertexNormals[ 0 ]; | |
var nb = face.vertexNormals[ 1 ]; | |
var nc = face.vertexNormals[ 2 ]; | |
normals[ i3 ] = na.x; | |
normals[ i3 + 1 ] = na.y; | |
normals[ i3 + 2 ] = na.z; | |
normals[ i3 + 3 ] = nb.x; | |
normals[ i3 + 4 ] = nb.y; | |
normals[ i3 + 5 ] = nb.z; | |
normals[ i3 + 6 ] = nc.x; | |
normals[ i3 + 7 ] = nc.y; | |
normals[ i3 + 8 ] = nc.z; | |
} else { | |
var n = face.normal; | |
normals[ i3 ] = n.x; | |
normals[ i3 + 1 ] = n.y; | |
normals[ i3 + 2 ] = n.z; | |
normals[ i3 + 3 ] = n.x; | |
normals[ i3 + 4 ] = n.y; | |
normals[ i3 + 5 ] = n.z; | |
normals[ i3 + 6 ] = n.x; | |
normals[ i3 + 7 ] = n.y; | |
normals[ i3 + 8 ] = n.z; | |
} | |
if ( vertexColors === THREE.FaceColors ) { | |
var fc = face.color; | |
colors[ i3 ] = fc.r; | |
colors[ i3 + 1 ] = fc.g; | |
colors[ i3 + 2 ] = fc.b; | |
colors[ i3 + 3 ] = fc.r; | |
colors[ i3 + 4 ] = fc.g; | |
colors[ i3 + 5 ] = fc.b; | |
colors[ i3 + 6 ] = fc.r; | |
colors[ i3 + 7 ] = fc.g; | |
colors[ i3 + 8 ] = fc.b; | |
} else if ( vertexColors === THREE.VertexColors ) { | |
var vca = face.vertexColors[ 0 ]; | |
var vcb = face.vertexColors[ 1 ]; | |
var vcc = face.vertexColors[ 2 ]; | |
colors[ i3 ] = vca.r; | |
colors[ i3 + 1 ] = vca.g; | |
colors[ i3 + 2 ] = vca.b; | |
colors[ i3 + 3 ] = vcb.r; | |
colors[ i3 + 4 ] = vcb.g; | |
colors[ i3 + 5 ] = vcb.b; | |
colors[ i3 + 6 ] = vcc.r; | |
colors[ i3 + 7 ] = vcc.g; | |
colors[ i3 + 8 ] = vcc.b; | |
} | |
if ( hasFaceVertexUv === true ) { | |
var uva = faceVertexUvs[ 0 ][ i ][ 0 ]; | |
var uvb = faceVertexUvs[ 0 ][ i ][ 1 ]; | |
var uvc = faceVertexUvs[ 0 ][ i ][ 2 ]; | |
uvs[ i2 ] = uva.x; | |
uvs[ i2 + 1 ] = uva.y; | |
uvs[ i2 + 2 ] = uvb.x; | |
uvs[ i2 + 3 ] = uvb.y; | |
uvs[ i2 + 4 ] = uvc.x; | |
uvs[ i2 + 5 ] = uvc.y; | |
} | |
} | |
this.computeBoundingSphere() | |
return this; | |
}, | |
computeBoundingBox: function () { | |
var vector = new THREE.Vector3(); | |
return function () { | |
if ( this.boundingBox === null ) { | |
this.boundingBox = new THREE.Box3(); | |
} | |
var positions = this.attributes.position.array; | |
if ( positions ) { | |
var bb = this.boundingBox; | |
bb.makeEmpty(); | |
for ( var i = 0, il = positions.length; i < il; i += 3 ) { | |
vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); | |
bb.expandByPoint( vector ); | |
} | |
} | |
if ( positions === undefined || positions.length === 0 ) { | |
this.boundingBox.min.set( 0, 0, 0 ); | |
this.boundingBox.max.set( 0, 0, 0 ); | |
} | |
if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { | |
console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' ); | |
} | |
} | |
}(), | |
computeBoundingSphere: function () { | |
var box = new THREE.Box3(); | |
var vector = new THREE.Vector3(); | |
return function () { | |
if ( this.boundingSphere === null ) { | |
this.boundingSphere = new THREE.Sphere(); | |
} | |
var positions = this.attributes.position.array; | |
if ( positions ) { | |
box.makeEmpty(); | |
var center = this.boundingSphere.center; | |
for ( var i = 0, il = positions.length; i < il; i += 3 ) { | |
vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); | |
box.expandByPoint( vector ); | |
} | |
box.center( center ); | |
// hoping to find a boundingSphere with a radius smaller than the | |
// boundingSphere of the boundingBox: sqrt(3) smaller in the best case | |
var maxRadiusSq = 0; | |
for ( var i = 0, il = positions.length; i < il; i += 3 ) { | |
vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); | |
maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); | |
} | |
this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); | |
if ( isNaN( this.boundingSphere.radius ) ) { | |
console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' ); | |
} | |
} | |
} | |
}(), | |
computeFaceNormals: function () { | |
// backwards compatibility | |
}, | |
computeVertexNormals: function () { | |
var attributes = this.attributes; | |
if ( attributes.position ) { | |
var positions = attributes.position.array; | |
if ( attributes.normal === undefined ) { | |
this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); | |
} else { | |
// reset existing normals to zero | |
var normals = attributes.normal.array; | |
for ( var i = 0, il = normals.length; i < il; i ++ ) { | |
normals[ i ] = 0; | |
} | |
} | |
var normals = attributes.normal.array; | |
var vA, vB, vC, | |
pA = new THREE.Vector3(), | |
pB = new THREE.Vector3(), | |
pC = new THREE.Vector3(), | |
cb = new THREE.Vector3(), | |
ab = new THREE.Vector3(); | |
// indexed elements | |
if ( attributes.index ) { | |
var indices = attributes.index.array; | |
var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] ); | |
for ( var j = 0, jl = offsets.length; j < jl; ++ j ) { | |
var start = offsets[ j ].start; | |
var count = offsets[ j ].count; | |
var index = offsets[ j ].index; | |
for ( var i = start, il = start + count; i < il; i += 3 ) { | |
vA = ( index + indices[ i ] ) * 3; | |
vB = ( index + indices[ i + 1 ] ) * 3; | |
vC = ( index + indices[ i + 2 ] ) * 3; | |
pA.fromArray( positions, vA ); | |
pB.fromArray( positions, vB ); | |
pC.fromArray( positions, vC ); | |
cb.subVectors( pC, pB ); | |
ab.subVectors( pA, pB ); | |
cb.cross( ab ); | |
normals[ vA ] += cb.x; | |
normals[ vA + 1 ] += cb.y; | |
normals[ vA + 2 ] += cb.z; | |
normals[ vB ] += cb.x; | |
normals[ vB + 1 ] += cb.y; | |
normals[ vB + 2 ] += cb.z; | |
normals[ vC ] += cb.x; | |
normals[ vC + 1 ] += cb.y; | |
normals[ vC + 2 ] += cb.z; | |
} | |
} | |
} else { | |
// non-indexed elements (unconnected triangle soup) | |
for ( var i = 0, il = positions.length; i < il; i += 9 ) { | |
pA.fromArray( positions, i ); | |
pB.fromArray( positions, i + 3 ); | |
pC.fromArray( positions, i + 6 ); | |
cb.subVectors( pC, pB ); | |
ab.subVectors( pA, pB ); | |
cb.cross( ab ); | |
normals[ i ] = cb.x; | |
normals[ i + 1 ] = cb.y; | |
normals[ i + 2 ] = cb.z; | |
normals[ i + 3 ] = cb.x; | |
normals[ i + 4 ] = cb.y; | |
normals[ i + 5 ] = cb.z; | |
normals[ i + 6 ] = cb.x; | |
normals[ i + 7 ] = cb.y; | |
normals[ i + 8 ] = cb.z; | |
} | |
} | |
this.normalizeNormals(); | |
attributes.normal.needsUpdate = 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 ) { | |
this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); | |
} | |
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 vA = new THREE.Vector3(), | |
vB = new THREE.Vector3(), | |
vC = new THREE.Vector3(), | |
uvA = new THREE.Vector2(), | |
uvB = new THREE.Vector2(), | |
uvC = new THREE.Vector2(), | |
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 ) { | |
vA.fromArray( positions, a * 3 ); | |
vB.fromArray( positions, b * 3 ); | |
vC.fromArray( positions, c * 3 ); | |
uvA.fromArray( uvs, a * 2 ); | |
uvB.fromArray( uvs, b * 2 ); | |
uvC.fromArray( uvs, c * 2 ); | |
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.x - uvA.x; | |
s2 = uvC.x - uvA.x; | |
t1 = uvB.y - uvA.y; | |
t2 = uvC.y - uvA.y; | |
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 ].add( sdir ); | |
tan1[ b ].add( sdir ); | |
tan1[ c ].add( sdir ); | |
tan2[ a ].add( tdir ); | |
tan2[ b ].add( tdir ); | |
tan2[ c ].add( tdir ); | |
} | |
var i, il; | |
var j, jl; | |
var iA, iB, iC; | |
if ( this.drawcalls.length === 0 ) { | |
this.addDrawCall( 0, indices.length, 0 ); | |
} | |
var drawcalls = this.drawcalls; | |
for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) { | |
var start = drawcalls[ j ].start; | |
var count = drawcalls[ j ].count; | |
var index = drawcalls[ 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; | |
function handleVertex( v ) { | |
n.fromArray( normals, v * 3 ); | |
n2.copy( n ); | |
t = tan1[ v ]; | |
// Gram-Schmidt orthogonalize | |
tmp.copy( t ); | |
tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); | |
// Calculate handedness | |
tmp2.crossVectors( 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 = drawcalls.length; j < jl; ++ j ) { | |
var start = drawcalls[ j ].start; | |
var count = drawcalls[ j ].count; | |
var index = drawcalls[ 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 ); | |
} | |
} | |
}, | |
/* | |
computeOffsets | |
Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices. | |
This method will effectively rewrite the index buffer and remap all attributes to match the new indices. | |
WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets. | |
indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks. | |
*/ | |
computeOffsets: function ( indexBufferSize ) { | |
var size = indexBufferSize; | |
if ( indexBufferSize === undefined ) | |
size = 65535; //WebGL limits type of index buffer values to 16-bit. | |
var s = Date.now(); | |
var indices = this.attributes.index.array; | |
var vertices = this.attributes.position.array; | |
var verticesCount = ( vertices.length / 3 ); | |
var facesCount = ( indices.length / 3 ); | |
/* | |
console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length); | |
console.log("Faces to process: "+(indices.length/3)); | |
console.log("Reordering "+verticesCount+" vertices."); | |
*/ | |
var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers | |
var indexPtr = 0; | |
var vertexPtr = 0; | |
var offsets = [ { start:0, count:0, index:0 } ]; | |
var offset = offsets[ 0 ]; | |
var duplicatedVertices = 0; | |
var newVerticeMaps = 0; | |
var faceVertices = new Int32Array( 6 ); | |
var vertexMap = new Int32Array( vertices.length ); | |
var revVertexMap = new Int32Array( vertices.length ); | |
for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; } | |
/* | |
Traverse every face and reorder vertices in the proper offsets of 65k. | |
We can have more than 65k entries in the index buffer per offset, but only reference 65k values. | |
*/ | |
for ( var findex = 0; findex < facesCount; findex ++ ) { | |
newVerticeMaps = 0; | |
for ( var vo = 0; vo < 3; vo ++ ) { | |
var vid = indices[ findex * 3 + vo ]; | |
if ( vertexMap[ vid ] == - 1 ) { | |
//Unmapped vertice | |
faceVertices[ vo * 2 ] = vid; | |
faceVertices[ vo * 2 + 1 ] = - 1; | |
newVerticeMaps ++; | |
} else if ( vertexMap[ vid ] < offset.index ) { | |
//Reused vertices from previous block (duplicate) | |
faceVertices[ vo * 2 ] = vid; | |
faceVertices[ vo * 2 + 1 ] = - 1; | |
duplicatedVertices ++; | |
} else { | |
//Reused vertice in the current block | |
faceVertices[ vo * 2 ] = vid; | |
faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ]; | |
} | |
} | |
var faceMax = vertexPtr + newVerticeMaps; | |
if ( faceMax > ( offset.index + size ) ) { | |
var new_offset = { start:indexPtr, count:0, index:vertexPtr }; | |
offsets.push( new_offset ); | |
offset = new_offset; | |
//Re-evaluate reused vertices in light of new offset. | |
for ( var v = 0; v < 6; v += 2 ) { | |
var new_vid = faceVertices[ v + 1 ]; | |
if ( new_vid > - 1 && new_vid < offset.index ) | |
faceVertices[ v + 1 ] = - 1; | |
} | |
} | |
//Reindex the face. | |
for ( var v = 0; v < 6; v += 2 ) { | |
var vid = faceVertices[ v ]; | |
var new_vid = faceVertices[ v + 1 ]; | |
if ( new_vid === - 1 ) | |
new_vid = vertexPtr ++; | |
vertexMap[ vid ] = new_vid; | |
revVertexMap[ new_vid ] = vid; | |
sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit | |
offset.count ++; | |
} | |
} | |
/* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */ | |
this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr ); | |
this.offsets = offsets; | |
/* | |
var orderTime = Date.now(); | |
console.log("Reorder time: "+(orderTime-s)+"ms"); | |
console.log("Duplicated "+duplicatedVertices+" vertices."); | |
console.log("Compute Buffers time: "+(Date.now()-s)+"ms"); | |
console.log("Draw offsets: "+offsets.length); | |
*/ | |
return offsets; | |
}, | |
merge: function () { | |
console.log( 'BufferGeometry.merge(): TODO' ); | |
}, | |
normalizeNormals: function () { | |
var normals = this.attributes.normal.array; | |
var x, y, z, n; | |
for ( var i = 0, il = normals.length; i < il; i += 3 ) { | |
x = normals[ i ]; | |
y = normals[ i + 1 ]; | |
z = normals[ i + 2 ]; | |
n = 1.0 / Math.sqrt( x * x + y * y + z * z ); | |
normals[ i ] *= n; | |
normals[ i + 1 ] *= n; | |
normals[ i + 2 ] *= n; | |
} | |
}, | |
/* | |
reoderBuffers: | |
Reorder attributes based on a new indexBuffer and indexMap. | |
indexBuffer - Uint16Array of the new ordered indices. | |
indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex. | |
vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack). | |
*/ | |
reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) { | |
/* Create a copy of all attributes for reordering. */ | |
var sortedAttributes = {}; | |
for ( var attr in this.attributes ) { | |
if ( attr == 'index' ) | |
continue; | |
var sourceArray = this.attributes[ attr ].array; | |
sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount ); | |
} | |
/* Move attribute positions based on the new index map */ | |
for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) { | |
var vid = indexMap[ new_vid ]; | |
for ( var attr in this.attributes ) { | |
if ( attr == 'index' ) | |
continue; | |
var attrArray = this.attributes[ attr ].array; | |
var attrSize = this.attributes[ attr ].itemSize; | |
var sortedAttr = sortedAttributes[ attr ]; | |
for ( var k = 0; k < attrSize; k ++ ) | |
sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ]; | |
} | |
} | |
/* Carry the new sorted buffers locally */ | |
this.attributes[ 'index' ].array = indexBuffer; | |
for ( var attr in this.attributes ) { | |
if ( attr == 'index' ) | |
continue; | |
this.attributes[ attr ].array = sortedAttributes[ attr ]; | |
this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount; | |
} | |
}, | |
toJSON: function () { | |
var output = { | |
metadata: { | |
version: 4.0, | |
type: 'BufferGeometry', | |
generator: 'BufferGeometryExporter' | |
}, | |
uuid: this.uuid, | |
type: this.type, | |
data: { | |
attributes: {} | |
} | |
}; | |
var attributes = this.attributes; | |
var offsets = this.offsets; | |
var boundingSphere = this.boundingSphere; | |
for ( var key in attributes ) { | |
var attribute = attributes[ key ]; | |
var array = [], typeArray = attribute.array; | |
for ( var i = 0, l = typeArray.length; i < l; i ++ ) { | |
array[ i ] = typeArray[ i ]; | |
} | |
output.data.attributes[ key ] = { | |
itemSize: attribute.itemSize, | |
type: attribute.array.constructor.name, | |
array: array | |
} | |
} | |
if ( offsets.length > 0 ) { | |
output.data.offsets = JSON.parse( JSON.stringify( offsets ) ); | |
} | |
if ( boundingSphere !== null ) { | |
output.data.boundingSphere = { | |
center: boundingSphere.center.toArray(), | |
radius: boundingSphere.radius | |
} | |
} | |
return output; | |
}, | |
clone: function () { | |
var geometry = new THREE.BufferGeometry(); | |
for ( var attr in this.attributes ) { | |
var sourceAttr = this.attributes[ attr ]; | |
geometry.addAttribute( attr, sourceAttr.clone() ); | |
} | |
for ( var i = 0, il = this.offsets.length; i < il; i ++ ) { | |
var offset = this.offsets[ i ]; | |
geometry.offsets.push( { | |
start: offset.start, | |
index: offset.index, | |
count: offset.count | |
} ); | |
} | |
return geometry; | |
}, | |
dispose: function () { | |
this.dispatchEvent( { type: 'dispose' } ); | |
} | |
}; | |
THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype ); | |
// File:src/core/Geometry.js | |
/** | |
* @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 | |
* @author bhouston / http://exocortex.com | |
*/ | |
THREE.Geometry = function () { | |
Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); | |
this.uuid = THREE.Math.generateUUID(); | |
this.name = ''; | |
this.type = 'Geometry'; | |
this.vertices = []; | |
this.colors = []; // one-to-one vertex colors, used in Points and Line | |
this.faces = []; | |
this.faceVertexUvs = [ [] ]; | |
this.morphTargets = []; | |
this.morphColors = []; | |
this.morphNormals = []; | |
this.skinWeights = []; | |
this.skinIndices = []; | |
this.lineDistances = []; | |
this.boundingBox = null; | |
this.boundingSphere = null; | |
this.hasTangents = false; | |
this.dynamic = true; // the intermediate typed arrays 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; | |
this.lineDistancesNeedUpdate = false; | |
this.groupsNeedUpdate = false; | |
}; | |
THREE.Geometry.prototype = { | |
constructor: THREE.Geometry, | |
applyMatrix: function ( matrix ) { | |
var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); | |
for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { | |
var vertex = this.vertices[ i ]; | |
vertex.applyMatrix4( matrix ); | |
} | |
for ( var i = 0, il = this.faces.length; i < il; i ++ ) { | |
var face = this.faces[ i ]; | |
face.normal.applyMatrix3( normalMatrix ).normalize(); | |
for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { | |
face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); | |
} | |
} | |
if ( this.boundingBox instanceof THREE.Box3 ) { | |
this.computeBoundingBox(); | |
} | |
if ( this.boundingSphere instanceof THREE.Sphere ) { | |
this.computeBoundingSphere(); | |
} | |
}, | |
fromBufferGeometry: function ( geometry ) { | |
var scope = this; | |
var attributes = geometry.attributes; | |
var vertices = attributes.position.array; | |
var indices = attributes.index !== undefined ? attributes.index.array : undefined; | |
var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; | |
var colors = attributes.color !== undefined ? attributes.color.array : undefined; | |
var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; | |
var tempNormals = []; | |
var tempUVs = []; | |
for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) { | |
scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); | |
if ( normals !== undefined ) { | |
tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); | |
} | |
if ( colors !== undefined ) { | |
scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); | |
} | |
if ( uvs !== undefined ) { | |
tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); | |
} | |
} | |
var addFace = function ( a, b, c ) { | |
var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; | |
var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; | |
scope.faces.push( new THREE.Face3( a, b, c, vertexNormals, vertexColors ) ); | |
scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ], tempUVs[ b ], tempUVs[ c ] ] ); | |
}; | |
if ( indices !== undefined ) { | |
for ( var i = 0; i < indices.length; i += 3 ) { | |
addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); | |
} | |
} else { | |
for ( var i = 0; i < vertices.length / 3; i += 3 ) { | |
addFace( i, i + 1, i + 2 ); | |
} | |
} | |
this.computeFaceNormals(); | |
if ( geometry.boundingBox !== null ) { | |
this.boundingBox = geometry.boundingBox.clone(); | |
} | |
if ( geometry.boundingSphere !== null ) { | |
this.boundingSphere = geometry.boundingSphere.clone(); | |
} | |
return this; | |
}, | |
center: function () { | |
this.computeBoundingBox(); | |
var offset = new THREE.Vector3(); | |
offset.addVectors( this.boundingBox.min, this.boundingBox.max ); | |
offset.multiplyScalar( - 0.5 ); | |
this.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) ); | |
this.computeBoundingBox(); | |
return offset; | |
}, | |
computeFaceNormals: function () { | |
var cb = new THREE.Vector3(), ab = new THREE.Vector3(); | |
for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { | |
var face = this.faces[ f ]; | |
var vA = this.vertices[ face.a ]; | |
var vB = this.vertices[ face.b ]; | |
var vC = this.vertices[ face.c ]; | |
cb.subVectors( vC, vB ); | |
ab.subVectors( vA, vB ); | |
cb.cross( ab ); | |
cb.normalize(); | |
face.normal.copy( cb ); | |
} | |
}, | |
computeVertexNormals: function ( areaWeighted ) { | |
var v, vl, f, fl, face, vertices; | |
vertices = new Array( this.vertices.length ); | |
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { | |
vertices[ v ] = new THREE.Vector3(); | |
} | |
if ( areaWeighted ) { | |
// vertex normals weighted by triangle areas | |
// http://www.iquilezles.org/www/articles/normals/normals.htm | |
var vA, vB, vC, vD; | |
var cb = new THREE.Vector3(), ab = new THREE.Vector3(), | |
db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = 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.subVectors( vC, vB ); | |
ab.subVectors( vA, vB ); | |
cb.cross( ab ); | |
vertices[ face.a ].add( cb ); | |
vertices[ face.b ].add( cb ); | |
vertices[ face.c ].add( cb ); | |
} | |
} else { | |
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { | |
face = this.faces[ f ]; | |
vertices[ face.a ].add( face.normal ); | |
vertices[ face.b ].add( face.normal ); | |
vertices[ face.c ].add( 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 ]; | |
face.vertexNormals[ 0 ] = vertices[ face.a ].clone(); | |
face.vertexNormals[ 1 ] = vertices[ face.b ].clone(); | |
face.vertexNormals[ 2 ] = vertices[ face.c ].clone(); | |
} | |
}, | |
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 ++ ) { | |
faceNormal = new THREE.Vector3(); | |
vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: 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 ); | |
vertexNormals.a.copy( face.vertexNormals[ 0 ] ); | |
vertexNormals.b.copy( face.vertexNormals[ 1 ] ); | |
vertexNormals.c.copy( face.vertexNormals[ 2 ] ); | |
} | |
} | |
// 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.x - uvA.x; | |
s2 = uvC.x - uvA.x; | |
t1 = uvB.y - uvA.y; | |
t2 = uvC.y - uvA.y; | |
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 ].add( sdir ); | |
tan1[ b ].add( sdir ); | |
tan1[ c ].add( sdir ); | |
tan2[ a ].add( tdir ); | |
tan2[ b ].add( tdir ); | |
tan2[ c ].add( 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 | |
handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 ); | |
} | |
var faceIndex = [ 'a', 'b', 'c', 'd' ]; | |
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { | |
face = this.faces[ f ]; | |
for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) { | |
n.copy( face.vertexNormals[ i ] ); | |
vertexIndex = face[ faceIndex[ i ] ]; | |
t = tan1[ vertexIndex ]; | |
// Gram-Schmidt orthogonalize | |
tmp.copy( t ); | |
tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); | |
// Calculate handedness | |
tmp2.crossVectors( 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; | |
}, | |
computeLineDistances: function () { | |
var d = 0; | |
var vertices = this.vertices; | |
for ( var i = 0, il = vertices.length; i < il; i ++ ) { | |
if ( i > 0 ) { | |
d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); | |
} | |
this.lineDistances[ i ] = d; | |
} | |
}, | |
computeBoundingBox: function () { | |
if ( this.boundingBox === null ) { | |
this.boundingBox = new THREE.Box3(); | |
} | |
this.boundingBox.setFromPoints( this.vertices ); | |
}, | |
computeBoundingSphere: function () { | |
if ( this.boundingSphere === null ) { | |
this.boundingSphere = new THREE.Sphere(); | |
} | |
this.boundingSphere.setFromPoints( this.vertices ); | |
}, | |
merge: function ( geometry, matrix, materialIndexOffset ) { | |
if ( geometry instanceof THREE.Geometry === false ) { | |
console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); | |
return; | |
} | |
var normalMatrix, | |
vertexOffset = this.vertices.length, | |
vertices1 = this.vertices, | |
vertices2 = geometry.vertices, | |
faces1 = this.faces, | |
faces2 = geometry.faces, | |
uvs1 = this.faceVertexUvs[ 0 ], | |
uvs2 = geometry.faceVertexUvs[ 0 ]; | |
if ( materialIndexOffset === undefined ) materialIndexOffset = 0; | |
if ( matrix !== undefined ) { | |
normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); | |
} | |
// vertices | |
for ( var i = 0, il = vertices2.length; i < il; i ++ ) { | |
var vertex = vertices2[ i ]; | |
var vertexCopy = vertex.clone(); | |
if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); | |
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; | |
faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); | |
faceCopy.normal.copy( face.normal ); | |
if ( normalMatrix !== undefined ) { | |
faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); | |
} | |
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { | |
normal = faceVertexNormals[ j ].clone(); | |
if ( normalMatrix !== undefined ) { | |
normal.applyMatrix3( normalMatrix ).normalize(); | |
} | |
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() ); | |
} | |
faceCopy.materialIndex = face.materialIndex + materialIndexOffset; | |
faces1.push( faceCopy ); | |
} | |
// uvs | |
for ( i = 0, il = uvs2.length; i < il; i ++ ) { | |
var uv = uvs2[ i ], uvCopy = []; | |
if ( uv === undefined ) { | |
continue; | |
} | |
for ( var j = 0, jl = uv.length; j < jl; j ++ ) { | |
uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) ); | |
} | |
uvs1.push( uvCopy ); | |
} | |
}, | |
/* | |
* 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 indices, 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 ); | |
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 ] ]; | |
} | |
}; | |
// if faces are completely degenerate after merging vertices, we | |
// have to remove them from the geometry. | |
var faceIndicesToRemove = []; | |
for ( i = 0, il = this.faces.length; i < il; i ++ ) { | |
face = this.faces[ i ]; | |
face.a = changes[ face.a ]; | |
face.b = changes[ face.b ]; | |
face.c = changes[ face.c ]; | |
indices = [ face.a, face.b, face.c ]; | |
var dupIndex = - 1; | |
// if any duplicate vertices are found in a Face3 | |
// we have to remove the face as nothing can be saved | |
for ( var n = 0; n < 3; n ++ ) { | |
if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) { | |
dupIndex = n; | |
faceIndicesToRemove.push( i ); | |
break; | |
} | |
} | |
} | |
for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { | |
var idx = faceIndicesToRemove[ i ]; | |
this.faces.splice( idx, 1 ); | |
for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { | |
this.faceVertexUvs[ j ].splice( idx, 1 ); | |
} | |
} | |
// Use unique set of vertices | |
var diff = this.vertices.length - unique.length; | |
this.vertices = unique; | |
return diff; | |
}, | |
toJSON: function () { | |
var output = { | |
metadata: { | |
version: 4.0, | |
type: 'BufferGeometry', | |
generator: 'BufferGeometryExporter' | |
}, | |
uuid: this.uuid, | |
type: this.type | |
}; | |
if ( this.name !== "" ) output.name = this.name; | |
if ( this.parameters !== undefined ) { | |
var parameters = this.parameters; | |
for ( var key in parameters ) { | |
if ( parameters[ key ] !== undefined ) output[ key ] = parameters[ key ]; | |
} | |
return output; | |
} | |
var vertices = []; | |
for ( var i = 0; i < this.vertices.length; i ++ ) { | |
var vertex = this.vertices[ i ]; | |
vertices.push( vertex.x, vertex.y, vertex.z ); | |
} | |
var faces = []; | |
var normals = []; | |
var normalsHash = {}; | |
var colors = []; | |
var colorsHash = {}; | |
var uvs = []; | |
var uvsHash = {}; | |
for ( var i = 0; i < this.faces.length; i ++ ) { | |
var face = this.faces[ i ]; | |
var hasMaterial = false; // face.materialIndex !== undefined; | |
var hasFaceUv = false; // deprecated | |
var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; | |
var hasFaceNormal = face.normal.length() > 0; | |
var hasFaceVertexNormal = face.vertexNormals.length > 0; | |
var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; | |
var hasFaceVertexColor = face.vertexColors.length > 0; | |
var faceType = 0; | |
faceType = setBit( faceType, 0, 0 ); | |
faceType = setBit( faceType, 1, hasMaterial ); | |
faceType = setBit( faceType, 2, hasFaceUv ); | |
faceType = setBit( faceType, 3, hasFaceVertexUv ); | |
faceType = setBit( faceType, 4, hasFaceNormal ); | |
faceType = setBit( faceType, 5, hasFaceVertexNormal ); | |
faceType = setBit( faceType, 6, hasFaceColor ); | |
faceType = setBit( faceType, 7, hasFaceVertexColor ); | |
faces.push( faceType ); | |
faces.push( face.a, face.b, face.c ); | |
/* | |
if ( hasMaterial ) { | |
faces.push( face.materialIndex ); | |
} | |
*/ | |
if ( hasFaceVertexUv ) { | |
var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; | |
faces.push( | |
getUvIndex( faceVertexUvs[ 0 ] ), | |
getUvIndex( faceVertexUvs[ 1 ] ), | |
getUvIndex( faceVertexUvs[ 2 ] ) | |
); | |
} | |
if ( hasFaceNormal ) { | |
faces.push( getNormalIndex( face.normal ) ); | |
} | |
if ( hasFaceVertexNormal ) { | |
var vertexNormals = face.vertexNormals; | |
faces.push( | |
getNormalIndex( vertexNormals[ 0 ] ), | |
getNormalIndex( vertexNormals[ 1 ] ), | |
getNormalIndex( vertexNormals[ 2 ] ) | |
); | |
} | |
if ( hasFaceColor ) { | |
faces.push( getColorIndex( face.color ) ); | |
} | |
if ( hasFaceVertexColor ) { | |
var vertexColors = face.vertexColors; | |
faces.push( | |
getColorIndex( vertexColors[ 0 ] ), | |
getColorIndex( vertexColors[ 1 ] ), | |
getColorIndex( vertexColors[ 2 ] ) | |
); | |
} | |
} | |
function setBit( value, position, enabled ) { | |
return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) ); | |
} | |
function getNormalIndex( normal ) { | |
var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); | |
if ( normalsHash[ hash ] !== undefined ) { | |
return normalsHash[ hash ]; | |
} | |
normalsHash[ hash ] = normals.length / 3; | |
normals.push( normal.x, normal.y, normal.z ); | |
return normalsHash[ hash ]; | |
} | |
function getColorIndex( color ) { | |
var hash = color.r.toString() + color.g.toString() + color.b.toString(); | |
if ( colorsHash[ hash ] !== undefined ) { | |
return colorsHash[ hash ]; | |
} | |
colorsHash[ hash ] = colors.length; | |
colors.push( color.getHex() ); | |
return colorsHash[ hash ]; | |
} | |
function getUvIndex( uv ) { | |
var hash = uv.x.toString() + uv.y.toString(); | |
if ( uvsHash[ hash ] !== undefined ) { | |
return uvsHash[ hash ]; | |
} | |
uvsHash[ hash ] = uvs.length / 2; | |
uvs.push( uv.x, uv.y ); | |
return uvsHash[ hash ]; | |
} | |
output.data = {}; | |
output.data.vertices = vertices; | |
output.data.normals = normals; | |
if ( colors.length > 0 ) output.data.colors = colors; | |
if ( uvs.length > 0 ) output.data.uvs = [ uvs ]; // temporal backward compatibility | |
output.data.faces = faces; | |
// | |
return output; | |
}, | |
clone: function () { | |
var geometry = new THREE.Geometry(); | |
var vertices = this.vertices; | |
for ( var i = 0, il = vertices.length; i < il; i ++ ) { | |
geometry.vertices.push( vertices[ i ].clone() ); | |
} | |
var faces = this.faces; | |
for ( var i = 0, il = faces.length; i < il; i ++ ) { | |
geometry.faces.push( faces[ i ].clone() ); | |
} | |
var uvs = this.faceVertexUvs[ 0 ]; | |
for ( var 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.Vector2( uv[ j ].x, uv[ j ].y ) ); | |
} | |
geometry.faceVertexUvs[ 0 ].push( uvCopy ); | |
} | |
return geometry; | |
}, | |
dispose: function () { | |
this.dispatchEvent( { type: 'dispose' } ); | |
} | |
}; | |
THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype ); | |
THREE.GeometryIdCount = 0; | |
// File:src/cameras/Camera.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author mikael emtinger / http://gomo.se/ | |
* @author WestLangley / http://github.com/WestLangley | |
*/ | |
THREE.Camera = function () { | |
THREE.Object3D.call( this ); | |
this.type = 'Camera'; | |
this.matrixWorldInverse = new THREE.Matrix4(); | |
this.projectionMatrix = new THREE.Matrix4(); | |
}; | |
THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); | |
THREE.Camera.prototype.getWorldDirection = function () { | |
var quaternion = new THREE.Quaternion(); | |
return function ( optionalTarget ) { | |
var result = optionalTarget || new THREE.Vector3(); | |
this.getWorldQuaternion( quaternion ); | |
return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); | |
} | |
}(); | |
THREE.Camera.prototype.lookAt = function () { | |
// This routine does not support cameras with rotated and/or translated parent(s) | |
var m1 = new THREE.Matrix4(); | |
return function ( vector ) { | |
m1.lookAt( this.position, vector, this.up ); | |
this.quaternion.setFromRotationMatrix( m1 ); | |
}; | |
}(); | |
THREE.Camera.prototype.clone = function ( camera ) { | |
if ( camera === undefined ) camera = new THREE.Camera(); | |
THREE.Object3D.prototype.clone.call( this, camera ); | |
camera.matrixWorldInverse.copy( this.matrixWorldInverse ); | |
camera.projectionMatrix.copy( this.projectionMatrix ); | |
return camera; | |
}; | |
// File:src/cameras/CubeCamera.js | |
/** | |
* 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 ); | |
this.type = 'CubeCamera'; | |
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 ); | |
// File:src/cameras/OrthographicCamera.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { | |
THREE.Camera.call( this ); | |
this.type = 'OrthographicCamera'; | |
this.zoom = 1; | |
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 () { | |
var dx = ( this.right - this.left ) / ( 2 * this.zoom ); | |
var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); | |
var cx = ( this.right + this.left ) / 2; | |
var cy = ( this.top + this.bottom ) / 2; | |
this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far ); | |
}; | |
THREE.OrthographicCamera.prototype.clone = function () { | |
var camera = new THREE.OrthographicCamera(); | |
THREE.Camera.prototype.clone.call( this, camera ); | |
camera.zoom = this.zoom; | |
camera.left = this.left; | |
camera.right = this.right; | |
camera.top = this.top; | |
camera.bottom = this.bottom; | |
camera.near = this.near; | |
camera.far = this.far; | |
camera.projectionMatrix.copy( this.projectionMatrix ); | |
return camera; | |
}; | |
// File:src/cameras/PerspectiveCamera.js | |
/** | |
* @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.type = 'PerspectiveCamera'; | |
this.zoom = 1; | |
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 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) ); | |
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 () { | |
var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) ); | |
if ( this.fullWidth ) { | |
var aspect = this.fullWidth / this.fullHeight; | |
var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * 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( fov, this.aspect, this.near, this.far ); | |
} | |
}; | |
THREE.PerspectiveCamera.prototype.clone = function () { | |
var camera = new THREE.PerspectiveCamera(); | |
THREE.Camera.prototype.clone.call( this, camera ); | |
camera.zoom = this.zoom; | |
camera.fov = this.fov; | |
camera.aspect = this.aspect; | |
camera.near = this.near; | |
camera.far = this.far; | |
camera.projectionMatrix.copy( this.projectionMatrix ); | |
return camera; | |
}; | |
// File:src/lights/Light.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.Light = function ( color ) { | |
THREE.Object3D.call( this ); | |
this.type = 'Light'; | |
this.color = new THREE.Color( color ); | |
}; | |
THREE.Light.prototype = Object.create( THREE.Object3D.prototype ); | |
THREE.Light.prototype.clone = function ( light ) { | |
if ( light === undefined ) light = new THREE.Light(); | |
THREE.Object3D.prototype.clone.call( this, light ); | |
light.color.copy( this.color ); | |
return light; | |
}; | |
// File:src/lights/AmbientLight.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.AmbientLight = function ( color ) { | |
THREE.Light.call( this, color ); | |
this.type = 'AmbientLight'; | |
}; | |
THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype ); | |
THREE.AmbientLight.prototype.clone = function () { | |
var light = new THREE.AmbientLight(); | |
THREE.Light.prototype.clone.call( this, light ); | |
return light; | |
}; | |
// File:src/lights/AreaLight.js | |
/** | |
* @author MPanknin / http://www.redplant.de/ | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.AreaLight = function ( color, intensity ) { | |
THREE.Light.call( this, color ); | |
this.type = 'AreaLight'; | |
this.normal = new THREE.Vector3( 0, - 1, 0 ); | |
this.right = new THREE.Vector3( 1, 0, 0 ); | |
this.intensity = ( intensity !== undefined ) ? intensity : 1; | |
this.width = 1.0; | |
this.height = 1.0; | |
this.constantAttenuation = 1.5; | |
this.linearAttenuation = 0.5; | |
this.quadraticAttenuation = 0.1; | |
}; | |
THREE.AreaLight.prototype = Object.create( THREE.Light.prototype ); | |
// File:src/lights/DirectionalLight.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.DirectionalLight = function ( color, intensity ) { | |
THREE.Light.call( this, color ); | |
this.type = 'DirectionalLight'; | |
this.position.set( 0, 1, 0 ); | |
this.target = new THREE.Object3D(); | |
this.intensity = ( intensity !== undefined ) ? intensity : 1; | |
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 ); | |
THREE.DirectionalLight.prototype.clone = function () { | |
var light = new THREE.DirectionalLight(); | |
THREE.Light.prototype.clone.call( this, light ); | |
light.target = this.target.clone(); | |
light.intensity = this.intensity; | |
light.castShadow = this.castShadow; | |
light.onlyShadow = this.onlyShadow; | |
// | |
light.shadowCameraNear = this.shadowCameraNear; | |
light.shadowCameraFar = this.shadowCameraFar; | |
light.shadowCameraLeft = this.shadowCameraLeft; | |
light.shadowCameraRight = this.shadowCameraRight; | |
light.shadowCameraTop = this.shadowCameraTop; | |
light.shadowCameraBottom = this.shadowCameraBottom; | |
light.shadowCameraVisible = this.shadowCameraVisible; | |
light.shadowBias = this.shadowBias; | |
light.shadowDarkness = this.shadowDarkness; | |
light.shadowMapWidth = this.shadowMapWidth; | |
light.shadowMapHeight = this.shadowMapHeight; | |
// | |
light.shadowCascade = this.shadowCascade; | |
light.shadowCascadeOffset.copy( this.shadowCascadeOffset ); | |
light.shadowCascadeCount = this.shadowCascadeCount; | |
light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 ); | |
light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 ); | |
light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 ); | |
light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 ); | |
light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 ); | |
return light; | |
}; | |
// File:src/lights/HemisphereLight.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { | |
THREE.Light.call( this, skyColor ); | |
this.type = 'HemisphereLight'; | |
this.position.set( 0, 100, 0 ); | |
this.groundColor = new THREE.Color( groundColor ); | |
this.intensity = ( intensity !== undefined ) ? intensity : 1; | |
}; | |
THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype ); | |
THREE.HemisphereLight.prototype.clone = function () { | |
var light = new THREE.HemisphereLight(); | |
THREE.Light.prototype.clone.call( this, light ); | |
light.groundColor.copy( this.groundColor ); | |
light.intensity = this.intensity; | |
return light; | |
}; | |
// File:src/lights/PointLight.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.PointLight = function ( color, intensity, distance ) { | |
THREE.Light.call( this, color ); | |
this.type = 'PointLight'; | |
this.intensity = ( intensity !== undefined ) ? intensity : 1; | |
this.distance = ( distance !== undefined ) ? distance : 0; | |
}; | |
THREE.PointLight.prototype = Object.create( THREE.Light.prototype ); | |
THREE.PointLight.prototype.clone = function () { | |
var light = new THREE.PointLight(); | |
THREE.Light.prototype.clone.call( this, light ); | |
light.intensity = this.intensity; | |
light.distance = this.distance; | |
return light; | |
}; | |
// File:src/lights/SpotLight.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) { | |
THREE.Light.call( this, color ); | |
this.type = 'SpotLight'; | |
this.position.set( 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 / 3; | |
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 ); | |
THREE.SpotLight.prototype.clone = function () { | |
var light = new THREE.SpotLight(); | |
THREE.Light.prototype.clone.call( this, light ); | |
light.target = this.target.clone(); | |
light.intensity = this.intensity; | |
light.distance = this.distance; | |
light.angle = this.angle; | |
light.exponent = this.exponent; | |
light.castShadow = this.castShadow; | |
light.onlyShadow = this.onlyShadow; | |
// | |
light.shadowCameraNear = this.shadowCameraNear; | |
light.shadowCameraFar = this.shadowCameraFar; | |
light.shadowCameraFov = this.shadowCameraFov; | |
light.shadowCameraVisible = this.shadowCameraVisible; | |
light.shadowBias = this.shadowBias; | |
light.shadowDarkness = this.shadowDarkness; | |
light.shadowMapWidth = this.shadowMapWidth; | |
light.shadowMapHeight = this.shadowMapHeight; | |
return light; | |
}; | |
// File:src/loaders/Cache.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Cache = function () { | |
this.files = {}; | |
}; | |
THREE.Cache.prototype = { | |
constructor: THREE.Cache, | |
add: function ( key, file ) { | |
// console.log( 'THREE.Cache', 'Adding key:', key ); | |
this.files[ key ] = file; | |
}, | |
get: function ( key ) { | |
// console.log( 'THREE.Cache', 'Checking key:', key ); | |
return this.files[ key ]; | |
}, | |
remove: function ( key ) { | |
delete this.files[ key ]; | |
}, | |
clear: function () { | |
this.files = {} | |
} | |
}; | |
// File:src/loaders/Loader.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.Loader = function ( showStatus ) { | |
this.showStatus = showStatus; | |
this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null; | |
this.imageLoader = new THREE.ImageLoader(); | |
this.onLoadStart = function () {}; | |
this.onLoadProgress = function () {}; | |
this.onLoadComplete = function () {}; | |
}; | |
THREE.Loader.prototype = { | |
constructor: THREE.Loader, | |
crossOrigin: undefined, | |
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 / 1024 ).toFixed( 2 ) + ' KB'; | |
} | |
this.statusDomElement.innerHTML = message; | |
}, | |
extractUrlBase: function ( url ) { | |
var parts = url.split( '/' ); | |
if ( parts.length === 1 ) return './'; | |
parts.pop(); | |
return parts.join( '/' ) + '/'; | |
}, | |
initMaterials: function ( materials, texturePath ) { | |
var array = []; | |
for ( var i = 0; i < materials.length; ++ i ) { | |
array[ i ] = this.createMaterial( materials[ i ], texturePath ); | |
} | |
return array; | |
}, | |
needsTangents: function ( materials ) { | |
for ( var i = 0, il = materials.length; i < il; i ++ ) { | |
var m = materials[ i ]; | |
if ( m instanceof THREE.ShaderMaterial ) return true; | |
} | |
return false; | |
}, | |
createMaterial: function ( m, texturePath ) { | |
var scope = this; | |
function nearest_pow2( n ) { | |
var l = Math.log( n ) / Math.LN2; | |
return Math.pow( 2, Math.round( l ) ); | |
} | |
function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) { | |
var fullPath = texturePath + sourceFile; | |
var texture; | |
var loader = THREE.Loader.Handlers.get( fullPath ); | |
if ( loader !== null ) { | |
texture = loader.load( fullPath ); | |
} else { | |
texture = new THREE.Texture(); | |
loader = scope.imageLoader; | |
loader.crossOrigin = scope.crossOrigin; | |
loader.load( fullPath, function ( image ) { | |
if ( THREE.Math.isPowerOfTwo( image.width ) === false || | |
THREE.Math.isPowerOfTwo( image.height ) === false ) { | |
var width = nearest_pow2( image.width ); | |
var height = nearest_pow2( image.height ); | |
var canvas = document.createElement( 'canvas' ); | |
canvas.width = width; | |
canvas.height = height; | |
var context = canvas.getContext( '2d' ); | |
context.drawImage( image, 0, 0, width, height ); | |
texture.image = canvas; | |
} else { | |
texture.image = image; | |
} | |
texture.needsUpdate = true; | |
} ); | |
} | |
texture.sourceFile = sourceFile; | |
if ( repeat ) { | |
texture.repeat.set( repeat[ 0 ], repeat[ 1 ] ); | |
if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; | |
if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; | |
} | |
if ( offset ) { | |
texture.offset.set( offset[ 0 ], offset[ 1 ] ); | |
} | |
if ( wrap ) { | |
var wrapMap = { | |
'repeat': THREE.RepeatWrapping, | |
'mirror': THREE.MirroredRepeatWrapping | |
} | |
if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ]; | |
if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ]; | |
} | |
if ( anisotropy ) { | |
texture.anisotropy = anisotropy; | |
} | |
where[ name ] = texture; | |
} | |
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 ); | |
} | |
if ( m.colorEmissive ) { | |
mpars.emissive = rgb2hex( m.colorEmissive ); | |
} | |
// 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.mapAlpha && texturePath ) { | |
create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); | |
} | |
// | |
if ( m.mapBumpScale ) { | |
mpars.bumpScale = m.mapBumpScale; | |
} | |
// special case for normal mapped material | |
if ( m.mapNormal ) { | |
var shader = THREE.ShaderLib[ 'normalmap' ]; | |
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[ 'diffuse' ].value.setHex( mpars.color ); | |
uniforms[ 'specular' ].value.setHex( mpars.specular ); | |
uniforms[ 'ambient' ].value.setHex( mpars.ambient ); | |
uniforms[ 'shininess' ].value = mpars.shininess; | |
if ( mpars.opacity !== undefined ) { | |
uniforms[ 'opacity' ].value = mpars.opacity; | |
} | |
var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true }; | |
var material = new THREE.ShaderMaterial( parameters ); | |
if ( mpars.transparent ) { | |
material.transparent = true; | |
} | |
} else { | |
var material = new THREE[ mtype ]( mpars ); | |
} | |
if ( m.DbgName !== undefined ) material.name = m.DbgName; | |
return material; | |
} | |
}; | |
THREE.Loader.Handlers = { | |
handlers: [], | |
add: function ( regex, loader ) { | |
this.handlers.push( regex, loader ); | |
}, | |
get: function ( file ) { | |
for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) { | |
var regex = this.handlers[ i ]; | |
var loader = this.handlers[ i + 1 ]; | |
if ( regex.test( file ) ) { | |
return loader; | |
} | |
} | |
return null; | |
} | |
}; | |
// File:src/loaders/XHRLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.XHRLoader = function ( manager ) { | |
this.cache = new THREE.Cache(); | |
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; | |
}; | |
THREE.XHRLoader.prototype = { | |
constructor: THREE.XHRLoader, | |
load: function ( url, onLoad, onProgress, onError ) { | |
var scope = this; | |
var cached = scope.cache.get( url ); | |
if ( cached !== undefined ) { | |
if ( onLoad ) onLoad( cached ); | |
return; | |
} | |
var request = new XMLHttpRequest(); | |
request.open( 'GET', url, true ); | |
request.addEventListener( 'load', function ( event ) { | |
scope.cache.add( url, this.response ); | |
if ( onLoad ) onLoad( this.response ); | |
scope.manager.itemEnd( url ); | |
}, false ); | |
if ( onProgress !== undefined ) { | |
request.addEventListener( 'progress', function ( event ) { | |
onProgress( event ); | |
}, false ); | |
} | |
if ( onError !== undefined ) { | |
request.addEventListener( 'error', function ( event ) { | |
onError( event ); | |
}, false ); | |
} | |
if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; | |
if ( this.responseType !== undefined ) request.responseType = this.responseType; | |
request.send( null ); | |
scope.manager.itemStart( url ); | |
}, | |
setResponseType: function ( value ) { | |
this.responseType = value; | |
}, | |
setCrossOrigin: function ( value ) { | |
this.crossOrigin = value; | |
} | |
}; | |
// File:src/loaders/ImageLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.ImageLoader = function ( manager ) { | |
this.cache = new THREE.Cache(); | |
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; | |
}; | |
THREE.ImageLoader.prototype = { | |
constructor: THREE.ImageLoader, | |
load: function ( url, onLoad, onProgress, onError ) { | |
var scope = this; | |
var cached = scope.cache.get( url ); | |
if ( cached !== undefined ) { | |
onLoad( cached ); | |
return; | |
} | |
var image = document.createElement( 'img' ); | |
if ( onLoad !== undefined ) { | |
image.addEventListener( 'load', function ( event ) { | |
scope.cache.add( url, this ); | |
onLoad( this ); | |
scope.manager.itemEnd( url ); | |
}, false ); | |
} | |
if ( onProgress !== undefined ) { | |
image.addEventListener( 'progress', function ( event ) { | |
onProgress( event ); | |
}, false ); | |
} | |
if ( onError !== undefined ) { | |
image.addEventListener( 'error', function ( event ) { | |
onError( event ); | |
}, false ); | |
} | |
if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; | |
image.src = url; | |
scope.manager.itemStart( url ); | |
return image; | |
}, | |
setCrossOrigin: function ( value ) { | |
this.crossOrigin = value; | |
} | |
} | |
// File:src/loaders/JSONLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.JSONLoader = function ( showStatus ) { | |
THREE.Loader.call( this, showStatus ); | |
this.withCredentials = false; | |
}; | |
THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype ); | |
THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) { | |
var scope = this; | |
// todo: unify load API to for easier SceneLoader use | |
texturePath = texturePath && ( typeof texturePath === 'string' ) ? 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 ); | |
if ( json.metadata !== undefined && json.metadata.type === 'scene' ) { | |
console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' ); | |
return; | |
} | |
var result = context.parse( json, texturePath ); | |
callback( result.geometry, result.materials ); | |
} else { | |
console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file 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 ) { | |
if ( callbackProgress !== undefined ) { | |
length = xhr.getResponseHeader( 'Content-Length' ); | |
} | |
} | |
}; | |
xhr.open( 'GET', url, true ); | |
xhr.withCredentials = this.withCredentials; | |
xhr.send( null ); | |
}; | |
THREE.JSONLoader.prototype.parse = function ( json, texturePath ) { | |
var scope = this, | |
geometry = new THREE.Geometry(), | |
scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; | |
parseModel( scale ); | |
parseSkin(); | |
parseMorphing( scale ); | |
geometry.computeFaceNormals(); | |
geometry.computeBoundingSphere(); | |
function parseModel( scale ) { | |
function isBitSet( value, position ) { | |
return value & ( 1 << position ); | |
} | |
var i, j, fi, | |
offset, zLength, | |
colorIndex, normalIndex, uvIndex, materialIndex, | |
type, | |
isQuad, | |
hasMaterial, | |
hasFaceVertexUv, | |
hasFaceNormal, hasFaceVertexNormal, | |
hasFaceColor, hasFaceVertexColor, | |
vertex, face, faceA, faceB, color, hex, normal, | |
uvLayer, uv, u, v, | |
faces = json.faces, | |
vertices = json.vertices, | |
normals = json.normals, | |
colors = json.colors, | |
nUvLayers = 0; | |
if ( json.uvs !== undefined ) { | |
// disregard empty arrays | |
for ( i = 0; i < json.uvs.length; i ++ ) { | |
if ( json.uvs[ i ].length ) nUvLayers ++; | |
} | |
for ( i = 0; i < nUvLayers; 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 ); | |
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, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); | |
if ( isQuad ) { | |
faceA = new THREE.Face3(); | |
faceA.a = faces[ offset ]; | |
faceA.b = faces[ offset + 1 ]; | |
faceA.c = faces[ offset + 3 ]; | |
faceB = new THREE.Face3(); | |
faceB.a = faces[ offset + 1 ]; | |
faceB.b = faces[ offset + 2 ]; | |
faceB.c = faces[ offset + 3 ]; | |
offset += 4; | |
if ( hasMaterial ) { | |
materialIndex = faces[ offset ++ ]; | |
faceA.materialIndex = materialIndex; | |
faceB.materialIndex = materialIndex; | |
} | |
// to get face <=> uv index correspondence | |
fi = geometry.faces.length; | |
if ( hasFaceVertexUv ) { | |
for ( i = 0; i < nUvLayers; i ++ ) { | |
uvLayer = json.uvs[ i ]; | |
geometry.faceVertexUvs[ i ][ fi ] = []; | |
geometry.faceVertexUvs[ i ][ fi + 1 ] = [] | |
for ( j = 0; j < 4; j ++ ) { | |
uvIndex = faces[ offset ++ ]; | |
u = uvLayer[ uvIndex * 2 ]; | |
v = uvLayer[ uvIndex * 2 + 1 ]; | |
uv = new THREE.Vector2( u, v ); | |
if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); | |
if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); | |
} | |
} | |
} | |
if ( hasFaceNormal ) { | |
normalIndex = faces[ offset ++ ] * 3; | |
faceA.normal.set( | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ] | |
); | |
faceB.normal.copy( faceA.normal ); | |
} | |
if ( hasFaceVertexNormal ) { | |
for ( i = 0; i < 4; i ++ ) { | |
normalIndex = faces[ offset ++ ] * 3; | |
normal = new THREE.Vector3( | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ] | |
); | |
if ( i !== 2 ) faceA.vertexNormals.push( normal ); | |
if ( i !== 0 ) faceB.vertexNormals.push( normal ); | |
} | |
} | |
if ( hasFaceColor ) { | |
colorIndex = faces[ offset ++ ]; | |
hex = colors[ colorIndex ]; | |
faceA.color.setHex( hex ); | |
faceB.color.setHex( hex ); | |
} | |
if ( hasFaceVertexColor ) { | |
for ( i = 0; i < 4; i ++ ) { | |
colorIndex = faces[ offset ++ ]; | |
hex = colors[ colorIndex ]; | |
if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); | |
if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); | |
} | |
} | |
geometry.faces.push( faceA ); | |
geometry.faces.push( faceB ); | |
} else { | |
face = new THREE.Face3(); | |
face.a = faces[ offset ++ ]; | |
face.b = faces[ offset ++ ]; | |
face.c = faces[ offset ++ ]; | |
if ( hasMaterial ) { | |
materialIndex = faces[ offset ++ ]; | |
face.materialIndex = materialIndex; | |
} | |
// to get face <=> uv index correspondence | |
fi = geometry.faces.length; | |
if ( hasFaceVertexUv ) { | |
for ( i = 0; i < nUvLayers; i ++ ) { | |
uvLayer = json.uvs[ i ]; | |
geometry.faceVertexUvs[ i ][ fi ] = []; | |
for ( j = 0; j < 3; j ++ ) { | |
uvIndex = faces[ offset ++ ]; | |
u = uvLayer[ uvIndex * 2 ]; | |
v = uvLayer[ uvIndex * 2 + 1 ]; | |
uv = new THREE.Vector2( u, v ); | |
geometry.faceVertexUvs[ i ][ fi ].push( uv ); | |
} | |
} | |
} | |
if ( hasFaceNormal ) { | |
normalIndex = faces[ offset ++ ] * 3; | |
face.normal.set( | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ] | |
); | |
} | |
if ( hasFaceVertexNormal ) { | |
for ( i = 0; i < 3; i ++ ) { | |
normalIndex = faces[ offset ++ ] * 3; | |
normal = new THREE.Vector3( | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ++ ], | |
normals[ normalIndex ] | |
); | |
face.vertexNormals.push( normal ); | |
} | |
} | |
if ( hasFaceColor ) { | |
colorIndex = faces[ offset ++ ]; | |
face.color.setHex( colors[ colorIndex ] ); | |
} | |
if ( hasFaceVertexColor ) { | |
for ( i = 0; i < 3; i ++ ) { | |
colorIndex = faces[ offset ++ ]; | |
face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); | |
} | |
} | |
geometry.faces.push( face ); | |
} | |
} | |
}; | |
function parseSkin() { | |
var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; | |
if ( json.skinWeights ) { | |
for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { | |
var x = json.skinWeights[ i ]; | |
var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; | |
var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; | |
var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; | |
geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); | |
} | |
} | |
if ( json.skinIndices ) { | |
for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { | |
var a = json.skinIndices[ i ]; | |
var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; | |
var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; | |
var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; | |
geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); | |
} | |
} | |
geometry.bones = json.bones; | |
if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { | |
console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + | |
geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); | |
} | |
// could change this to json.animations[0] or remove completely | |
geometry.animation = json.animation; | |
geometry.animations = json.animations; | |
}; | |
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 ); | |
} | |
} | |
} | |
}; | |
if ( json.materials === undefined || json.materials.length === 0 ) { | |
return { geometry: geometry }; | |
} else { | |
var materials = this.initMaterials( json.materials, texturePath ); | |
if ( this.needsTangents( materials ) ) { | |
geometry.computeTangents(); | |
} | |
return { geometry: geometry, materials: materials }; | |
} | |
}; | |
// File:src/loaders/LoadingManager.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.LoadingManager = function ( onLoad, onProgress, onError ) { | |
var scope = this; | |
var loaded = 0, total = 0; | |
this.onLoad = onLoad; | |
this.onProgress = onProgress; | |
this.onError = onError; | |
this.itemStart = function ( url ) { | |
total ++; | |
}; | |
this.itemEnd = function ( url ) { | |
loaded ++; | |
if ( scope.onProgress !== undefined ) { | |
scope.onProgress( url, loaded, total ); | |
} | |
if ( loaded === total && scope.onLoad !== undefined ) { | |
scope.onLoad(); | |
} | |
}; | |
}; | |
THREE.DefaultLoadingManager = new THREE.LoadingManager(); | |
// File:src/loaders/BufferGeometryLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.BufferGeometryLoader = function ( manager ) { | |
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; | |
}; | |
THREE.BufferGeometryLoader.prototype = { | |
constructor: THREE.BufferGeometryLoader, | |
load: function ( url, onLoad, onProgress, onError ) { | |
var scope = this; | |
var loader = new THREE.XHRLoader(); | |
loader.setCrossOrigin( this.crossOrigin ); | |
loader.load( url, function ( text ) { | |
onLoad( scope.parse( JSON.parse( text ) ) ); | |
}, onProgress, onError ); | |
}, | |
setCrossOrigin: function ( value ) { | |
this.crossOrigin = value; | |
}, | |
parse: function ( json ) { | |
var geometry = new THREE.BufferGeometry(); | |
var attributes = json.attributes; | |
for ( var key in attributes ) { | |
var attribute = attributes[ key ]; | |
var typedArray = new self[ attribute.type ]( attribute.array ); | |
geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) ); | |
} | |
var offsets = json.offsets; | |
if ( offsets !== undefined ) { | |
geometry.offsets = JSON.parse( JSON.stringify( offsets ) ); | |
} | |
var boundingSphere = json.boundingSphere; | |
if ( boundingSphere !== undefined ) { | |
var center = new THREE.Vector3(); | |
if ( boundingSphere.center !== undefined ) { | |
center.fromArray( boundingSphere.center ); | |
} | |
geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); | |
} | |
return geometry; | |
} | |
}; | |
// File:src/loaders/MaterialLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.MaterialLoader = function ( manager ) { | |
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; | |
}; | |
THREE.MaterialLoader.prototype = { | |
constructor: THREE.MaterialLoader, | |
load: function ( url, onLoad, onProgress, onError ) { | |
var scope = this; | |
var loader = new THREE.XHRLoader(); | |
loader.setCrossOrigin( this.crossOrigin ); | |
loader.load( url, function ( text ) { | |
onLoad( scope.parse( JSON.parse( text ) ) ); | |
}, onProgress, onError ); | |
}, | |
setCrossOrigin: function ( value ) { | |
this.crossOrigin = value; | |
}, | |
parse: function ( json ) { | |
var material = new THREE[ json.type ]; | |
if ( json.color !== undefined ) material.color.setHex( json.color ); | |
if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient ); | |
if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); | |
if ( json.specular !== undefined ) material.specular.setHex( json.specular ); | |
if ( json.shininess !== undefined ) material.shininess = json.shininess; | |
if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; | |
if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; | |
if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; | |
if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; | |
if ( json.shading !== undefined ) material.shading = json.shading; | |
if ( json.blending !== undefined ) material.blending = json.blending; | |
if ( json.side !== undefined ) material.side = json.side; | |
if ( json.opacity !== undefined ) material.opacity = json.opacity; | |
if ( json.transparent !== undefined ) material.transparent = json.transparent; | |
if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; | |
if ( json.materials !== undefined ) { | |
for ( var i = 0, l = json.materials.length; i < l; i ++ ) { | |
material.materials.push( this.parse( json.materials[ i ] ) ); | |
} | |
} | |
return material; | |
} | |
}; | |
// File:src/loaders/ObjectLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.ObjectLoader = function ( manager ) { | |
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; | |
}; | |
THREE.ObjectLoader.prototype = { | |
constructor: THREE.ObjectLoader, | |
load: function ( url, onLoad, onProgress, onError ) { | |
var scope = this; | |
var loader = new THREE.XHRLoader( scope.manager ); | |
loader.setCrossOrigin( this.crossOrigin ); | |
loader.load( url, function ( text ) { | |
onLoad( scope.parse( JSON.parse( text ) ) ); | |
}, onProgress, onError ); | |
}, | |
setCrossOrigin: function ( value ) { | |
this.crossOrigin = value; | |
}, | |
parse: function ( json ) { | |
var geometries = this.parseGeometries( json.geometries ); | |
var materials = this.parseMaterials( json.materials ); | |
var object = this.parseObject( json.object, geometries, materials ); | |
return object; | |
}, | |
parseGeometries: function ( json ) { | |
var geometries = {}; | |
if ( json !== undefined ) { | |
var geometryLoader = new THREE.JSONLoader(); | |
var bufferGeometryLoader = new THREE.BufferGeometryLoader(); | |
for ( var i = 0, l = json.length; i < l; i ++ ) { | |
var geometry; | |
var data = json[ i ]; | |
switch ( data.type ) { | |
case 'PlaneGeometry': | |
geometry = new THREE.PlaneGeometry( | |
data.width, | |
data.height, | |
data.widthSegments, | |
data.heightSegments | |
); | |
break; | |
case 'BoxGeometry': | |
case 'CubeGeometry': // backwards compatible | |
geometry = new THREE.BoxGeometry( | |
data.width, | |
data.height, | |
data.depth, | |
data.widthSegments, | |
data.heightSegments, | |
data.depthSegments | |
); | |
break; | |
case 'CircleGeometry': | |
geometry = new THREE.CircleGeometry( | |
data.radius, | |
data.segments | |
); | |
break; | |
case 'CylinderGeometry': | |
geometry = new THREE.CylinderGeometry( | |
data.radiusTop, | |
data.radiusBottom, | |
data.height, | |
data.radialSegments, | |
data.heightSegments, | |
data.openEnded | |
); | |
break; | |
case 'SphereGeometry': | |
geometry = new THREE.SphereGeometry( | |
data.radius, | |
data.widthSegments, | |
data.heightSegments, | |
data.phiStart, | |
data.phiLength, | |
data.thetaStart, | |
data.thetaLength | |
); | |
break; | |
case 'IcosahedronGeometry': | |
geometry = new THREE.IcosahedronGeometry( | |
data.radius, | |
data.detail | |
); | |
break; | |
case 'TorusGeometry': | |
geometry = new THREE.TorusGeometry( | |
data.radius, | |
data.tube, | |
data.radialSegments, | |
data.tubularSegments, | |
data.arc | |
); | |
break; | |
case 'TorusKnotGeometry': | |
geometry = new THREE.TorusKnotGeometry( | |
data.radius, | |
data.tube, | |
data.radialSegments, | |
data.tubularSegments, | |
data.p, | |
data.q, | |
data.heightScale | |
); | |
break; | |
case 'BufferGeometry': | |
geometry = bufferGeometryLoader.parse( data.data ); | |
break; | |
case 'Geometry': | |
geometry = geometryLoader.parse( data.data ).geometry; | |
break; | |
} | |
geometry.uuid = data.uuid; | |
if ( data.name !== undefined ) geometry.name = data.name; | |
geometries[ data.uuid ] = geometry; | |
} | |
} | |
return geometries; | |
}, | |
parseMaterials: function ( json ) { | |
var materials = {}; | |
if ( json !== undefined ) { | |
var loader = new THREE.MaterialLoader(); | |
for ( var i = 0, l = json.length; i < l; i ++ ) { | |
var data = json[ i ]; | |
var material = loader.parse( data ); | |
material.uuid = data.uuid; | |
if ( data.name !== undefined ) material.name = data.name; | |
materials[ data.uuid ] = material; | |
} | |
} | |
return materials; | |
}, | |
parseObject: function () { | |
var matrix = new THREE.Matrix4(); | |
return function ( data, geometries, materials ) { | |
var object; | |
switch ( data.type ) { | |
case 'Scene': | |
object = new THREE.Scene(); | |
break; | |
case 'PerspectiveCamera': | |
object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); | |
break; | |
case 'OrthographicCamera': | |
object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); | |
break; | |
case 'AmbientLight': | |
object = new THREE.AmbientLight( data.color ); | |
break; | |
case 'DirectionalLight': | |
object = new THREE.DirectionalLight( data.color, data.intensity ); | |
break; | |
case 'PointLight': | |
object = new THREE.PointLight( data.color, data.intensity, data.distance ); | |
break; | |
case 'SpotLight': | |
object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent ); | |
break; | |
case 'HemisphereLight': | |
object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); | |
break; | |
case 'Mesh': | |
var geometry = geometries[ data.geometry ]; | |
var material = materials[ data.material ]; | |
if ( geometry === undefined ) { | |
console.warn( 'THREE.ObjectLoader: Undefined geometry', data.geometry ); | |
} | |
if ( material === undefined ) { | |
console.warn( 'THREE.ObjectLoader: Undefined material', data.material ); | |
} | |
object = new THREE.Mesh( geometry, material ); | |
break; | |
case 'Line': | |
var geometry = geometries[ data.geometry ]; | |
var material = materials[ data.material ]; | |
if ( geometry === undefined ) { | |
console.warn( 'THREE.ObjectLoader: Undefined geometry', data.geometry ); | |
} | |
if ( material === undefined ) { | |
console.warn( 'THREE.ObjectLoader: Undefined material', data.material ); | |
} | |
object = new THREE.Line( geometry, material ); | |
break; | |
case 'Sprite': | |
var material = materials[ data.material ]; | |
if ( material === undefined ) { | |
console.warn( 'THREE.ObjectLoader: Undefined material', data.material ); | |
} | |
object = new THREE.Sprite( material ); | |
break; | |
case 'Group': | |
object = new THREE.Group(); | |
break; | |
default: | |
object = new THREE.Object3D(); | |
} | |
object.uuid = data.uuid; | |
if ( data.name !== undefined ) object.name = data.name; | |
if ( data.matrix !== undefined ) { | |
matrix.fromArray( data.matrix ); | |
matrix.decompose( object.position, object.quaternion, object.scale ); | |
} else { | |
if ( data.position !== undefined ) object.position.fromArray( data.position ); | |
if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); | |
if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); | |
} | |
if ( data.visible !== undefined ) object.visible = data.visible; | |
if ( data.userData !== undefined ) object.userData = data.userData; | |
if ( data.children !== undefined ) { | |
for ( var child in data.children ) { | |
object.add( this.parseObject( data.children[ child ], geometries, materials ) ); | |
} | |
} | |
return object; | |
} | |
}() | |
}; | |
// File:src/loaders/TextureLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.TextureLoader = function ( manager ) { | |
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; | |
}; | |
THREE.TextureLoader.prototype = { | |
constructor: THREE.TextureLoader, | |
load: function ( url, onLoad, onProgress, onError ) { | |
var scope = this; | |
var loader = new THREE.ImageLoader( scope.manager ); | |
loader.setCrossOrigin( this.crossOrigin ); | |
loader.load( url, function ( image ) { | |
var texture = new THREE.Texture( image ); | |
texture.needsUpdate = true; | |
if ( onLoad !== undefined ) { | |
onLoad( texture ); | |
} | |
}, onProgress, onError ); | |
}, | |
setCrossOrigin: function ( value ) { | |
this.crossOrigin = value; | |
} | |
}; | |
// File:src/loaders/CompressedTextureLoader.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* | |
* Abstract Base class to block based textures loader (dds, pvr, ...) | |
*/ | |
THREE.CompressedTextureLoader = function () { | |
// override in sub classes | |
this._parser = null; | |
}; | |
THREE.CompressedTextureLoader.prototype = { | |
constructor: THREE.CompressedTextureLoader, | |
load: function ( url, onLoad, onError ) { | |
var scope = this; | |
var images = []; | |
var texture = new THREE.CompressedTexture(); | |
texture.image = images; | |
var loader = new THREE.XHRLoader(); | |
loader.setResponseType( 'arraybuffer' ); | |
if ( url instanceof Array ) { | |
var loaded = 0; | |
var loadTexture = function ( i ) { | |
loader.load( url[ i ], function ( buffer ) { | |
var texDatas = scope._parser( buffer, true ); | |
images[ i ] = { | |
width: texDatas.width, | |
height: texDatas.height, | |
format: texDatas.format, | |
mipmaps: texDatas.mipmaps | |
}; | |
loaded += 1; | |
if ( loaded === 6 ) { | |
if (texDatas.mipmapCount == 1) | |
texture.minFilter = THREE.LinearFilter; | |
texture.format = texDatas.format; | |
texture.needsUpdate = true; | |
if ( onLoad ) onLoad( texture ); | |
} | |
} ); | |
}; | |
for ( var i = 0, il = url.length; i < il; ++ i ) { | |
loadTexture( i ); | |
} | |
} else { | |
// compressed cubemap texture stored in a single DDS file | |
loader.load( url, function ( buffer ) { | |
var texDatas = scope._parser( buffer, true ); | |
if ( texDatas.isCubemap ) { | |
var faces = texDatas.mipmaps.length / texDatas.mipmapCount; | |
for ( var f = 0; f < faces; f ++ ) { | |
images[ f ] = { mipmaps : [] }; | |
for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { | |
images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); | |
images[ f ].format = texDatas.format; | |
images[ f ].width = texDatas.width; | |
images[ f ].height = texDatas.height; | |
} | |
} | |
} else { | |
texture.image.width = texDatas.width; | |
texture.image.height = texDatas.height; | |
texture.mipmaps = texDatas.mipmaps; | |
} | |
if ( texDatas.mipmapCount === 1 ) { | |
texture.minFilter = THREE.LinearFilter; | |
} | |
texture.format = texDatas.format; | |
texture.needsUpdate = true; | |
if ( onLoad ) onLoad( texture ); | |
} ); | |
} | |
return texture; | |
} | |
}; | |
// File:src/materials/Material.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.Material = function () { | |
Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); | |
this.uuid = THREE.Math.generateUUID(); | |
this.name = ''; | |
this.type = 'Material'; | |
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 = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer | |
this.visible = true; | |
this.needsUpdate = true; | |
}; | |
THREE.Material.prototype = { | |
constructor: THREE.Material, | |
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 ) { | |
currentValue.set( newValue ); | |
} else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { | |
currentValue.copy( newValue ); | |
} else if ( key == 'overdraw' ) { | |
// ensure overdraw is backwards-compatable with legacy boolean type | |
this[ key ] = Number( newValue ); | |
} else { | |
this[ key ] = newValue; | |
} | |
} | |
} | |
}, | |
toJSON: function () { | |
var output = { | |
metadata: { | |
version: 4.2, | |
type: 'material', | |
generator: 'MaterialExporter' | |
}, | |
uuid: this.uuid, | |
type: this.type | |
}; | |
if ( this.name !== "" ) output.name = this.name; | |
if ( this instanceof THREE.MeshBasicMaterial ) { | |
output.color = this.color.getHex(); | |
if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; | |
if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; | |
if ( this.side !== THREE.FrontSide ) output.side = this.side; | |
} else if ( this instanceof THREE.MeshLambertMaterial ) { | |
output.color = this.color.getHex(); | |
output.ambient = this.ambient.getHex(); | |
output.emissive = this.emissive.getHex(); | |
if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; | |
if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; | |
if ( this.side !== THREE.FrontSide ) output.side = this.side; | |
} else if ( this instanceof THREE.MeshPhongMaterial ) { | |
output.color = this.color.getHex(); | |
output.ambient = this.ambient.getHex(); | |
output.emissive = this.emissive.getHex(); | |
output.specular = this.specular.getHex(); | |
output.shininess = this.shininess; | |
if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; | |
if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; | |
if ( this.side !== THREE.FrontSide ) output.side = this.side; | |
} else if ( this instanceof THREE.MeshNormalMaterial ) { | |
if ( this.shading !== THREE.FlatShading ) output.shading = this.shading; | |
if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; | |
if ( this.side !== THREE.FrontSide ) output.side = this.side; | |
} else if ( this instanceof THREE.MeshDepthMaterial ) { | |
if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; | |
if ( this.side !== THREE.FrontSide ) output.side = this.side; | |
} else if ( this instanceof THREE.ShaderMaterial ) { | |
output.uniforms = this.uniforms; | |
output.vertexShader = this.vertexShader; | |
output.fragmentShader = this.fragmentShader; | |
} else if ( this instanceof THREE.SpriteMaterial ) { | |
output.color = this.color.getHex(); | |
} | |
if ( this.opacity < 1 ) output.opacity = this.opacity; | |
if ( this.transparent !== false ) output.transparent = this.transparent; | |
if ( this.wireframe !== false ) output.wireframe = this.wireframe; | |
return output; | |
}, | |
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; | |
}, | |
dispose: function () { | |
this.dispatchEvent( { type: 'dispose' } ); | |
} | |
}; | |
THREE.EventDispatcher.prototype.apply( THREE.Material.prototype ); | |
THREE.MaterialIdCount = 0; | |
// File:src/materials/LineBasicMaterial.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
* | |
* parameters = { | |
* color: <hex>, | |
* opacity: <float>, | |
* | |
* blending: THREE.NormalBlending, | |
* depthTest: <bool>, | |
* depthWrite: <bool>, | |
* | |
* linewidth: <float>, | |
* linecap: "round", | |
* linejoin: "round", | |
* | |
* vertexColors: <bool> | |
* | |
* fog: <bool> | |
* } | |
*/ | |
THREE.LineBasicMaterial = function ( parameters ) { | |
THREE.Material.call( this ); | |
this.type = 'LineBasicMaterial'; | |
this.color = new THREE.Color( 0xffffff ); | |
this.linewidth = 1; | |
this.linecap = 'round'; | |
this.linejoin = 'round'; | |
this.vertexColors = THREE.NoColors; | |
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; | |
}; | |
// File:src/materials/LineDashedMaterial.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
* | |
* parameters = { | |
* color: <hex>, | |
* opacity: <float>, | |
* | |
* blending: THREE.NormalBlending, | |
* depthTest: <bool>, | |
* depthWrite: <bool>, | |
* | |
* linewidth: <float>, | |
* | |
* scale: <float>, | |
* dashSize: <float>, | |
* gapSize: <float>, | |
* | |
* vertexColors: <bool> | |
* | |
* fog: <bool> | |
* } | |
*/ | |
THREE.LineDashedMaterial = function ( parameters ) { | |
THREE.Material.call( this ); | |
this.type = 'LineDashedMaterial'; | |
this.color = new THREE.Color( 0xffffff ); | |
this.linewidth = 1; | |
this.scale = 1; | |
this.dashSize = 3; | |
this.gapSize = 1; | |
this.vertexColors = false; | |
this.fog = true; | |
this.setValues( parameters ); | |
}; | |
THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); | |
THREE.LineDashedMaterial.prototype.clone = function () { | |
var material = new THREE.LineDashedMaterial(); | |
THREE.Material.prototype.clone.call( this, material ); | |
material.color.copy( this.color ); | |
material.linewidth = this.linewidth; | |
material.scale = this.scale; | |
material.dashSize = this.dashSize; | |
material.gapSize = this.gapSize; | |
material.vertexColors = this.vertexColors; | |
material.fog = this.fog; | |
return material; | |
}; | |
// File:src/materials/MeshBasicMaterial.js | |
/** | |
* @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> ), | |
* | |
* alphaMap: 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>, | |
* depthWrite: <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.type = 'MeshBasicMaterial'; | |
this.color = new THREE.Color( 0xffffff ); // emissive | |
this.map = null; | |
this.lightMap = null; | |
this.specularMap = null; | |
this.alphaMap = 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.alphaMap = this.alphaMap; | |
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; | |
}; | |
// File:src/materials/MeshLambertMaterial.js | |
/** | |
* @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> ), | |
* | |
* alphaMap: 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>, | |
* depthWrite: <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.type = 'MeshLambertMaterial'; | |
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.alphaMap = 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.alphaMap = this.alphaMap; | |
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; | |
}; | |
// File:src/materials/MeshPhongMaterial.js | |
/** | |
* @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> ), | |
* | |
* alphaMap: 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>, | |
* depthWrite: <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.type = 'MeshPhongMaterial'; | |
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.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.alphaMap = 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.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.alphaMap = this.alphaMap; | |
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; | |
}; | |
// File:src/materials/MeshDepthMaterial.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
* | |
* parameters = { | |
* opacity: <float>, | |
* | |
* blending: THREE.NormalBlending, | |
* depthTest: <bool>, | |
* depthWrite: <bool>, | |
* | |
* wireframe: <boolean>, | |
* wireframeLinewidth: <float> | |
* } | |
*/ | |
THREE.MeshDepthMaterial = function ( parameters ) { | |
THREE.Material.call( this ); | |
this.type = 'MeshDepthMaterial'; | |
this.morphTargets = false; | |
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.MeshDepthMaterial(); | |
THREE.Material.prototype.clone.call( this, material ); | |
material.wireframe = this.wireframe; | |
material.wireframeLinewidth = this.wireframeLinewidth; | |
return material; | |
}; | |
// File:src/materials/MeshNormalMaterial.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* | |
* parameters = { | |
* opacity: <float>, | |
* | |
* shading: THREE.FlatShading, | |
* blending: THREE.NormalBlending, | |
* depthTest: <bool>, | |
* depthWrite: <bool>, | |
* | |
* wireframe: <boolean>, | |
* wireframeLinewidth: <float> | |
* } | |
*/ | |
THREE.MeshNormalMaterial = function ( parameters ) { | |
THREE.Material.call( this, parameters ); | |
this.type = 'MeshNormalMaterial'; | |
this.shading = THREE.FlatShading; | |
this.wireframe = false; | |
this.wireframeLinewidth = 1; | |
this.morphTargets = false; | |
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; | |
}; | |
// File:src/materials/MeshFaceMaterial.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.MeshFaceMaterial = function ( materials ) { | |
this.uuid = THREE.Math.generateUUID(); | |
this.type = 'MeshFaceMaterial'; | |
this.materials = materials instanceof Array ? materials : []; | |
}; | |
THREE.MeshFaceMaterial.prototype = { | |
constructor: THREE.MeshFaceMaterial, | |
toJSON: function () { | |
var output = { | |
metadata: { | |
version: 4.2, | |
type: 'material', | |
generator: 'MaterialExporter' | |
}, | |
uuid: this.uuid, | |
type: this.type, | |
materials: [] | |
}; | |
for ( var i = 0, l = this.materials.length; i < l; i ++ ) { | |
output.materials.push( this.materials[ i ].toJSON() ); | |
} | |
return output; | |
}, | |
clone: function () { | |
var material = new THREE.MeshFaceMaterial(); | |
for ( var i = 0; i < this.materials.length; i ++ ) { | |
material.materials.push( this.materials[ i ].clone() ); | |
} | |
return material; | |
} | |
}; | |
// File:src/materials/PointCloudMaterial.js | |
/** | |
* @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>, | |
* depthWrite: <bool>, | |
* | |
* vertexColors: <bool>, | |
* | |
* fog: <bool> | |
* } | |
*/ | |
THREE.PointCloudMaterial = function ( parameters ) { | |
THREE.Material.call( this ); | |
this.type = 'PointCloudMaterial'; | |
this.color = new THREE.Color( 0xffffff ); | |
this.map = null; | |
this.size = 1; | |
this.sizeAttenuation = true; | |
this.vertexColors = THREE.NoColors; | |
this.fog = true; | |
this.setValues( parameters ); | |
}; | |
THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype ); | |
THREE.PointCloudMaterial.prototype.clone = function () { | |
var material = new THREE.PointCloudMaterial(); | |
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; | |
}; | |
// backwards compatibility | |
THREE.ParticleBasicMaterial = function ( parameters ) { | |
console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' ); | |
return new THREE.PointCloudMaterial( parameters ); | |
}; | |
THREE.ParticleSystemMaterial = function ( parameters ) { | |
console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' ); | |
return new THREE.PointCloudMaterial( parameters ); | |
}; | |
// File:src/materials/ShaderMaterial.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
* | |
* parameters = { | |
* defines: { "label" : "value" }, | |
* uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } }, | |
* | |
* fragmentShader: <string>, | |
* vertexShader: <string>, | |
* | |
* shading: THREE.SmoothShading, | |
* blending: THREE.NormalBlending, | |
* depthTest: <bool>, | |
* depthWrite: <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.type = 'ShaderMaterial'; | |
this.defines = {}; | |
this.uniforms = {}; | |
this.attributes = null; | |
this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; | |
this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; | |
this.shading = THREE.SmoothShading; | |
this.linewidth = 1; | |
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 | |
// When rendered geometry doesn't include these attributes but the material does, | |
// use these default values in WebGL. This avoids errors when buffer data is missing. | |
this.defaultAttributeValues = { | |
'color': [ 1, 1, 1 ], | |
'uv': [ 0, 0 ], | |
'uv2': [ 0, 0 ] | |
}; | |
this.index0AttributeName = undefined; | |
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 = THREE.UniformsUtils.clone( 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; | |
}; | |
// File:src/materials/RawShaderMaterial.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.RawShaderMaterial = function ( parameters ) { | |
THREE.ShaderMaterial.call( this, parameters ); | |
this.type = 'RawShaderMaterial'; | |
}; | |
THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); | |
THREE.RawShaderMaterial.prototype.clone = function () { | |
var material = new THREE.RawShaderMaterial(); | |
THREE.ShaderMaterial.prototype.clone.call( this, material ); | |
return material; | |
}; | |
// File:src/materials/SpriteMaterial.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
* | |
* parameters = { | |
* color: <hex>, | |
* opacity: <float>, | |
* map: new THREE.Texture( <Image> ), | |
* | |
* blending: THREE.NormalBlending, | |
* depthTest: <bool>, | |
* depthWrite: <bool>, | |
* | |
* uvOffset: new THREE.Vector2(), | |
* uvScale: new THREE.Vector2(), | |
* | |
* fog: <bool> | |
* } | |
*/ | |
THREE.SpriteMaterial = function ( parameters ) { | |
THREE.Material.call( this ); | |
this.type = 'SpriteMaterial'; | |
this.color = new THREE.Color( 0xffffff ); | |
this.map = null; | |
this.rotation = 0; | |
this.fog = false; | |
// set parameters | |
this.setValues( parameters ); | |
}; | |
THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); | |
THREE.SpriteMaterial.prototype.clone = function () { | |
var material = new THREE.SpriteMaterial(); | |
THREE.Material.prototype.clone.call( this, material ); | |
material.color.copy( this.color ); | |
material.map = this.map; | |
material.rotation = this.rotation; | |
material.fog = this.fog; | |
return material; | |
}; | |
// File:src/textures/Texture.js | |
/** | |
* @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 ) { | |
Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); | |
this.uuid = THREE.Math.generateUUID(); | |
this.name = ''; | |
this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; | |
this.mipmaps = []; | |
this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; | |
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.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) | |
this._needsUpdate = false; | |
this.onUpdate = null; | |
}; | |
THREE.Texture.DEFAULT_IMAGE = undefined; | |
THREE.Texture.DEFAULT_MAPPING = new THREE.UVMapping(); | |
THREE.Texture.prototype = { | |
constructor: THREE.Texture, | |
get needsUpdate () { | |
return this._needsUpdate; | |
}, | |
set needsUpdate ( value ) { | |
if ( value === true ) this.update(); | |
this._needsUpdate = value; | |
}, | |
clone: function ( texture ) { | |
if ( texture === undefined ) texture = new THREE.Texture(); | |
texture.image = this.image; | |
texture.mipmaps = this.mipmaps.slice( 0 ); | |
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; | |
texture.unpackAlignment = this.unpackAlignment; | |
return texture; | |
}, | |
update: function () { | |
this.dispatchEvent( { type: 'update' } ); | |
}, | |
dispose: function () { | |
this.dispatchEvent( { type: 'dispose' } ); | |
} | |
}; | |
THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype ); | |
THREE.TextureIdCount = 0; | |
// File:src/textures/CubeTexture.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { | |
THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); | |
this.images = images; | |
}; | |
THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); | |
THREE.CubeTexture.clone = function ( texture ) { | |
if ( texture === undefined ) texture = new THREE.CubeTexture(); | |
THREE.Texture.prototype.clone.call( this, texture ); | |
texture.images = this.images; | |
return texture; | |
}; | |
// File:src/textures/CompressedTexture.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { | |
THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); | |
this.image = { width: width, height: height }; | |
this.mipmaps = mipmaps; | |
// no flipping for cube textures | |
// (also flipping doesn't work for compressed textures ) | |
this.flipY = false; | |
// can't generate mipmaps for compressed textures | |
// mips must be embedded in DDS files | |
this.generateMipmaps = false; | |
}; | |
THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); | |
THREE.CompressedTexture.prototype.clone = function () { | |
var texture = new THREE.CompressedTexture(); | |
THREE.Texture.prototype.clone.call( this, texture ); | |
return texture; | |
}; | |
// File:src/textures/DataTexture.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { | |
THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); | |
this.image = { data: data, width: width, height: height }; | |
}; | |
THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); | |
THREE.DataTexture.prototype.clone = function () { | |
var texture = new THREE.DataTexture(); | |
THREE.Texture.prototype.clone.call( this, texture ); | |
return texture; | |
}; | |
// File:src/textures/VideoTexture.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { | |
THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); | |
this.generateMipmaps = false; | |
var scope = this; | |
var update = function () { | |
requestAnimationFrame( update ); | |
if ( video.readyState === video.HAVE_ENOUGH_DATA ) { | |
scope.needsUpdate = true; | |
} | |
}; | |
update(); | |
}; | |
THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); | |
// File:src/objects/Group.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Group = function () { | |
THREE.Object3D.call( this ); | |
this.type = 'Group'; | |
}; | |
THREE.Group.prototype = Object.create( THREE.Object3D.prototype ); | |
// File:src/objects/PointCloud.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.PointCloud = function ( geometry, material ) { | |
THREE.Object3D.call( this ); | |
this.type = 'PointCloud'; | |
this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); | |
this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } ); | |
this.sortParticles = false; | |
}; | |
THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype ); | |
THREE.PointCloud.prototype.raycast = ( function () { | |
var inverseMatrix = new THREE.Matrix4(); | |
var ray = new THREE.Ray(); | |
return function ( raycaster, intersects ) { | |
var object = this; | |
var geometry = object.geometry; | |
var threshold = raycaster.params.PointCloud.threshold; | |
inverseMatrix.getInverse( this.matrixWorld ); | |
ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); | |
if ( geometry.boundingBox !== null ) { | |
if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { | |
return; | |
} | |
} | |
var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); | |
var position = new THREE.Vector3(); | |
var testPoint = function ( point, index ) { | |
var rayPointDistance = ray.distanceToPoint( point ); | |
if ( rayPointDistance < localThreshold ) { | |
var intersectPoint = ray.closestPointToPoint( point ); | |
intersectPoint.applyMatrix4( object.matrixWorld ); | |
var distance = raycaster.ray.origin.distanceTo( intersectPoint ); | |
intersects.push( { | |
distance: distance, | |
distanceToRay: rayPointDistance, | |
point: intersectPoint.clone(), | |
index: index, | |
face: null, | |
object: object | |
} ); | |
} | |
}; | |
if ( geometry instanceof THREE.BufferGeometry ) { | |
var attributes = geometry.attributes; | |
var positions = attributes.position.array; | |
if ( attributes.index !== undefined ) { | |
var indices = attributes.index.array; | |
var offsets = geometry.offsets; | |
if ( offsets.length === 0 ) { | |
var offset = { | |
start: 0, | |
count: indices.length, | |
index: 0 | |
}; | |
offsets = [ offset ]; | |
} | |
for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) { | |
var start = offsets[ oi ].start; | |
var count = offsets[ oi ].count; | |
var index = offsets[ oi ].index; | |
for ( var i = start, il = start + count; i < il; i ++ ) { | |
var a = index + indices[ i ]; | |
position.fromArray( positions, a * 3 ); | |
testPoint( position, a ); | |
} | |
} | |
} else { | |
var pointCount = positions.length / 3; | |
for ( var i = 0; i < pointCount; i ++ ) { | |
position.set( | |
positions[ 3 * i ], | |
positions[ 3 * i + 1 ], | |
positions[ 3 * i + 2 ] | |
); | |
testPoint( position, i ); | |
} | |
} | |
} else { | |
var vertices = this.geometry.vertices; | |
for ( var i = 0; i < vertices.length; i ++ ) { | |
testPoint( vertices[ i ], i ); | |
} | |
} | |
}; | |
}() ); | |
THREE.PointCloud.prototype.clone = function ( object ) { | |
if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material ); | |
object.sortParticles = this.sortParticles; | |
THREE.Object3D.prototype.clone.call( this, object ); | |
return object; | |
}; | |
// Backwards compatibility | |
THREE.ParticleSystem = function ( geometry, material ) { | |
console.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' ); | |
return new THREE.PointCloud( geometry, material ); | |
}; | |
// File:src/objects/Line.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
*/ | |
THREE.Line = function ( geometry, material, mode ) { | |
THREE.Object3D.call( this ); | |
this.type = 'Line'; | |
this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); | |
this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); | |
this.mode = ( mode !== undefined ) ? mode : THREE.LineStrip; | |
}; | |
THREE.LineStrip = 0; | |
THREE.LinePieces = 1; | |
THREE.Line.prototype = Object.create( THREE.Object3D.prototype ); | |
THREE.Line.prototype.raycast = ( function () { | |
var inverseMatrix = new THREE.Matrix4(); | |
var ray = new THREE.Ray(); | |
var sphere = new THREE.Sphere(); | |
return function ( raycaster, intersects ) { | |
var precision = raycaster.linePrecision; | |
var precisionSq = precision * precision; | |
var geometry = this.geometry; | |
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); | |
// Checking boundingSphere distance to ray | |
sphere.copy( geometry.boundingSphere ); | |
sphere.applyMatrix4( this.matrixWorld ); | |
if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { | |
return; | |
} | |
inverseMatrix.getInverse( this.matrixWorld ); | |
ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); | |
/* if ( geometry instanceof THREE.BufferGeometry ) { | |
} else */ if ( geometry instanceof THREE.Geometry ) { | |
var vertices = geometry.vertices; | |
var nbVertices = vertices.length; | |
var interSegment = new THREE.Vector3(); | |
var interRay = new THREE.Vector3(); | |
var step = this.mode === THREE.LineStrip ? 1 : 2; | |
for ( var i = 0; i < nbVertices - 1; i = i + step ) { | |
var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); | |
if ( distSq > precisionSq ) continue; | |
var distance = ray.origin.distanceTo( interRay ); | |
if ( distance < raycaster.near || distance > raycaster.far ) continue; | |
intersects.push( { | |
distance: distance, | |
// What do we want? intersection point on the ray or on the segment?? | |
// point: raycaster.ray.at( distance ), | |
point: interSegment.clone().applyMatrix4( this.matrixWorld ), | |
face: null, | |
faceIndex: null, | |
object: this | |
} ); | |
} | |
} | |
}; | |
}() ); | |
THREE.Line.prototype.clone = function ( object ) { | |
if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.mode ); | |
THREE.Object3D.prototype.clone.call( this, object ); | |
return object; | |
}; | |
// File:src/objects/Mesh.js | |
/** | |
* @author mrdoob / http://mrdoob.com/ | |
* @author alteredq / http://alteredqualia.com/ | |
* @author mikael emtinger / http://gomo.se/ | |
* @author jonobr1 / http://jonobr1.com/ | |
*/ | |
THREE.Mesh = function ( geometry, material ) { | |
THREE.Object3D.call( this ); | |
this.type = 'Mesh'; | |
this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); | |
this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); | |
this.updateMorphTargets(); | |
}; | |
THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype ); | |
THREE.Mesh.prototype.updateMorphTargets = function () { | |
if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { | |
this.morphTargetBase = - 1; | |
this.morphTargetForcedOrder = []; | |
this.morphTargetInfluences = []; | |
this.morphTargetDictionary = {}; | |
for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { | |
this.morphTargetInfluences.push( 0 ); | |
this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; | |
} | |
} | |
}; | |
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.raycast = ( function () { | |
var inverseMatrix = new THREE.Matrix4(); | |
var ray = new THREE.Ray(); | |
var sphere = new THREE.Sphere(); | |
var vA = new THREE.Vector3(); | |
var vB = new THREE.Vector3(); | |
var vC = new THREE.Vector3(); | |
return function ( raycaster, intersects ) { | |
var geometry = this.geometry; | |
// Checking boundingSphere distance to ray | |
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); | |
sphere.copy( geometry.boundingSphere ); | |
sphere.applyMatrix4( this.matrixWorld ); | |
if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { | |
return; | |
} | |
// Check boundingBox before continuing | |
inverseMatrix.getInverse( this.matrixWorld ); | |
ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); | |
if ( geometry.boundingBox !== null ) { | |
if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { | |
return; | |
} | |
} | |
if ( geometry instanceof THREE.BufferGeometry ) { | |
var material = this.material; | |
if ( material === undefined ) return; | |
var attributes = geometry.attributes; | |
var a, b, c; | |
var precision = raycaster.precision; | |
if ( attributes.index !== undefined ) { | |
var indices = attributes.index.array; | |
var positions = attributes.position.array; | |
var offsets = geometry.offsets; | |
if ( offsets.length === 0 ) { | |
offsets = [ { start: 0, count: indices.length, index: 0 } ]; | |
} | |
for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) { | |
var start = offsets[ oi ].start; | |
var count = offsets[ oi ].count; | |
var index = offsets[ oi ].index; | |
for ( var i = start, il = start + count; i < il; i += 3 ) { | |
a = index + indices[ i ]; | |
b = index + indices[ i + 1 ]; | |
c = index + indices[ i + 2 ]; | |
vA.fromArray( positions, a * 3 ); | |
vB.fromArray( positions, b * 3 ); | |
vC.fromArray( positions, c * 3 ); | |
if ( material.side === THREE.BackSide ) { | |
var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); | |
} else { | |
var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); | |
} | |
if ( intersectionPoint === null ) continue; | |
intersectionPoint.applyMatrix4( this.matrixWorld ); | |
var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); | |
if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; | |
intersects.push( { | |
distance: distance, | |
point: intersectionPoint, | |
face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), | |
faceIndex: null, | |
object: this | |
} ); | |
} | |
} | |
} else { | |
var positions = attributes.position.array; | |
for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) { | |
a = i; | |
b = i + 1; | |
c = i + 2; | |
vA.fromArray( positions, j ); | |
vB.fromArray( positions, j + 3 ); | |
vC.fromArray( positions, j + 6 ); | |
if ( material.side === THREE.BackSide ) { | |
var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); | |
} else { | |
var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); | |
} | |
if ( intersectionPoint === null ) continue; | |
intersectionPoint.applyMatrix4( this.matrixWorld ); | |
var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); | |
if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; | |
intersects.push( { | |
distance: distance, | |
point: intersectionPoint, | |
face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), | |
faceIndex: null, | |
object: this | |
} ); | |
} | |
} | |
} else if ( geometry instanceof THREE.Geometry ) { | |
var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial; | |
var objectMaterials = isFaceMaterial === true ? this.material.materials : null; | |
var a, b, c, d; | |
var precision = raycaster.precision; | |
var vertices = geometry.vertices; | |
for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { | |
var face = geometry.faces[ f ]; | |
var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material; | |
if ( material === undefined ) continue; | |
a = vertices[ face.a ]; | |
b = vertices[ face.b ]; | |
c = vertices[ face.c ]; | |
if ( material.morphTargets === true ) { | |
var morphTargets = geometry.morphTargets; | |
var morphInfluences = this.morphTargetInfluences; | |
vA.set( 0, 0, 0 ); | |
vB.set( 0, 0, 0 ); | |
vC.set( 0, 0, 0 ); | |
for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { | |
var influence = morphInfluences[ t ]; | |
if ( influence === 0 ) continue; | |
var targets = morphTargets[ t ].vertices; | |
vA.x += ( targets[ face.a ].x - a.x ) * influence; | |
vA.y += ( targets[ face.a ].y - a.y ) * influence; | |
vA.z += ( targets[ face.a ].z - a.z ) * influence; | |
vB.x += ( targets[ face.b ].x - b.x ) * influence; | |
vB.y += ( targets[ face.b ].y - b.y ) * influence; | |
vB.z += ( targets[ face.b ].z - b.z ) * influence; | |
vC.x += ( targets[ face.c ].x - c.x ) * influence; | |
vC.y += ( targets[ face.c ].y - c.y ) * influence; | |
vC.z += ( targets[ face.c ].z - c.z ) * influence; | |
} | |
vA.add( a ); | |
vB.add( b ); | |
vC.add( c ); | |
a = vA; | |
b = vB; | |
c = vC; | |
} | |
if ( material.side === THREE.BackSide ) { | |
var intersectionPoint = ray.intersectTriangle( c, b, a, true ); | |
} else { | |
var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide ); | |
} | |
if ( intersectionPoint === null ) continue; | |
intersectionPoint.applyMatrix4( this.matrixWorld ); | |
var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); | |
if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; | |
intersects.push( { | |
distance: distance, | |
point: intersectionPoint, | |
face: face, | |
faceIndex: f, | |
object: this | |
} ); | |
} | |
} | |
}; | |
}() ); | |
THREE.Mesh.prototype.clone = function ( object, recursive ) { | |
if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material ); | |
THREE.Object3D.prototype.clone.call( this, object, recursive ); | |
return object; | |
}; | |
// File:src/objects/Bone.js | |
/** | |
* @author mikael emtinger / http://gomo.se/ | |
* @author alteredq / http://alteredqualia.com/ | |
* @author ikerr / http://verold.com | |
*/ | |
THREE.Bone = function ( belongsToSkin ) { | |
THREE.Object3D.call( this ); | |
this.skin = belongsToSkin; | |
}; | |
THREE.Bone.prototype = Object.create( THREE.Object3D.prototype ); | |
// File:src/objects/Skeleton.js | |
/** | |
* @author mikael emtinger / http://gomo.se/ | |
* @author alteredq / http://alteredqualia.com/ | |
* @author michael guerrero / http://realitymeltdown.com | |
* @author ikerr / http://verold.com | |
*/ | |
THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { | |
this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; | |
this.identityMatrix = new THREE.Matrix4(); | |
// copy the bone array | |
bones = bones || []; | |
this.bones = bones.slice( 0 ); | |
// create a bone texture or an array of floats | |
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 ( this.bones.length > 256 ) | |
size = 64; | |
else if ( this.bones.length > 64 ) | |
size = 32; | |
else if ( this.bones.length > 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 * this.bones.length ); | |
} | |
// use the supplied bone inverses or calculate the inverses | |
if ( boneInverses === undefined ) { | |
this.calculateInverses(); | |
} else { | |
if ( this.bones.length === boneInverses.length ) { | |
this.boneInverses = boneInverses.slice( 0 ); | |
} else { | |
console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); | |
this.boneInverses = []; | |
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { | |
this.boneInverses.push( new THREE.Matrix4() ); | |
} | |
} | |
} | |
}; | |
THREE.Skeleton.prototype.calculateInverses = function () { | |
this.boneInverses = []; | |
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { | |
var inverse = new THREE.Matrix4(); | |
if ( this.bones[ b ] ) { | |
inverse.getInverse( this.bones[ b ].matrixWorld ); | |
} | |
this.boneInverses.push( inverse ); | |
} | |
}; | |
THREE.Skeleton.prototype.pose = function () { | |
var bone; | |
// recover the bind-time world matrices | |
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { | |
bone = this.bones[ b ]; | |
if ( bone ) { | |
bone.matrixWorld.getInverse( this.boneInverses[ b ] ); | |
} | |
} | |
// compute the local matrices, positions, rotations and scales | |
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { | |
bone = this.bones[ b ]; | |
if ( bone ) { | |
if ( bone.parent ) { | |
bone.matrix.getInverse( bone.parent.matrixWorld ); | |
bone.matrix.multiply( bone.matrixWorld ); | |
} else { | |
bone.matrix.copy( bone.matrixWorld ); | |
} | |
bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); | |
} | |
} | |
}; | |
THREE.Skeleton.prototype.update = ( function () { | |
var offsetMatrix = new THREE.Matrix4(); | |
return function () { | |
// 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 | |
var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; | |
offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); | |
offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 ); | |
} | |
if ( this.useVertexTexture ) { | |
this.boneTexture.needsUpdate = true; | |
} | |
}; | |
} )(); | |
// File:src/objects/SkinnedMesh.js | |
/** | |
* @author mikael emtinger / http://gomo.se/ | |
* @author alteredq / http://alteredqualia.com/ | |
* @author ikerr / http://verold.com | |
*/ | |
THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { | |
THREE.Mesh.call( this, geometry, material ); | |
this.type = 'SkinnedMesh'; | |
this.bindMode = "attached"; | |
this.bindMatrix = new THREE.Matrix4(); | |
this.bindMatrixInverse = new THREE.Matrix4(); | |
// init bones | |
// TODO: remove bone creation as there is no reason (other than | |
// convenience) for THREE.SkinnedMesh to do this. | |
var bones = []; | |
if ( this.geometry && this.geometry.bones !== undefined ) { | |
var bone, gbone, p, q, s; | |
for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++b ) { | |
gbone = this.geometry.bones[ b ]; | |
p = gbone.pos; | |
q = gbone.rotq; | |
s = gbone.scl; | |
bone = new THREE.Bone( this ); | |
bones.push( bone ); | |
bone.name = gbone.name; | |
bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] ); | |
bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] ); | |
if ( s !== undefined ) { | |
bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] ); | |
} else { | |
bone.scale.set( 1, 1, 1 ); | |
} | |
} | |
for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++b ) { | |
gbone = this.geometry.bones[ b ]; | |
if ( gbone.parent !== - 1 ) { | |
bones[ gbone.parent ].add( bones[ b ] ); | |
} else { | |
this.add( bones[ b ] ); | |
} | |
} | |
} | |
this.normalizeSkinWeights(); | |
this.updateMatrixWorld( true ); | |
this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) ); | |
}; | |
THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype ); | |
THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) { | |
this.skeleton = skeleton; | |
if ( bindMatrix === undefined ) { | |
this.updateMatrixWorld( true ); | |
bindMatrix = this.matrixWorld; | |
} | |
this.bindMatrix.copy( bindMatrix ); | |
this.bindMatrixInverse.getInverse( bindMatrix ); | |
}; | |
THREE.SkinnedMesh.prototype.pose = function () { | |
this.skeleton.pose(); | |
}; | |
THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () { | |
if ( this.geometry instanceof THREE.Geometry ) { | |
for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) { | |
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 | |
} | |
} | |
} else { | |
// skinning weights assumed to be normalized for THREE.BufferGeometry | |
} | |
}; | |
THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) { | |
THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); | |
if ( this.bindMode === "attached" ) { | |
this.bindMatrixInverse.getInverse( this.matrixWorld ); | |
} else if ( this.bindMode === "detached" ) { | |
this.bindMatrixInverse.getInverse( this.bindMatrix ); | |
} else { | |
console.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode ); | |
} | |
}; | |
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; | |
}; | |
// File:src/objects/MorphAnimMesh.js | |
/** | |
* @author alteredq / http://alteredqualia.com/ | |
*/ | |
THREE.MorphAnimMesh = function ( geometry, material ) { | |
THREE.Mesh.call( this, geometry, material ); | |
this.type = 'MorphAnimMesh'; | |
// 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.direc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment