code stringlengths 2 1.05M |
|---|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 11.55C9.64 9.35 6.48 8 3 8v11c3.48 0 6.64 1.35 9 3.55 2.36-2.19 5.52-3.55 9-3.55V8c-3.48 0-6.64 1.35-9 3.55zM12 8c1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3 1.34 3 3 3z"
}), 'LocalLibrarySharp'); |
var test = require('tape');
var distance = require('@turf/distance');
var destination = require('./');
test('destination', function(t){
var pt1 = {
type: "Feature",
geometry: {type: "Point", coordinates: [-75.0, 39.0]}
};
var dist = 100;
var bear = 180;
var pt2 = destination(pt1, dist, bear, 'kilometers');
t.deepEqual(pt2, { geometry: { coordinates: [ -75, 38.10096062273525 ], type: 'Point' }, properties: {}, type: 'Feature' }, 'returns the correct point');
t.end();
});
|
export default {
activeCall: "Aktiver Anruf"
};
// @key: @#@"activeCall"@#@ @source: @#@"Active Call"@#@
|
'use strict';
var test = require('tape');
var forEach = require('foreach');
var is = require('object-is');
var debug = require('object-inspect');
var assign = require('object.assign');
var keys = require('object-keys');
var has = require('has');
var assertRecordTests = require('./helpers/assertRecord');
var v = require('./helpers/values');
var diffOps = require('./diffOps');
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
var getArraySubclassWithSpeciesConstructor = function getArraySubclass(speciesConstructor) {
var Bar = function Bar() {
var inst = [];
Object.setPrototypeOf(inst, Bar.prototype);
Object.defineProperty(inst, 'constructor', { value: Bar });
return inst;
};
Bar.prototype = Object.create(Array.prototype);
Object.setPrototypeOf(Bar, Array);
Object.defineProperty(Bar, Symbol.species, { value: speciesConstructor });
return Bar;
};
var hasSpecies = v.hasSymbols && Symbol.species;
var hasGroups = 'groups' in (/a/).exec('a');
var groups = function groups(matchObject) {
return hasGroups ? assign(matchObject, { groups: matchObject.groups }) : matchObject;
};
var testEnumerableOwnNames = function (t, enumerableOwnNames) {
forEach(v.primitives, function (nonObject) {
t['throws'](
function () { enumerableOwnNames(nonObject); },
debug(nonObject) + ' is not an Object'
);
});
var Child = function Child() {
this.own = {};
};
Child.prototype = {
inherited: {}
};
var obj = new Child();
t.equal('own' in obj, true, 'has "own"');
t.equal(has(obj, 'own'), true, 'has own "own"');
t.equal(Object.prototype.propertyIsEnumerable.call(obj, 'own'), true, 'has enumerable "own"');
t.equal('inherited' in obj, true, 'has "inherited"');
t.equal(has(obj, 'inherited'), false, 'has non-own "inherited"');
t.equal(has(Child.prototype, 'inherited'), true, 'Child.prototype has own "inherited"');
t.equal(Child.prototype.inherited, obj.inherited, 'Child.prototype.inherited === obj.inherited');
t.equal(Object.prototype.propertyIsEnumerable.call(Child.prototype, 'inherited'), true, 'has enumerable "inherited"');
t.equal('toString' in obj, true, 'has "toString"');
t.equal(has(obj, 'toString'), false, 'has non-own "toString"');
t.equal(has(Object.prototype, 'toString'), true, 'Object.prototype has own "toString"');
t.equal(Object.prototype.toString, obj.toString, 'Object.prototype.toString === obj.toString');
// eslint-disable-next-line no-useless-call
t.equal(Object.prototype.propertyIsEnumerable.call(Object.prototype, 'toString'), false, 'has non-enumerable "toString"');
return obj;
};
var es2015 = function ES2015(ES, ops, expectedMissing, skips) {
test('has expected operations', function (t) {
var diff = diffOps(ES, ops, expectedMissing);
t.deepEqual(diff.extra, [], 'no extra ops');
t.deepEqual(diff.missing, [], 'no unexpected missing ops');
t.end();
});
test('ToPrimitive', function (t) {
t.test('primitives', function (st) {
var testPrimitive = function (primitive) {
st.ok(is(ES.ToPrimitive(primitive), primitive), debug(primitive) + ' is returned correctly');
};
forEach(v.primitives, testPrimitive);
st.end();
});
t.test('objects', function (st) {
st.equal(ES.ToPrimitive(v.coercibleObject), 3, 'coercibleObject with no hint coerces to valueOf');
st.ok(is(ES.ToPrimitive({}), '[object Object]'), '{} with no hint coerces to Object#toString');
st.equal(ES.ToPrimitive(v.coercibleObject, Number), 3, 'coercibleObject with hint Number coerces to valueOf');
st.ok(is(ES.ToPrimitive({}, Number), '[object Object]'), '{} with hint Number coerces to NaN');
st.equal(ES.ToPrimitive(v.coercibleObject, String), 42, 'coercibleObject with hint String coerces to nonstringified toString');
st.equal(ES.ToPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString');
st.equal(ES.ToPrimitive(v.toStringOnlyObject), 7, 'toStringOnlyObject returns non-stringified toString');
st.equal(ES.ToPrimitive(v.valueOfOnlyObject), 4, 'valueOfOnlyObject returns valueOf');
st['throws'](function () { return ES.ToPrimitive(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError');
st.end();
});
t.test('dates', function (st) {
var invalid = new Date(NaN);
st.equal(ES.ToPrimitive(invalid), Date.prototype.toString.call(invalid), 'invalid Date coerces to Date#toString');
var now = new Date();
st.equal(ES.ToPrimitive(now), Date.prototype.toString.call(now), 'Date coerces to Date#toString');
st.end();
});
t.end();
});
test('ToBoolean', function (t) {
t.equal(false, ES.ToBoolean(undefined), 'undefined coerces to false');
t.equal(false, ES.ToBoolean(null), 'null coerces to false');
t.equal(false, ES.ToBoolean(false), 'false returns false');
t.equal(true, ES.ToBoolean(true), 'true returns true');
t.test('numbers', function (st) {
forEach([0, -0, NaN], function (falsyNumber) {
st.equal(false, ES.ToBoolean(falsyNumber), 'falsy number ' + falsyNumber + ' coerces to false');
});
forEach([Infinity, 42, 1, -Infinity], function (truthyNumber) {
st.equal(true, ES.ToBoolean(truthyNumber), 'truthy number ' + truthyNumber + ' coerces to true');
});
st.end();
});
t.equal(false, ES.ToBoolean(''), 'empty string coerces to false');
t.equal(true, ES.ToBoolean('foo'), 'nonempty string coerces to true');
t.test('objects', function (st) {
forEach(v.objects, function (obj) {
st.equal(true, ES.ToBoolean(obj), 'object coerces to true');
});
st.equal(true, ES.ToBoolean(v.uncoercibleObject), 'uncoercibleObject coerces to true');
st.end();
});
t.end();
});
test('ToNumber', function (t) {
t.ok(is(NaN, ES.ToNumber(undefined)), 'undefined coerces to NaN');
t.ok(is(ES.ToNumber(null), 0), 'null coerces to +0');
t.ok(is(ES.ToNumber(false), 0), 'false coerces to +0');
t.equal(1, ES.ToNumber(true), 'true coerces to 1');
t.test('numbers', function (st) {
st.ok(is(NaN, ES.ToNumber(NaN)), 'NaN returns itself');
forEach([0, -0, 42, Infinity, -Infinity], function (num) {
st.equal(num, ES.ToNumber(num), num + ' returns itself');
});
forEach(['foo', '0', '4a', '2.0', 'Infinity', '-Infinity'], function (numString) {
st.ok(is(+numString, ES.ToNumber(numString)), '"' + numString + '" coerces to ' + Number(numString));
});
st.end();
});
t.test('objects', function (st) {
forEach(v.objects, function (object) {
st.ok(is(ES.ToNumber(object), ES.ToNumber(ES.ToPrimitive(object))), 'object ' + object + ' coerces to same as ToPrimitive of object does');
});
st['throws'](function () { return ES.ToNumber(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
st.end();
});
t.test('binary literals', function (st) {
st.equal(ES.ToNumber('0b10'), 2, '0b10 is 2');
st.equal(ES.ToNumber({ toString: function () { return '0b11'; } }), 3, 'Object that toStrings to 0b11 is 3');
st.equal(true, is(ES.ToNumber('0b12'), NaN), '0b12 is NaN');
st.equal(true, is(ES.ToNumber({ toString: function () { return '0b112'; } }), NaN), 'Object that toStrings to 0b112 is NaN');
st.end();
});
t.test('octal literals', function (st) {
st.equal(ES.ToNumber('0o10'), 8, '0o10 is 8');
st.equal(ES.ToNumber({ toString: function () { return '0o11'; } }), 9, 'Object that toStrings to 0o11 is 9');
st.equal(true, is(ES.ToNumber('0o18'), NaN), '0o18 is NaN');
st.equal(true, is(ES.ToNumber({ toString: function () { return '0o118'; } }), NaN), 'Object that toStrings to 0o118 is NaN');
st.end();
});
t.test('signed hex numbers', function (st) {
st.equal(true, is(ES.ToNumber('-0xF'), NaN), '-0xF is NaN');
st.equal(true, is(ES.ToNumber(' -0xF '), NaN), 'space-padded -0xF is NaN');
st.equal(true, is(ES.ToNumber('+0xF'), NaN), '+0xF is NaN');
st.equal(true, is(ES.ToNumber(' +0xF '), NaN), 'space-padded +0xF is NaN');
st.end();
});
t.test('trimming of whitespace and non-whitespace characters', function (st) {
var whitespace = ' \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000';
st.equal(0, ES.ToNumber(whitespace + 0 + whitespace), 'whitespace is trimmed');
// Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace.
var nonWhitespaces = {
'\\u0085': '\u0085',
'\\u200b': '\u200b',
'\\ufffe': '\ufffe'
};
forEach(nonWhitespaces, function (desc, nonWS) {
st.equal(true, is(ES.ToNumber(nonWS + 0 + nonWS), NaN), 'non-whitespace ' + desc + ' not trimmed');
});
st.end();
});
forEach(v.symbols, function (symbol) {
t['throws'](
function () { ES.ToNumber(symbol); },
TypeError,
'Symbols can’t be converted to a Number: ' + debug(symbol)
);
});
t.test('dates', function (st) {
var invalid = new Date(NaN);
st.ok(is(ES.ToNumber(invalid), NaN), 'invalid Date coerces to NaN');
var now = Date.now();
st.equal(ES.ToNumber(new Date(now)), now, 'Date coerces to timestamp');
st.end();
});
t.end();
});
test('ToInteger', function (t) {
t.ok(is(0, ES.ToInteger(NaN)), 'NaN coerces to +0');
forEach([0, Infinity, 42], function (num) {
t.ok(is(num, ES.ToInteger(num)), num + ' returns itself');
t.ok(is(-num, ES.ToInteger(-num)), '-' + num + ' returns itself');
});
t.equal(3, ES.ToInteger(Math.PI), 'pi returns 3');
t['throws'](function () { return ES.ToInteger(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
t.end();
});
test('ToInt32', function (t) {
t.ok(is(0, ES.ToInt32(NaN)), 'NaN coerces to +0');
forEach([0, Infinity], function (num) {
t.ok(is(0, ES.ToInt32(num)), num + ' returns +0');
t.ok(is(0, ES.ToInt32(-num)), '-' + num + ' returns +0');
});
t['throws'](function () { return ES.ToInt32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
t.ok(is(ES.ToInt32(0x100000000), 0), '2^32 returns +0');
t.ok(is(ES.ToInt32(0x100000000 - 1), -1), '2^32 - 1 returns -1');
t.ok(is(ES.ToInt32(0x80000000), -0x80000000), '2^31 returns -2^31');
t.ok(is(ES.ToInt32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1');
forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) {
t.ok(is(ES.ToInt32(num), ES.ToInt32(ES.ToUint32(num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for 0x' + num.toString(16));
t.ok(is(ES.ToInt32(-num), ES.ToInt32(ES.ToUint32(-num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for -0x' + num.toString(16));
});
t.end();
});
test('ToUint32', function (t) {
t.ok(is(0, ES.ToUint32(NaN)), 'NaN coerces to +0');
forEach([0, Infinity], function (num) {
t.ok(is(0, ES.ToUint32(num)), num + ' returns +0');
t.ok(is(0, ES.ToUint32(-num)), '-' + num + ' returns +0');
});
t['throws'](function () { return ES.ToUint32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
t.ok(is(ES.ToUint32(0x100000000), 0), '2^32 returns +0');
t.ok(is(ES.ToUint32(0x100000000 - 1), 0x100000000 - 1), '2^32 - 1 returns 2^32 - 1');
t.ok(is(ES.ToUint32(0x80000000), 0x80000000), '2^31 returns 2^31');
t.ok(is(ES.ToUint32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1');
forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) {
t.ok(is(ES.ToUint32(num), ES.ToUint32(ES.ToInt32(num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for 0x' + num.toString(16));
t.ok(is(ES.ToUint32(-num), ES.ToUint32(ES.ToInt32(-num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for -0x' + num.toString(16));
});
t.end();
});
test('ToInt16', function (t) {
t.ok(is(0, ES.ToInt16(NaN)), 'NaN coerces to +0');
forEach([0, Infinity], function (num) {
t.ok(is(0, ES.ToInt16(num)), num + ' returns +0');
t.ok(is(0, ES.ToInt16(-num)), '-' + num + ' returns +0');
});
t['throws'](function () { return ES.ToInt16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
t.ok(is(ES.ToInt16(0x100000000), 0), '2^32 returns +0');
t.ok(is(ES.ToInt16(0x100000000 - 1), -1), '2^32 - 1 returns -1');
t.ok(is(ES.ToInt16(0x80000000), 0), '2^31 returns +0');
t.ok(is(ES.ToInt16(0x80000000 - 1), -1), '2^31 - 1 returns -1');
t.ok(is(ES.ToInt16(0x10000), 0), '2^16 returns +0');
t.ok(is(ES.ToInt16(0x10000 - 1), -1), '2^16 - 1 returns -1');
t.end();
});
test('ToUint16', function (t) {
t.ok(is(0, ES.ToUint16(NaN)), 'NaN coerces to +0');
forEach([0, Infinity], function (num) {
t.ok(is(0, ES.ToUint16(num)), num + ' returns +0');
t.ok(is(0, ES.ToUint16(-num)), '-' + num + ' returns +0');
});
t['throws'](function () { return ES.ToUint16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
t.ok(is(ES.ToUint16(0x100000000), 0), '2^32 returns +0');
t.ok(is(ES.ToUint16(0x100000000 - 1), 0x10000 - 1), '2^32 - 1 returns 2^16 - 1');
t.ok(is(ES.ToUint16(0x80000000), 0), '2^31 returns +0');
t.ok(is(ES.ToUint16(0x80000000 - 1), 0x10000 - 1), '2^31 - 1 returns 2^16 - 1');
t.ok(is(ES.ToUint16(0x10000), 0), '2^16 returns +0');
t.ok(is(ES.ToUint16(0x10000 - 1), 0x10000 - 1), '2^16 - 1 returns 2^16 - 1');
t.end();
});
test('ToInt8', function (t) {
t.ok(is(0, ES.ToInt8(NaN)), 'NaN coerces to +0');
forEach([0, Infinity], function (num) {
t.ok(is(0, ES.ToInt8(num)), num + ' returns +0');
t.ok(is(0, ES.ToInt8(-num)), '-' + num + ' returns +0');
});
t['throws'](function () { return ES.ToInt8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
t.ok(is(ES.ToInt8(0x100000000), 0), '2^32 returns +0');
t.ok(is(ES.ToInt8(0x100000000 - 1), -1), '2^32 - 1 returns -1');
t.ok(is(ES.ToInt8(0x80000000), 0), '2^31 returns +0');
t.ok(is(ES.ToInt8(0x80000000 - 1), -1), '2^31 - 1 returns -1');
t.ok(is(ES.ToInt8(0x10000), 0), '2^16 returns +0');
t.ok(is(ES.ToInt8(0x10000 - 1), -1), '2^16 - 1 returns -1');
t.ok(is(ES.ToInt8(0x100), 0), '2^8 returns +0');
t.ok(is(ES.ToInt8(0x100 - 1), -1), '2^8 - 1 returns -1');
t.ok(is(ES.ToInt8(0x10), 0x10), '2^4 returns 2^4');
t.end();
});
test('ToUint8', function (t) {
t.ok(is(0, ES.ToUint8(NaN)), 'NaN coerces to +0');
forEach([0, Infinity], function (num) {
t.ok(is(0, ES.ToUint8(num)), num + ' returns +0');
t.ok(is(0, ES.ToUint8(-num)), '-' + num + ' returns +0');
});
t['throws'](function () { return ES.ToUint8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
t.ok(is(ES.ToUint8(0x100000000), 0), '2^32 returns +0');
t.ok(is(ES.ToUint8(0x100000000 - 1), 0x100 - 1), '2^32 - 1 returns 2^8 - 1');
t.ok(is(ES.ToUint8(0x80000000), 0), '2^31 returns +0');
t.ok(is(ES.ToUint8(0x80000000 - 1), 0x100 - 1), '2^31 - 1 returns 2^8 - 1');
t.ok(is(ES.ToUint8(0x10000), 0), '2^16 returns +0');
t.ok(is(ES.ToUint8(0x10000 - 1), 0x100 - 1), '2^16 - 1 returns 2^8 - 1');
t.ok(is(ES.ToUint8(0x100), 0), '2^8 returns +0');
t.ok(is(ES.ToUint8(0x100 - 1), 0x100 - 1), '2^8 - 1 returns 2^16 - 1');
t.ok(is(ES.ToUint8(0x10), 0x10), '2^4 returns 2^4');
t.ok(is(ES.ToUint8(0x10 - 1), 0x10 - 1), '2^4 - 1 returns 2^4 - 1');
t.end();
});
test('ToUint8Clamp', function (t) {
t.ok(is(0, ES.ToUint8Clamp(NaN)), 'NaN coerces to +0');
t.ok(is(0, ES.ToUint8Clamp(0)), '+0 returns +0');
t.ok(is(0, ES.ToUint8Clamp(-0)), '-0 returns +0');
t.ok(is(0, ES.ToUint8Clamp(-Infinity)), '-Infinity returns +0');
t['throws'](function () { return ES.ToUint8Clamp(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
forEach([255, 256, 0x100000, Infinity], function (number) {
t.ok(is(255, ES.ToUint8Clamp(number)), number + ' coerces to 255');
});
t.equal(1, ES.ToUint8Clamp(1.49), '1.49 coerces to 1');
t.equal(2, ES.ToUint8Clamp(1.5), '1.5 coerces to 2, because 2 is even');
t.equal(2, ES.ToUint8Clamp(1.51), '1.51 coerces to 2');
t.equal(2, ES.ToUint8Clamp(2.49), '2.49 coerces to 2');
t.equal(2, ES.ToUint8Clamp(2.5), '2.5 coerces to 2, because 2 is even');
t.equal(3, ES.ToUint8Clamp(2.51), '2.51 coerces to 3');
t.end();
});
test('ToString', function (t) {
forEach(v.objects.concat(v.nonSymbolPrimitives), function (item) {
t.equal(ES.ToString(item), String(item), 'ES.ToString(' + debug(item) + ') ToStrings to String(' + debug(item) + ')');
});
t['throws'](function () { return ES.ToString(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws');
forEach(v.symbols, function (symbol) {
t['throws'](function () { return ES.ToString(symbol); }, TypeError, debug(symbol) + ' throws');
});
t.end();
});
test('ToObject', function (t) {
t['throws'](function () { return ES.ToObject(undefined); }, TypeError, 'undefined throws');
t['throws'](function () { return ES.ToObject(null); }, TypeError, 'null throws');
forEach(v.numbers, function (number) {
var obj = ES.ToObject(number);
t.equal(typeof obj, 'object', 'number ' + number + ' coerces to object');
t.equal(true, obj instanceof Number, 'object of ' + number + ' is Number object');
t.ok(is(obj.valueOf(), number), 'object of ' + number + ' coerces to ' + number);
});
t.end();
});
test('RequireObjectCoercible', function (t) {
t.equal(false, 'CheckObjectCoercible' in ES, 'CheckObjectCoercible -> RequireObjectCoercible in ES6');
t['throws'](function () { return ES.RequireObjectCoercible(undefined); }, TypeError, 'undefined throws');
t['throws'](function () { return ES.RequireObjectCoercible(null); }, TypeError, 'null throws');
var isCoercible = function (value) {
t.doesNotThrow(function () { return ES.RequireObjectCoercible(value); }, debug(value) + ' does not throw');
};
forEach(v.objects.concat(v.nonNullPrimitives), isCoercible);
t.end();
});
test('IsCallable', function (t) {
t.equal(true, ES.IsCallable(function () {}), 'function is callable');
var nonCallables = [/a/g, {}, Object.prototype, NaN].concat(v.nonFunctions);
forEach(nonCallables, function (nonCallable) {
t.equal(false, ES.IsCallable(nonCallable), debug(nonCallable) + ' is not callable');
});
t.end();
});
test('SameValue', function (t) {
t.equal(true, ES.SameValue(NaN, NaN), 'NaN is SameValue as NaN');
t.equal(false, ES.SameValue(0, -0), '+0 is not SameValue as -0');
forEach(v.objects.concat(v.primitives), function (val) {
t.equal(val === val, ES.SameValue(val, val), debug(val) + ' is SameValue to itself');
});
t.end();
});
test('SameValueZero', function (t) {
t.equal(true, ES.SameValueZero(NaN, NaN), 'NaN is SameValueZero as NaN');
t.equal(true, ES.SameValueZero(0, -0), '+0 is SameValueZero as -0');
forEach(v.objects.concat(v.primitives), function (val) {
t.equal(val === val, ES.SameValueZero(val, val), debug(val) + ' is SameValueZero to itself');
});
t.end();
});
test('ToPropertyKey', function (t) {
forEach(v.objects.concat(v.nonSymbolPrimitives), function (value) {
t.equal(ES.ToPropertyKey(value), String(value), 'ToPropertyKey(value) === String(value) for non-Symbols');
});
forEach(v.symbols, function (symbol) {
t.equal(
ES.ToPropertyKey(symbol),
symbol,
'ToPropertyKey(' + debug(symbol) + ') === ' + debug(symbol)
);
t.equal(
ES.ToPropertyKey(Object(symbol)),
symbol,
'ToPropertyKey(' + debug(Object(symbol)) + ') === ' + debug(symbol)
);
});
t.end();
});
test('ToLength', function (t) {
t['throws'](function () { return ES.ToLength(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError');
t.equal(3, ES.ToLength(v.coercibleObject), 'coercibleObject coerces to 3');
t.equal(42, ES.ToLength('42.5'), '"42.5" coerces to 42');
t.equal(7, ES.ToLength(7.3), '7.3 coerces to 7');
forEach([-0, -1, -42, -Infinity], function (negative) {
t.ok(is(0, ES.ToLength(negative)), negative + ' coerces to +0');
});
t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 1), '2^53 coerces to 2^53 - 1');
t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 3), '2^53 + 2 coerces to 2^53 - 1');
t.end();
});
test('IsArray', function (t) {
t.equal(true, ES.IsArray([]), '[] is array');
t.equal(false, ES.IsArray({}), '{} is not array');
t.equal(false, ES.IsArray({ length: 1, 0: true }), 'arraylike object is not array');
forEach(v.objects.concat(v.primitives), function (value) {
t.equal(false, ES.IsArray(value), debug(value) + ' is not array');
});
t.end();
});
test('IsRegExp', function (t) {
forEach([/a/g, new RegExp('a', 'g')], function (regex) {
t.equal(true, ES.IsRegExp(regex), regex + ' is regex');
});
forEach(v.objects.concat(v.primitives), function (nonRegex) {
t.equal(false, ES.IsRegExp(nonRegex), debug(nonRegex) + ' is not regex');
});
t.test('Symbol.match', { skip: !v.hasSymbols || !Symbol.match }, function (st) {
var obj = {};
obj[Symbol.match] = true;
st.equal(true, ES.IsRegExp(obj), 'object with truthy Symbol.match is regex');
var regex = /a/;
regex[Symbol.match] = false;
st.equal(false, ES.IsRegExp(regex), 'regex with falsy Symbol.match is not regex');
st.end();
});
t.end();
});
test('IsPropertyKey', function (t) {
forEach(v.numbers.concat(v.objects), function (notKey) {
t.equal(false, ES.IsPropertyKey(notKey), debug(notKey) + ' is not property key');
});
t.equal(true, ES.IsPropertyKey('foo'), 'string is property key');
forEach(v.symbols, function (symbol) {
t.equal(true, ES.IsPropertyKey(symbol), debug(symbol) + ' is property key');
});
t.end();
});
test('IsInteger', function (t) {
for (var i = -100; i < 100; i += 10) {
t.equal(true, ES.IsInteger(i), i + ' is integer');
t.equal(false, ES.IsInteger(i + 0.2), (i + 0.2) + ' is not integer');
}
t.equal(true, ES.IsInteger(-0), '-0 is integer');
var notInts = v.nonNumbers.concat(v.nonIntegerNumbers, [Infinity, -Infinity, NaN, [], new Date()]);
forEach(notInts, function (notInt) {
t.equal(false, ES.IsInteger(notInt), debug(notInt) + ' is not integer');
});
t.equal(false, ES.IsInteger(v.uncoercibleObject), 'uncoercibleObject is not integer');
t.end();
});
test('IsExtensible', function (t) {
forEach(v.objects, function (object) {
t.equal(true, ES.IsExtensible(object), debug(object) + ' object is extensible');
});
forEach(v.primitives, function (primitive) {
t.equal(false, ES.IsExtensible(primitive), debug(primitive) + ' is not extensible');
});
if (Object.preventExtensions) {
t.equal(false, ES.IsExtensible(Object.preventExtensions({})), 'object with extensions prevented is not extensible');
}
t.end();
});
test('CanonicalNumericIndexString', function (t) {
var throwsOnNonString = function (notString) {
t['throws'](
function () { return ES.CanonicalNumericIndexString(notString); },
TypeError,
debug(notString) + ' is not a string'
);
};
forEach(v.objects.concat(v.numbers), throwsOnNonString);
t.ok(is(-0, ES.CanonicalNumericIndexString('-0')), '"-0" returns -0');
for (var i = -50; i < 50; i += 10) {
t.equal(i, ES.CanonicalNumericIndexString(String(i)), '"' + i + '" returns ' + i);
t.equal(undefined, ES.CanonicalNumericIndexString(String(i) + 'a'), '"' + i + 'a" returns undefined');
}
t.end();
});
test('IsConstructor', function (t) {
t.equal(true, ES.IsConstructor(function () {}), 'function is constructor');
t.equal(false, ES.IsConstructor(/a/g), 'regex is not constructor');
forEach(v.objects, function (object) {
t.equal(false, ES.IsConstructor(object), object + ' object is not constructor');
});
try {
var foo = Function('return class Foo {}')(); // eslint-disable-line no-new-func
t.equal(ES.IsConstructor(foo), true, 'class is constructor');
} catch (e) {
t.comment('SKIP: class syntax not supported.');
}
t.end();
});
test('Call', function (t) {
var receiver = {};
var notFuncs = v.nonFunctions.concat([/a/g, new RegExp('a', 'g')]);
t.plan(notFuncs.length + 4);
var throwsIfNotCallable = function (notFunc) {
t['throws'](
function () { return ES.Call(notFunc, receiver); },
TypeError,
debug(notFunc) + ' (' + typeof notFunc + ') is not callable'
);
};
forEach(notFuncs, throwsIfNotCallable);
ES.Call(
function (a, b) {
t.equal(this, receiver, 'context matches expected');
t.deepEqual([a, b], [1, 2], 'named args are correct');
t.equal(arguments.length, 3, 'extra argument was passed');
t.equal(arguments[2], 3, 'extra argument was correct');
},
receiver,
[1, 2, 3]
);
t.end();
});
test('GetV', function (t) {
t['throws'](function () { return ES.GetV({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key');
var obj = { a: function () {} };
t.equal(ES.GetV(obj, 'a'), obj.a, 'returns property if it exists');
t.equal(ES.GetV(obj, 'b'), undefined, 'returns undefiend if property does not exist');
t.end();
});
test('GetMethod', function (t) {
t['throws'](function () { return ES.GetMethod({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key');
t.equal(ES.GetMethod({}, 'a'), undefined, 'returns undefined in property is undefined');
t.equal(ES.GetMethod({ a: null }, 'a'), undefined, 'returns undefined if property is null');
t.equal(ES.GetMethod({ a: undefined }, 'a'), undefined, 'returns undefined if property is undefined');
var obj = { a: function () {} };
t['throws'](function () { ES.GetMethod({ a: 'b' }, 'a'); }, TypeError, 'throws TypeError if property exists and is not callable');
t.equal(ES.GetMethod(obj, 'a'), obj.a, 'returns property if it is callable');
t.end();
});
test('Get', function (t) {
t['throws'](function () { return ES.Get('a', 'a'); }, TypeError, 'Throws a TypeError if `O` is not an Object');
t['throws'](function () { return ES.Get({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key');
var value = {};
t.test('Symbols', { skip: !v.hasSymbols }, function (st) {
var sym = Symbol('sym');
var obj = {};
obj[sym] = value;
st.equal(ES.Get(obj, sym), value, 'returns property `P` if it exists on object `O`');
st.end();
});
t.equal(ES.Get({ a: value }, 'a'), value, 'returns property `P` if it exists on object `O`');
t.end();
});
test('Type', { skip: !v.hasSymbols }, function (t) {
t.equal(ES.Type(Symbol.iterator), 'Symbol', 'Type(Symbol.iterator) is Symbol');
t.end();
});
test('SpeciesConstructor', function (t) {
t['throws'](function () { ES.SpeciesConstructor(null); }, TypeError);
t['throws'](function () { ES.SpeciesConstructor(undefined); }, TypeError);
var defaultConstructor = function Foo() {};
t.equal(
ES.SpeciesConstructor({ constructor: undefined }, defaultConstructor),
defaultConstructor,
'undefined constructor returns defaultConstructor'
);
t['throws'](
function () { return ES.SpeciesConstructor({ constructor: null }, defaultConstructor); },
TypeError,
'non-undefined non-object constructor throws'
);
t.test('with Symbol.species', { skip: !hasSpecies }, function (st) {
var Bar = function Bar() {};
Bar[Symbol.species] = null;
st.equal(
ES.SpeciesConstructor(new Bar(), defaultConstructor),
defaultConstructor,
'undefined/null Symbol.species returns default constructor'
);
var Baz = function Baz() {};
Baz[Symbol.species] = Bar;
st.equal(
ES.SpeciesConstructor(new Baz(), defaultConstructor),
Bar,
'returns Symbol.species constructor value'
);
Baz[Symbol.species] = {};
st['throws'](
function () { ES.SpeciesConstructor(new Baz(), defaultConstructor); },
TypeError,
'throws when non-constructor non-null non-undefined species value found'
);
st.end();
});
t.end();
});
test('IsPropertyDescriptor', { skip: skips && skips.IsPropertyDescriptor }, function (t) {
forEach(v.nonUndefinedPrimitives, function (primitive) {
t.equal(
ES.IsPropertyDescriptor(primitive),
false,
debug(primitive) + ' is not a Property Descriptor'
);
});
t.equal(ES.IsPropertyDescriptor({ invalid: true }), false, 'invalid keys not allowed on a Property Descriptor');
t.equal(ES.IsPropertyDescriptor({}), true, 'empty object is an incomplete Property Descriptor');
t.equal(ES.IsPropertyDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is a Property Descriptor');
t.equal(ES.IsPropertyDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is a Property Descriptor');
t.equal(ES.IsPropertyDescriptor(v.dataDescriptor()), true, 'data descriptor is a Property Descriptor');
t.equal(ES.IsPropertyDescriptor(v.genericDescriptor()), true, 'generic descriptor is a Property Descriptor');
t['throws'](
function () {
ES.IsPropertyDescriptor(v.bothDescriptor());
}, TypeError,
'a Property Descriptor can not be both a Data and an Accessor Descriptor'
);
t.end();
});
assertRecordTests(ES, test);
test('IsAccessorDescriptor', function (t) {
forEach(v.nonUndefinedPrimitives, function (primitive) {
t['throws'](
function () { ES.IsAccessorDescriptor(primitive); },
TypeError,
debug(primitive) + ' is not a Property Descriptor'
);
});
t.equal(ES.IsAccessorDescriptor(), false, 'no value is not an Accessor Descriptor');
t.equal(ES.IsAccessorDescriptor(undefined), false, 'undefined value is not an Accessor Descriptor');
t.equal(ES.IsAccessorDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is an Accessor Descriptor');
t.equal(ES.IsAccessorDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is an Accessor Descriptor');
t.equal(ES.IsAccessorDescriptor(v.dataDescriptor()), false, 'data descriptor is not an Accessor Descriptor');
t.equal(ES.IsAccessorDescriptor(v.genericDescriptor()), false, 'generic descriptor is not an Accessor Descriptor');
t.end();
});
test('IsDataDescriptor', function (t) {
forEach(v.nonUndefinedPrimitives, function (primitive) {
t['throws'](
function () { ES.IsDataDescriptor(primitive); },
TypeError,
debug(primitive) + ' is not a Property Descriptor'
);
});
t.equal(ES.IsDataDescriptor(), false, 'no value is not a Data Descriptor');
t.equal(ES.IsDataDescriptor(undefined), false, 'undefined value is not a Data Descriptor');
t.equal(ES.IsDataDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a Data Descriptor');
t.equal(ES.IsDataDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a Data Descriptor');
t.equal(ES.IsDataDescriptor(v.dataDescriptor()), true, 'data descriptor is a Data Descriptor');
t.equal(ES.IsDataDescriptor(v.genericDescriptor()), false, 'generic descriptor is not a Data Descriptor');
t.end();
});
test('IsGenericDescriptor', function (t) {
forEach(v.nonUndefinedPrimitives, function (primitive) {
t['throws'](
function () { ES.IsGenericDescriptor(primitive); },
TypeError,
debug(primitive) + ' is not a Property Descriptor'
);
});
t.equal(ES.IsGenericDescriptor(), false, 'no value is not a Data Descriptor');
t.equal(ES.IsGenericDescriptor(undefined), false, 'undefined value is not a Data Descriptor');
t.equal(ES.IsGenericDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a generic Descriptor');
t.equal(ES.IsGenericDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a generic Descriptor');
t.equal(ES.IsGenericDescriptor(v.dataDescriptor()), false, 'data descriptor is not a generic Descriptor');
t.equal(ES.IsGenericDescriptor(v.genericDescriptor()), true, 'generic descriptor is a generic Descriptor');
t.end();
});
test('FromPropertyDescriptor', function (t) {
t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined');
t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined');
forEach(v.nonUndefinedPrimitives, function (primitive) {
t['throws'](
function () { ES.FromPropertyDescriptor(primitive); },
TypeError,
debug(primitive) + ' is not a Property Descriptor'
);
});
var accessor = v.accessorDescriptor();
t.deepEqual(ES.FromPropertyDescriptor(accessor), {
get: accessor['[[Get]]'],
enumerable: !!accessor['[[Enumerable]]'],
configurable: !!accessor['[[Configurable]]']
});
var mutator = v.mutatorDescriptor();
t.deepEqual(ES.FromPropertyDescriptor(mutator), {
set: mutator['[[Set]]'],
enumerable: !!mutator['[[Enumerable]]'],
configurable: !!mutator['[[Configurable]]']
});
var data = v.dataDescriptor();
t.deepEqual(ES.FromPropertyDescriptor(data), {
value: data['[[Value]]'],
writable: data['[[Writable]]']
});
t.deepEqual(ES.FromPropertyDescriptor(v.genericDescriptor()), {
enumerable: false,
configurable: true
});
t.end();
});
test('ToPropertyDescriptor', function (t) {
forEach(v.nonUndefinedPrimitives, function (primitive) {
t['throws'](
function () { ES.ToPropertyDescriptor(primitive); },
TypeError,
debug(primitive) + ' is not an Object'
);
});
var accessor = v.accessorDescriptor();
t.deepEqual(ES.ToPropertyDescriptor({
get: accessor['[[Get]]'],
enumerable: !!accessor['[[Enumerable]]'],
configurable: !!accessor['[[Configurable]]']
}), accessor);
var mutator = v.mutatorDescriptor();
t.deepEqual(ES.ToPropertyDescriptor({
set: mutator['[[Set]]'],
enumerable: !!mutator['[[Enumerable]]'],
configurable: !!mutator['[[Configurable]]']
}), mutator);
var data = v.dataDescriptor();
t.deepEqual(ES.ToPropertyDescriptor({
value: data['[[Value]]'],
writable: data['[[Writable]]'],
configurable: !!data['[[Configurable]]']
}), assign(data, { '[[Configurable]]': false }));
var both = v.bothDescriptor();
t['throws'](
function () {
ES.FromPropertyDescriptor({ get: both['[[Get]]'], value: both['[[Value]]'] });
},
TypeError,
'data and accessor descriptors are mutually exclusive'
);
t.end();
});
test('CompletePropertyDescriptor', function (t) {
forEach(v.nonUndefinedPrimitives, function (primitive) {
t['throws'](
function () { ES.CompletePropertyDescriptor(primitive); },
TypeError,
debug(primitive) + ' is not a Property Descriptor'
);
});
var generic = v.genericDescriptor();
t.deepEqual(
ES.CompletePropertyDescriptor(generic),
{
'[[Configurable]]': !!generic['[[Configurable]]'],
'[[Enumerable]]': !!generic['[[Enumerable]]'],
'[[Value]]': undefined,
'[[Writable]]': false
},
'completes a Generic Descriptor'
);
var data = v.dataDescriptor();
t.deepEqual(
ES.CompletePropertyDescriptor(data),
{
'[[Configurable]]': !!data['[[Configurable]]'],
'[[Enumerable]]': false,
'[[Value]]': data['[[Value]]'],
'[[Writable]]': !!data['[[Writable]]']
},
'completes a Data Descriptor'
);
var accessor = v.accessorDescriptor();
t.deepEqual(
ES.CompletePropertyDescriptor(accessor),
{
'[[Get]]': accessor['[[Get]]'],
'[[Enumerable]]': !!accessor['[[Enumerable]]'],
'[[Configurable]]': !!accessor['[[Configurable]]'],
'[[Set]]': undefined
},
'completes an Accessor Descriptor'
);
var mutator = v.mutatorDescriptor();
t.deepEqual(
ES.CompletePropertyDescriptor(mutator),
{
'[[Set]]': mutator['[[Set]]'],
'[[Enumerable]]': !!mutator['[[Enumerable]]'],
'[[Configurable]]': !!mutator['[[Configurable]]'],
'[[Get]]': undefined
},
'completes a mutator Descriptor'
);
t['throws'](
function () { ES.CompletePropertyDescriptor(v.bothDescriptor()); },
TypeError,
'data and accessor descriptors are mutually exclusive'
);
t.end();
});
test('Set', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.Set(primitive, '', null, false); },
TypeError,
debug(primitive) + ' is not an Object'
);
});
forEach(v.nonPropertyKeys, function (nonKey) {
t['throws'](
function () { ES.Set({}, nonKey, null, false); },
TypeError,
debug(nonKey) + ' is not a Property Key'
);
});
forEach(v.nonBooleans, function (nonBoolean) {
t['throws'](
function () { ES.Set({}, '', null, nonBoolean); },
TypeError,
debug(nonBoolean) + ' is not a Boolean'
);
});
var o = {};
var value = {};
ES.Set(o, 'key', value, true);
t.deepEqual(o, { key: value }, 'key is set');
t.test('nonwritable', { skip: !Object.defineProperty }, function (st) {
var obj = { a: value };
Object.defineProperty(obj, 'a', { writable: false });
st['throws'](
function () { ES.Set(obj, 'a', value, true); },
TypeError,
'can not Set nonwritable property'
);
st.doesNotThrow(
function () { ES.Set(obj, 'a', value, false); },
'setting Throw to false prevents an exception'
);
st.end();
});
t.test('nonconfigurable', { skip: !Object.defineProperty }, function (st) {
var obj = { a: value };
Object.defineProperty(obj, 'a', { configurable: false });
ES.Set(obj, 'a', value, true);
st.deepEqual(obj, { a: value }, 'key is set');
st.end();
});
t.end();
});
test('HasOwnProperty', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.HasOwnProperty(primitive, 'key'); },
TypeError,
debug(primitive) + ' is not an Object'
);
});
forEach(v.nonPropertyKeys, function (nonKey) {
t['throws'](
function () { ES.HasOwnProperty({}, nonKey); },
TypeError,
debug(nonKey) + ' is not a Property Key'
);
});
t.equal(ES.HasOwnProperty({}, 'toString'), false, 'inherited properties are not own');
t.equal(
ES.HasOwnProperty({ toString: 1 }, 'toString'),
true,
'shadowed inherited own properties are own'
);
t.equal(ES.HasOwnProperty({ a: 1 }, 'a'), true, 'own properties are own');
t.end();
});
test('HasProperty', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.HasProperty(primitive, 'key'); },
TypeError,
debug(primitive) + ' is not an Object'
);
});
forEach(v.nonPropertyKeys, function (nonKey) {
t['throws'](
function () { ES.HasProperty({}, nonKey); },
TypeError,
debug(nonKey) + ' is not a Property Key'
);
});
t.equal(ES.HasProperty({}, 'nope'), false, 'object does not have nonexistent properties');
t.equal(ES.HasProperty({}, 'toString'), true, 'object has inherited properties');
t.equal(
ES.HasProperty({ toString: 1 }, 'toString'),
true,
'object has shadowed inherited own properties'
);
t.equal(ES.HasProperty({ a: 1 }, 'a'), true, 'object has own properties');
t.end();
});
test('IsConcatSpreadable', function (t) {
forEach(v.primitives, function (primitive) {
t.equal(ES.IsConcatSpreadable(primitive), false, debug(primitive) + ' is not an Object');
});
var hasSymbolConcatSpreadable = v.hasSymbols && Symbol.isConcatSpreadable;
t.test('Symbol.isConcatSpreadable', { skip: !hasSymbolConcatSpreadable }, function (st) {
forEach(v.falsies, function (falsy) {
var obj = {};
obj[Symbol.isConcatSpreadable] = falsy;
st.equal(
ES.IsConcatSpreadable(obj),
false,
'an object with ' + debug(falsy) + ' as Symbol.isConcatSpreadable is not concat spreadable'
);
});
forEach(v.truthies, function (truthy) {
var obj = {};
obj[Symbol.isConcatSpreadable] = truthy;
st.equal(
ES.IsConcatSpreadable(obj),
true,
'an object with ' + debug(truthy) + ' as Symbol.isConcatSpreadable is concat spreadable'
);
});
st.end();
});
forEach(v.objects, function (object) {
t.equal(
ES.IsConcatSpreadable(object),
false,
'non-array without Symbol.isConcatSpreadable is not concat spreadable'
);
});
t.equal(ES.IsConcatSpreadable([]), true, 'arrays are concat spreadable');
t.end();
});
test('Invoke', function (t) {
forEach(v.nonPropertyKeys, function (nonKey) {
t['throws'](
function () { ES.Invoke({}, nonKey); },
TypeError,
debug(nonKey) + ' is not a Property Key'
);
});
t['throws'](function () { ES.Invoke({ o: false }, 'o'); }, TypeError, 'fails on a non-function');
t.test('invoked callback', function (st) {
var aValue = {};
var bValue = {};
var obj = {
f: function (a) {
st.equal(arguments.length, 2, '2 args passed');
st.equal(a, aValue, 'first arg is correct');
st.equal(arguments[1], bValue, 'second arg is correct');
}
};
st.plan(3);
ES.Invoke(obj, 'f', aValue, bValue);
});
t.end();
});
test('GetIterator', { skip: true });
test('IteratorNext', { skip: true });
test('IteratorComplete', { skip: true });
test('IteratorValue', { skip: true });
test('IteratorStep', { skip: true });
test('IteratorClose', { skip: true });
test('CreateIterResultObject', function (t) {
forEach(v.nonBooleans, function (nonBoolean) {
t['throws'](
function () { ES.CreateIterResultObject({}, nonBoolean); },
TypeError,
'"done" argument must be a boolean; ' + debug(nonBoolean) + ' is not'
);
});
var value = {};
t.deepEqual(
ES.CreateIterResultObject(value, true),
{ value: value, done: true },
'creates a "done" iteration result'
);
t.deepEqual(
ES.CreateIterResultObject(value, false),
{ value: value, done: false },
'creates a "not done" iteration result'
);
t.end();
});
test('RegExpExec', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.RegExpExec(primitive); },
TypeError,
'"R" argument must be an object; ' + debug(primitive) + ' is not'
);
});
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { ES.RegExpExec({}, nonString); },
TypeError,
'"S" argument must be a String; ' + debug(nonString) + ' is not'
);
});
t.test('gets and calls a callable "exec"', function (st) {
var str = '123';
var o = {
exec: function (S) {
st.equal(this, o, '"exec" receiver is R');
st.equal(S, str, '"exec" argument is S');
return null;
}
};
st.plan(2);
ES.RegExpExec(o, str);
st.end();
});
t.test('throws if a callable "exec" returns a non-null non-object', function (st) {
var str = '123';
st.plan(v.nonNullPrimitives.length);
forEach(v.nonNullPrimitives, function (nonNullPrimitive) {
st['throws'](
function () { ES.RegExpExec({ exec: function () { return nonNullPrimitive; } }, str); },
TypeError,
'"exec" method must return `null` or an Object; ' + debug(nonNullPrimitive) + ' is not'
);
});
st.end();
});
t.test('actual regex that should match against a string', function (st) {
var S = 'aabc';
var R = /a/g;
var match1 = ES.RegExpExec(R, S);
var match2 = ES.RegExpExec(R, S);
var match3 = ES.RegExpExec(R, S);
st.deepEqual(match1, assign(['a'], groups({ index: 0, input: S })), 'match object 1 is as expected');
st.deepEqual(match2, assign(['a'], groups({ index: 1, input: S })), 'match object 2 is as expected');
st.equal(match3, null, 'match 3 is null as expected');
st.end();
});
t.test('actual regex that should match against a string, with shadowed "exec"', function (st) {
var S = 'aabc';
var R = /a/g;
R.exec = undefined;
var match1 = ES.RegExpExec(R, S);
var match2 = ES.RegExpExec(R, S);
var match3 = ES.RegExpExec(R, S);
st.deepEqual(match1, assign(['a'], groups({ index: 0, input: S })), 'match object 1 is as expected');
st.deepEqual(match2, assign(['a'], groups({ index: 1, input: S })), 'match object 2 is as expected');
st.equal(match3, null, 'match 3 is null as expected');
st.end();
});
t.end();
});
test('ArraySpeciesCreate', function (t) {
t.test('errors', function (st) {
var testNonNumber = function (nonNumber) {
st['throws'](
function () { ES.ArraySpeciesCreate([], nonNumber); },
TypeError,
debug(nonNumber) + ' is not a number'
);
};
forEach(v.nonNumbers, testNonNumber);
st['throws'](
function () { ES.ArraySpeciesCreate([], -1); },
TypeError,
'-1 is not >= 0'
);
st['throws'](
function () { ES.ArraySpeciesCreate([], -Infinity); },
TypeError,
'-Infinity is not >= 0'
);
var testNonIntegers = function (nonInteger) {
st['throws'](
function () { ES.ArraySpeciesCreate([], nonInteger); },
TypeError,
debug(nonInteger) + ' is not an integer'
);
};
forEach(v.nonIntegerNumbers, testNonIntegers);
st.end();
});
t.test('works with a non-array', function (st) {
forEach(v.objects.concat(v.primitives), function (nonArray) {
var arr = ES.ArraySpeciesCreate(nonArray, 0);
st.ok(ES.IsArray(arr), 'is an array');
st.equal(arr.length, 0, 'length is correct');
st.equal(arr.constructor, Array, 'constructor is correct');
});
st.end();
});
t.test('works with a normal array', function (st) {
var len = 2;
var orig = [1, 2, 3];
var arr = ES.ArraySpeciesCreate(orig, len);
st.ok(ES.IsArray(arr), 'is an array');
st.equal(arr.length, len, 'length is correct');
st.equal(arr.constructor, orig.constructor, 'constructor is correct');
st.end();
});
t.test('-0 length produces +0 length', function (st) {
var len = -0;
st.ok(is(len, -0), '-0 is negative zero');
st.notOk(is(len, 0), '-0 is not positive zero');
var orig = [1, 2, 3];
var arr = ES.ArraySpeciesCreate(orig, len);
st.equal(ES.IsArray(arr), true);
st.ok(is(arr.length, 0));
st.equal(arr.constructor, orig.constructor);
st.end();
});
t.test('works with species construtor', { skip: !hasSpecies }, function (st) {
var sentinel = {};
var Foo = function Foo(len) {
this.length = len;
this.sentinel = sentinel;
};
var Bar = getArraySubclassWithSpeciesConstructor(Foo);
var bar = new Bar();
t.equal(ES.IsArray(bar), true, 'Bar instance is an array');
var arr = ES.ArraySpeciesCreate(bar, 3);
st.equal(arr.constructor, Foo, 'result used species constructor');
st.equal(arr.length, 3, 'length property is correct');
st.equal(arr.sentinel, sentinel, 'Foo constructor was exercised');
st.end();
});
t.test('works with null species constructor', { skip: !hasSpecies }, function (st) {
var Bar = getArraySubclassWithSpeciesConstructor(null);
var bar = new Bar();
t.equal(ES.IsArray(bar), true, 'Bar instance is an array');
var arr = ES.ArraySpeciesCreate(bar, 3);
st.equal(arr.constructor, Array, 'result used default constructor');
st.equal(arr.length, 3, 'length property is correct');
st.end();
});
t.test('works with undefined species constructor', { skip: !hasSpecies }, function (st) {
var Bar = getArraySubclassWithSpeciesConstructor();
var bar = new Bar();
t.equal(ES.IsArray(bar), true, 'Bar instance is an array');
var arr = ES.ArraySpeciesCreate(bar, 3);
st.equal(arr.constructor, Array, 'result used default constructor');
st.equal(arr.length, 3, 'length property is correct');
st.end();
});
t.test('throws with object non-construtor species constructor', { skip: !hasSpecies }, function (st) {
forEach(v.objects, function (obj) {
var Bar = getArraySubclassWithSpeciesConstructor(obj);
var bar = new Bar();
st.equal(ES.IsArray(bar), true, 'Bar instance is an array');
st['throws'](
function () { ES.ArraySpeciesCreate(bar, 3); },
TypeError,
debug(obj) + ' is not a constructor'
);
});
st.end();
});
t.end();
});
test('CreateDataProperty', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.CreateDataProperty(primitive); },
TypeError,
debug(primitive) + ' is not an object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.CreateDataProperty({}, nonPropertyKey); },
TypeError,
debug(nonPropertyKey) + ' is not a property key'
);
});
var sentinel = {};
forEach(v.propertyKeys, function (propertyKey) {
var obj = {};
var status = ES.CreateDataProperty(obj, propertyKey, sentinel);
t.equal(status, true, 'status is true');
t.equal(
obj[propertyKey],
sentinel,
debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object'
);
if (typeof Object.defineProperty === 'function') {
var nonWritable = Object.defineProperty({}, propertyKey, { configurable: true, writable: false });
var nonWritableStatus = ES.CreateDataProperty(nonWritable, propertyKey, sentinel);
t.equal(nonWritableStatus, false, 'create data property failed');
t.notEqual(
nonWritable[propertyKey],
sentinel,
debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonwritable'
);
var nonConfigurable = Object.defineProperty({}, propertyKey, { configurable: false, writable: true });
var nonConfigurableStatus = ES.CreateDataProperty(nonConfigurable, propertyKey, sentinel);
t.equal(nonConfigurableStatus, false, 'create data property failed');
t.notEqual(
nonConfigurable[propertyKey],
sentinel,
debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonconfigurable'
);
}
});
t.end();
});
test('CreateDataPropertyOrThrow', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.CreateDataPropertyOrThrow(primitive); },
TypeError,
debug(primitive) + ' is not an object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.CreateDataPropertyOrThrow({}, nonPropertyKey); },
TypeError,
debug(nonPropertyKey) + ' is not a property key'
);
});
var sentinel = {};
forEach(v.propertyKeys, function (propertyKey) {
var obj = {};
var status = ES.CreateDataPropertyOrThrow(obj, propertyKey, sentinel);
t.equal(status, true, 'status is true');
t.equal(
obj[propertyKey],
sentinel,
debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object'
);
if (typeof Object.preventExtensions === 'function') {
var notExtensible = {};
Object.preventExtensions(notExtensible);
t['throws'](
function () { ES.CreateDataPropertyOrThrow(notExtensible, propertyKey, sentinel); },
TypeError,
'can not install ' + debug(propertyKey) + ' on non-extensible object'
);
t.notEqual(
notExtensible[propertyKey],
sentinel,
debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object'
);
}
});
t.end();
});
test('ObjectCreate', function (t) {
forEach(v.nonNullPrimitives, function (value) {
t['throws'](
function () { ES.ObjectCreate(value); },
TypeError,
debug(value) + ' is not null, or an object'
);
});
t.test('proto arg', function (st) {
var Parent = function Parent() {};
Parent.prototype.foo = {};
var child = ES.ObjectCreate(Parent.prototype);
st.equal(child instanceof Parent, true, 'child is instanceof Parent');
st.equal(child.foo, Parent.prototype.foo, 'child inherits properties from Parent.prototype');
st.end();
});
t.test('internal slots arg', function (st) {
st.doesNotThrow(function () { ES.ObjectCreate(null, []); }, 'an empty slot list is valid');
st['throws'](
function () { ES.ObjectCreate(null, ['a']); },
SyntaxError,
'internal slots are not supported'
);
st.end();
});
t.test('null proto', { skip: !Object.create }, function (st) {
st.equal('toString' in ({}), true, 'normal objects have toString');
st.equal('toString' in ES.ObjectCreate(null), false, 'makes a null object');
st.end();
});
t.test('null proto when no native Object.create', { skip: Object.create }, function (st) {
st['throws'](
function () { ES.ObjectCreate(null); },
SyntaxError,
'without a native Object.create, can not create null objects'
);
st.end();
});
t.end();
});
test('AdvanceStringIndex', function (t) {
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { ES.AdvanceStringIndex(nonString); },
TypeError,
'"S" argument must be a String; ' + debug(nonString) + ' is not'
);
});
var notInts = v.nonNumbers.concat(
v.nonIntegerNumbers,
[Infinity, -Infinity, NaN, [], new Date(), Math.pow(2, 53), -1]
);
forEach(notInts, function (nonInt) {
t['throws'](
function () { ES.AdvanceStringIndex('abc', nonInt); },
TypeError,
'"index" argument must be an integer, ' + debug(nonInt) + ' is not.'
);
});
forEach(v.nonBooleans, function (nonBoolean) {
t['throws'](
function () { ES.AdvanceStringIndex('abc', 0, nonBoolean); },
TypeError,
debug(nonBoolean) + ' is not a Boolean'
);
});
var str = 'a\uD83D\uDCA9c';
t.test('non-unicode mode', function (st) {
for (var i = 0; i < str.length + 2; i += 1) {
st.equal(ES.AdvanceStringIndex(str, i, false), i + 1, i + ' advances to ' + (i + 1));
}
st.end();
});
t.test('unicode mode', function (st) {
st.equal(ES.AdvanceStringIndex(str, 0, true), 1, '0 advances to 1');
st.equal(ES.AdvanceStringIndex(str, 1, true), 3, '1 advances to 3');
st.equal(ES.AdvanceStringIndex(str, 2, true), 3, '2 advances to 3');
st.equal(ES.AdvanceStringIndex(str, 3, true), 4, '3 advances to 4');
st.equal(ES.AdvanceStringIndex(str, 4, true), 5, '4 advances to 5');
st.end();
});
t.test('lone surrogates', function (st) {
var halfPoo = 'a\uD83Dc';
st.equal(ES.AdvanceStringIndex(halfPoo, 0, true), 1, '0 advances to 1');
st.equal(ES.AdvanceStringIndex(halfPoo, 1, true), 2, '1 advances to 2');
st.equal(ES.AdvanceStringIndex(halfPoo, 2, true), 3, '2 advances to 3');
st.equal(ES.AdvanceStringIndex(halfPoo, 3, true), 4, '3 advances to 4');
st.end();
});
t.test('surrogate pairs', function (st) {
var lowestPair = String.fromCharCode('0xD800') + String.fromCharCode('0xDC00');
var highestPair = String.fromCharCode('0xDBFF') + String.fromCharCode('0xDFFF');
var poop = String.fromCharCode('0xD83D') + String.fromCharCode('0xDCA9');
st.equal(ES.AdvanceStringIndex(lowestPair, 0, true), 2, 'lowest surrogate pair, 0 -> 2');
st.equal(ES.AdvanceStringIndex(highestPair, 0, true), 2, 'highest surrogate pair, 0 -> 2');
st.equal(ES.AdvanceStringIndex(poop, 0, true), 2, 'poop, 0 -> 2');
st.end();
});
t.end();
});
test('CreateMethodProperty', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.CreateMethodProperty(primitive, 'key'); },
TypeError,
'O must be an Object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.CreateMethodProperty({}, nonPropertyKey); },
TypeError,
debug(nonPropertyKey) + ' is not a Property Key'
);
});
t.test('defines correctly', function (st) {
var obj = {};
var key = 'the key';
var value = { foo: 'bar' };
st.equal(ES.CreateMethodProperty(obj, key, value), true, 'defines property successfully');
st.test('property descriptor', { skip: !Object.getOwnPropertyDescriptor }, function (s2t) {
s2t.deepEqual(
Object.getOwnPropertyDescriptor(obj, key),
{
configurable: true,
enumerable: false,
value: value,
writable: true
},
'sets the correct property descriptor'
);
s2t.end();
});
st.equal(obj[key], value, 'sets the correct value');
st.end();
});
t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) {
var obj = Object.freeze({ foo: 'bar' });
st['throws'](
function () { ES.CreateMethodProperty(obj, 'foo', { value: 'baz' }); },
TypeError,
'nonconfigurable key can not be defined'
);
st.end();
});
var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor
|| !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable;
t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) {
st['throws'](
function () { ES.CreateMethodProperty(function () {}, 'name', { value: 'baz' }); },
TypeError,
'nonconfigurable function name can not be defined'
);
st.end();
});
t.end();
});
test('DefinePropertyOrThrow', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.DefinePropertyOrThrow(primitive, 'key', {}); },
TypeError,
'O must be an Object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.DefinePropertyOrThrow({}, nonPropertyKey, {}); },
TypeError,
debug(nonPropertyKey) + ' is not a Property Key'
);
});
t.test('defines correctly', function (st) {
var obj = {};
var key = 'the key';
var descriptor = {
configurable: true,
enumerable: false,
value: { foo: 'bar' },
writable: true
};
st.equal(ES.DefinePropertyOrThrow(obj, key, descriptor), true, 'defines property successfully');
st.test('property descriptor', { skip: !Object.getOwnPropertyDescriptor }, function (s2t) {
s2t.deepEqual(
Object.getOwnPropertyDescriptor(obj, key),
descriptor,
'sets the correct property descriptor'
);
s2t.end();
});
st.deepEqual(obj[key], descriptor.value, 'sets the correct value');
st.end();
});
t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) {
var obj = Object.freeze({ foo: 'bar' });
st['throws'](
function () {
ES.DefinePropertyOrThrow(obj, 'foo', { configurable: true, value: 'baz' });
},
TypeError,
'nonconfigurable key can not be defined'
);
st.end();
});
var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor
|| !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable;
t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) {
st['throws'](
function () {
ES.DefinePropertyOrThrow(function () {}, 'name', { configurable: true, value: 'baz' });
},
TypeError,
'nonconfigurable function name can not be defined'
);
st.end();
});
t.end();
});
test('DeletePropertyOrThrow', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.DeletePropertyOrThrow(primitive, 'key', {}); },
TypeError,
'O must be an Object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.DeletePropertyOrThrow({}, nonPropertyKey, {}); },
TypeError,
debug(nonPropertyKey) + ' is not a Property Key'
);
});
t.test('defines correctly', function (st) {
var obj = { 'the key': 42 };
var key = 'the key';
st.equal(ES.DeletePropertyOrThrow(obj, key), true, 'deletes property successfully');
st.equal(key in obj, false, 'key is no longer in the object');
st.end();
});
t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) {
var obj = Object.freeze({ foo: 'bar' });
st['throws'](
function () { ES.DeletePropertyOrThrow(obj, 'foo'); },
TypeError,
'nonconfigurable key can not be deleted'
);
st.end();
});
var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor
|| !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable;
t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) {
st['throws'](
function () { ES.DeletePropertyOrThrow(function () {}, 'name'); },
TypeError,
'nonconfigurable function name can not be deleted'
);
st.end();
});
t.end();
});
test('EnumerableOwnNames', { skip: skips && skips.EnumerableOwnNames }, function (t) {
var obj = testEnumerableOwnNames(t, function (O) { return ES.EnumerableOwnNames(O); });
t.deepEqual(
ES.EnumerableOwnNames(obj),
['own'],
'returns enumerable own names'
);
t.end();
});
test('thisNumberValue', function (t) {
forEach(v.nonNumbers, function (nonNumber) {
t['throws'](
function () { ES.thisNumberValue(nonNumber); },
TypeError,
debug(nonNumber) + ' is not a Number'
);
});
forEach(v.numbers, function (number) {
t.equal(ES.thisNumberValue(number), number, debug(number) + ' is its own thisNumberValue');
var obj = Object(number);
t.equal(ES.thisNumberValue(obj), number, debug(obj) + ' is the boxed thisNumberValue');
});
t.end();
});
test('thisBooleanValue', function (t) {
forEach(v.nonBooleans, function (nonBoolean) {
t['throws'](
function () { ES.thisBooleanValue(nonBoolean); },
TypeError,
debug(nonBoolean) + ' is not a Boolean'
);
});
forEach(v.booleans, function (boolean) {
t.equal(ES.thisBooleanValue(boolean), boolean, debug(boolean) + ' is its own thisBooleanValue');
var obj = Object(boolean);
t.equal(ES.thisBooleanValue(obj), boolean, debug(obj) + ' is the boxed thisBooleanValue');
});
t.end();
});
test('thisStringValue', function (t) {
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { ES.thisStringValue(nonString); },
TypeError,
debug(nonString) + ' is not a String'
);
});
forEach(v.strings, function (string) {
t.equal(ES.thisStringValue(string), string, debug(string) + ' is its own thisStringValue');
var obj = Object(string);
t.equal(ES.thisStringValue(obj), string, debug(obj) + ' is the boxed thisStringValue');
});
t.end();
});
test('thisTimeValue', function (t) {
forEach(v.primitives.concat(v.objects), function (nonDate) {
t['throws'](
function () { ES.thisTimeValue(nonDate); },
TypeError,
debug(nonDate) + ' is not a Date'
);
});
forEach(v.timestamps, function (timestamp) {
var date = new Date(timestamp);
t.equal(ES.thisTimeValue(date), timestamp, debug(date) + ' is its own thisTimeValue');
});
t.end();
});
test('SetIntegrityLevel', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.SetIntegrityLevel(primitive); },
TypeError,
debug(primitive) + ' is not an Object'
);
});
t['throws'](
function () { ES.SetIntegrityLevel({}); },
/^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/,
'`level` must be `"sealed"` or `"frozen"`'
);
var O = { a: 1 };
t.equal(ES.SetIntegrityLevel(O, 'sealed'), true);
t['throws'](
function () { O.b = 2; },
/^TypeError: (Cannot|Can't) add property b, object is not extensible$/,
'sealing prevent new properties from being added'
);
O.a = 2;
t.equal(O.a, 2, 'pre-frozen, existing properties are mutable');
t.equal(ES.SetIntegrityLevel(O, 'frozen'), true);
t['throws'](
function () { O.a = 3; },
/^TypeError: Cannot assign to read only property 'a' of /,
'freezing prevents existing properties from being mutated'
);
t.end();
});
test('TestIntegrityLevel', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.TestIntegrityLevel(primitive); },
TypeError,
debug(primitive) + ' is not an Object'
);
});
t['throws'](
function () { ES.TestIntegrityLevel({ a: 1 }); },
/^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/,
'`level` must be `"sealed"` or `"frozen"`'
);
t.equal(ES.TestIntegrityLevel({ a: 1 }, 'sealed'), false, 'basic object is not sealed');
t.equal(ES.TestIntegrityLevel({ a: 1 }, 'frozen'), false, 'basic object is not frozen');
t.test('preventExtensions', { skip: !Object.preventExtensions }, function (st) {
var o = Object.preventExtensions({ a: 1 });
st.equal(ES.TestIntegrityLevel(o, 'sealed'), false, 'nonextensible object is not sealed');
st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'nonextensible object is not frozen');
var empty = Object.preventExtensions({});
st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty nonextensible object is sealed');
st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty nonextensible object is frozen');
st.end();
});
t.test('seal', { skip: !Object.seal }, function (st) {
var o = Object.seal({ a: 1 });
st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'sealed object is sealed');
st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'sealed object is not frozen');
var empty = Object.seal({});
st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty sealed object is sealed');
st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty sealed object is frozen');
st.end();
});
t.test('freeze', { skip: !Object.freeze }, function (st) {
var o = Object.freeze({ a: 1 });
st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'frozen object is sealed');
st.equal(ES.TestIntegrityLevel(o, 'frozen'), true, 'frozen object is frozen');
var empty = Object.freeze({});
st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty frozen object is sealed');
st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty frozen object is frozen');
st.end();
});
t.end();
});
test('OrdinaryHasInstance', function (t) {
forEach(v.nonFunctions, function (nonFunction) {
t.equal(ES.OrdinaryHasInstance(nonFunction, {}), false, debug(nonFunction) + ' is not callable');
});
forEach(v.primitives, function (primitive) {
t.equal(ES.OrdinaryHasInstance(function () {}, primitive), false, debug(primitive) + ' is not an object');
});
var C = function C() {};
var D = function D() {};
t.equal(ES.OrdinaryHasInstance(C, new C()), true, 'constructor function has an instance of itself');
t.equal(ES.OrdinaryHasInstance(C, new D()), false, 'constructor/instance mismatch is false');
t.equal(ES.OrdinaryHasInstance(D, new C()), false, 'instance/constructor mismatch is false');
t.equal(ES.OrdinaryHasInstance(C, {}), false, 'plain object is not an instance of a constructor');
t.equal(ES.OrdinaryHasInstance(Object, {}), true, 'plain object is an instance of Object');
t.end();
});
test('OrdinaryHasProperty', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.OrdinaryHasProperty(primitive, ''); },
TypeError,
debug(primitive) + ' is not an object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.OrdinaryHasProperty({}, nonPropertyKey); },
TypeError,
'P: ' + debug(nonPropertyKey) + ' is not a Property Key'
);
});
t.equal(ES.OrdinaryHasProperty({ a: 1 }, 'a'), true, 'own property is true');
t.equal(ES.OrdinaryHasProperty({}, 'toString'), true, 'inherited property is true');
t.equal(ES.OrdinaryHasProperty({}, 'nope'), false, 'absent property is false');
t.end();
});
test('InstanceofOperator', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.InstanceofOperator(primitive, function () {}); },
TypeError,
debug(primitive) + ' is not an object'
);
});
forEach(v.nonFunctions, function (nonFunction) {
t['throws'](
function () { ES.InstanceofOperator({}, nonFunction); },
TypeError,
debug(nonFunction) + ' is not callable'
);
});
var C = function C() {};
var D = function D() {};
t.equal(ES.InstanceofOperator(new C(), C), true, 'constructor function has an instance of itself');
t.equal(ES.InstanceofOperator(new D(), C), false, 'constructor/instance mismatch is false');
t.equal(ES.InstanceofOperator(new C(), D), false, 'instance/constructor mismatch is false');
t.equal(ES.InstanceofOperator({}, C), false, 'plain object is not an instance of a constructor');
t.equal(ES.InstanceofOperator({}, Object), true, 'plain object is an instance of Object');
t.test('Symbol.hasInstance', { skip: !v.hasSymbols || !Symbol.hasInstance }, function (st) {
st.plan(4);
var O = {};
var C2 = function () {};
st.equal(ES.InstanceofOperator(O, C2), false, 'O is not an instance of C2');
Object.defineProperty(C2, Symbol.hasInstance, {
value: function (obj) {
st.equal(this, C2, 'hasInstance receiver is C2');
st.equal(obj, O, 'hasInstance argument is O');
return {}; // testing coercion to boolean
}
});
st.equal(ES.InstanceofOperator(O, C2), true, 'O is now an instance of C2');
st.end();
});
t.end();
});
test('Abstract Equality Comparison', function (t) {
t.test('same types use ===', function (st) {
forEach(v.primitives.concat(v.objects), function (value) {
st.equal(ES['Abstract Equality Comparison'](value, value), value === value, debug(value) + ' is abstractly equal to itself');
});
st.end();
});
t.test('different types coerce', function (st) {
var pairs = [
[null, undefined],
[3, '3'],
[true, '3'],
[true, 3],
[false, 0],
[false, '0'],
[3, [3]],
['3', [3]],
[true, [1]],
[false, [0]],
[String(v.coercibleObject), v.coercibleObject],
[Number(String(v.coercibleObject)), v.coercibleObject],
[Number(v.coercibleObject), v.coercibleObject],
[String(Number(v.coercibleObject)), v.coercibleObject]
];
forEach(pairs, function (pair) {
var a = pair[0];
var b = pair[1];
// eslint-disable-next-line eqeqeq
st.equal(ES['Abstract Equality Comparison'](a, b), a == b, debug(a) + ' == ' + debug(b));
// eslint-disable-next-line eqeqeq
st.equal(ES['Abstract Equality Comparison'](b, a), b == a, debug(b) + ' == ' + debug(a));
});
st.end();
});
t.end();
});
test('Strict Equality Comparison', function (t) {
t.test('same types use ===', function (st) {
forEach(v.primitives.concat(v.objects), function (value) {
st.equal(ES['Strict Equality Comparison'](value, value), value === value, debug(value) + ' is strictly equal to itself');
});
st.end();
});
t.test('different types are not ===', function (st) {
var pairs = [
[null, undefined],
[3, '3'],
[true, '3'],
[true, 3],
[false, 0],
[false, '0'],
[3, [3]],
['3', [3]],
[true, [1]],
[false, [0]],
[String(v.coercibleObject), v.coercibleObject],
[Number(String(v.coercibleObject)), v.coercibleObject],
[Number(v.coercibleObject), v.coercibleObject],
[String(Number(v.coercibleObject)), v.coercibleObject]
];
forEach(pairs, function (pair) {
var a = pair[0];
var b = pair[1];
st.equal(ES['Strict Equality Comparison'](a, b), a === b, debug(a) + ' === ' + debug(b));
st.equal(ES['Strict Equality Comparison'](b, a), b === a, debug(b) + ' === ' + debug(a));
});
st.end();
});
t.end();
});
test('Abstract Relational Comparison', function (t) {
t.test('at least one operand is NaN', function (st) {
st.equal(ES['Abstract Relational Comparison'](NaN, {}, true), undefined, 'LeftFirst: first is NaN, returns undefined');
st.equal(ES['Abstract Relational Comparison']({}, NaN, true), undefined, 'LeftFirst: second is NaN, returns undefined');
st.equal(ES['Abstract Relational Comparison'](NaN, {}, false), undefined, '!LeftFirst: first is NaN, returns undefined');
st.equal(ES['Abstract Relational Comparison']({}, NaN, false), undefined, '!LeftFirst: second is NaN, returns undefined');
st.end();
});
t.equal(ES['Abstract Relational Comparison'](3, 4, true), true, 'LeftFirst: 3 is less than 4');
t.equal(ES['Abstract Relational Comparison'](4, 3, true), false, 'LeftFirst: 3 is not less than 4');
t.equal(ES['Abstract Relational Comparison'](3, 4, false), true, '!LeftFirst: 3 is less than 4');
t.equal(ES['Abstract Relational Comparison'](4, 3, false), false, '!LeftFirst: 3 is not less than 4');
t.equal(ES['Abstract Relational Comparison']('3', '4', true), true, 'LeftFirst: "3" is less than "4"');
t.equal(ES['Abstract Relational Comparison']('4', '3', true), false, 'LeftFirst: "3" is not less than "4"');
t.equal(ES['Abstract Relational Comparison']('3', '4', false), true, '!LeftFirst: "3" is less than "4"');
t.equal(ES['Abstract Relational Comparison']('4', '3', false), false, '!LeftFirst: "3" is not less than "4"');
t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, true), true, 'LeftFirst: coercible object is less than 42');
t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, true), false, 'LeftFirst: 42 is not less than coercible object');
t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, false), true, '!LeftFirst: coercible object is less than 42');
t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, false), false, '!LeftFirst: 42 is not less than coercible object');
t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', true), false, 'LeftFirst: coercible object is not less than "3"');
t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, true), false, 'LeftFirst: "3" is not less than coercible object');
t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', false), false, '!LeftFirst: coercible object is not less than "3"');
t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, false), false, '!LeftFirst: "3" is not less than coercible object');
t.end();
});
test('ValidateAndApplyPropertyDescriptor', function (t) {
forEach(v.nonUndefinedPrimitives, function (nonUndefinedPrimitive) {
t['throws'](
function () { ES.ValidateAndApplyPropertyDescriptor(nonUndefinedPrimitive, '', false, v.genericDescriptor(), v.genericDescriptor()); },
TypeError,
'O: ' + debug(nonUndefinedPrimitive) + ' is not undefined or an Object'
);
});
forEach(v.nonBooleans, function (nonBoolean) {
t['throws'](
function () {
return ES.ValidateAndApplyPropertyDescriptor(
undefined,
null,
nonBoolean,
v.genericDescriptor(),
v.genericDescriptor()
);
},
TypeError,
'extensible: ' + debug(nonBoolean) + ' is not a Boolean'
);
});
forEach(v.primitives, function (primitive) {
// Desc must be a Property Descriptor
t['throws'](
function () {
return ES.ValidateAndApplyPropertyDescriptor(
undefined,
null,
false,
primitive,
v.genericDescriptor()
);
},
TypeError,
'Desc: ' + debug(primitive) + ' is not a Property Descriptor'
);
});
forEach(v.nonUndefinedPrimitives, function (primitive) {
// current must be undefined or a Property Descriptor
t['throws'](
function () {
return ES.ValidateAndApplyPropertyDescriptor(
undefined,
null,
false,
v.genericDescriptor(),
primitive
);
},
TypeError,
'current: ' + debug(primitive) + ' is not a Property Descriptor or undefined'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
// if O is an object, P must be a property key
t['throws'](
function () {
return ES.ValidateAndApplyPropertyDescriptor(
{},
nonPropertyKey,
false,
v.genericDescriptor(),
v.genericDescriptor()
);
},
TypeError,
'P: ' + debug(nonPropertyKey) + ' is not a Property Key'
);
});
t.test('current is undefined', function (st) {
var propertyKey = 'howdy';
st.test('generic descriptor', function (s2t) {
var generic = v.genericDescriptor();
generic['[[Enumerable]]'] = true;
var O = {};
ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, generic);
s2t.equal(
ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, generic),
false,
'when extensible is false, nothing happens'
);
s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false');
s2t.equal(
ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, generic),
true,
'operation is successful'
);
var expected = {};
expected[propertyKey] = undefined;
s2t.deepEqual(O, expected, 'generic descriptor has been defined as an own data property');
s2t.end();
});
st.test('data descriptor', function (s2t) {
var data = v.dataDescriptor();
data['[[Enumerable]]'] = true;
var O = {};
ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, data);
s2t.equal(
ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, data),
false,
'when extensible is false, nothing happens'
);
s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false');
s2t.equal(
ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, data),
true,
'operation is successful'
);
var expected = {};
expected[propertyKey] = data['[[Value]]'];
s2t.deepEqual(O, expected, 'data descriptor has been defined as an own data property');
s2t.end();
});
st.test('accessor descriptor', function (s2t) {
var count = 0;
var accessor = v.accessorDescriptor();
accessor['[[Enumerable]]'] = true;
accessor['[[Get]]'] = function () {
count += 1;
return count;
};
var O = {};
ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, accessor);
s2t.equal(
ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, accessor),
false,
'when extensible is false, nothing happens'
);
s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false');
s2t.equal(
ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, accessor),
true,
'operation is successful'
);
var expected = {};
expected[propertyKey] = accessor['[[Get]]']() + 1;
s2t.deepEqual(O, expected, 'accessor descriptor has been defined as an own accessor property');
s2t.end();
});
st.end();
});
t.test('every field in Desc is absent', { skip: 'it is unclear if having no fields qualifies Desc to be a Property Descriptor' });
forEach([v.dataDescriptor, v.accessorDescriptor, v.mutatorDescriptor], function (getDescriptor) {
t.equal(
ES.ValidateAndApplyPropertyDescriptor(undefined, 'property key', true, getDescriptor(), getDescriptor()),
true,
'when Desc and current are the same, early return true'
);
});
t.test('current is nonconfigurable', function (st) {
// note: these must not be generic descriptors, or else the algorithm returns an early true
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.descriptors.configurable(v.dataDescriptor()),
v.descriptors.nonConfigurable(v.dataDescriptor())
),
false,
'false if Desc is configurable'
);
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.descriptors.enumerable(v.dataDescriptor()),
v.descriptors.nonEnumerable(v.dataDescriptor())
),
false,
'false if Desc is Enumerable and current is not'
);
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.descriptors.nonEnumerable(v.dataDescriptor()),
v.descriptors.enumerable(v.dataDescriptor())
),
false,
'false if Desc is not Enumerable and current is'
);
var descLackingEnumerable = v.accessorDescriptor();
delete descLackingEnumerable['[[Enumerable]]'];
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
descLackingEnumerable,
v.descriptors.enumerable(v.accessorDescriptor())
),
true,
'not false if Desc lacks Enumerable'
);
st.end();
});
t.test('Desc and current: one is a data descriptor, one is not', { skip: !Object.defineProperty }, function (st) {
// note: Desc must be configurable if current is nonconfigurable, to hit this branch
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.descriptors.configurable(v.accessorDescriptor()),
v.descriptors.nonConfigurable(v.dataDescriptor())
),
false,
'false if current (data) is nonconfigurable'
);
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.descriptors.configurable(v.dataDescriptor()),
v.descriptors.nonConfigurable(v.accessorDescriptor())
),
false,
'false if current (not data) is nonconfigurable'
);
// one is data and one is not,
// // if current is data, convert to accessor
// // else convert to data
var startsWithData = {
'property key': 42
};
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
startsWithData,
'property key',
true,
v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor())),
v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor()))
),
true,
'operation is successful: current is data, Desc is accessor'
);
var shouldBeAccessor = Object.getOwnPropertyDescriptor(startsWithData, 'property key');
st.equal(typeof shouldBeAccessor.get, 'function', 'has a getter');
var key = 'property key';
var startsWithAccessor = {};
Object.defineProperty(startsWithAccessor, key, {
configurable: true,
enumerable: true,
get: function get() { return 42; }
});
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
startsWithAccessor,
key,
true,
v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor())),
v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor(42)))
),
true,
'operation is successful: current is accessor, Desc is data'
);
var shouldBeData = Object.getOwnPropertyDescriptor(startsWithAccessor, 'property key');
st.deepEqual(shouldBeData, { configurable: true, enumerable: true, value: 42, writable: false }, 'is a data property');
st.end();
});
t.test('Desc and current are both data descriptors', function (st) {
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.descriptors.writable(v.dataDescriptor()),
v.descriptors.nonWritable(v.descriptors.nonConfigurable(v.dataDescriptor()))
),
false,
'false if frozen current and writable Desc'
);
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.descriptors.configurable({ '[[Value]]': 42 }),
v.descriptors.nonWritable({ '[[Value]]': 7 })
),
false,
'false if nonwritable current has a different value than Desc'
);
st.end();
});
t.test('current is nonconfigurable; Desc and current are both accessor descriptors', function (st) {
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.mutatorDescriptor(),
v.descriptors.nonConfigurable(v.mutatorDescriptor())
),
false,
'false if both Sets are not equal'
);
st.equal(
ES.ValidateAndApplyPropertyDescriptor(
undefined,
'property key',
true,
v.accessorDescriptor(),
v.descriptors.nonConfigurable(v.accessorDescriptor())
),
false,
'false if both Gets are not equal'
);
st.end();
});
t.end();
});
test('OrdinaryGetOwnProperty', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.OrdinaryGetOwnProperty(primitive, ''); },
TypeError,
'O: ' + debug(primitive) + ' is not an Object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.OrdinaryGetOwnProperty({}, nonPropertyKey); },
TypeError,
'P: ' + debug(nonPropertyKey) + ' is not a Property Key'
);
});
t.equal(ES.OrdinaryGetOwnProperty({}, 'not in the object'), undefined, 'missing property yields undefined');
t.equal(ES.OrdinaryGetOwnProperty({}, 'toString'), undefined, 'inherited non-own property yields undefined');
t.deepEqual(
ES.OrdinaryGetOwnProperty({ a: 1 }, 'a'),
ES.ToPropertyDescriptor({
configurable: true,
enumerable: true,
value: 1,
writable: true
}),
'own assigned data property yields expected descriptor'
);
t.deepEqual(
ES.OrdinaryGetOwnProperty(/a/, 'lastIndex'),
ES.ToPropertyDescriptor({
configurable: false,
enumerable: false,
value: 0,
writable: true
}),
'regex lastIndex yields expected descriptor'
);
t.deepEqual(
ES.OrdinaryGetOwnProperty([], 'length'),
ES.ToPropertyDescriptor({
configurable: false,
enumerable: false,
value: 0,
writable: true
}),
'array length yields expected descriptor'
);
t.deepEqual(
ES.OrdinaryGetOwnProperty(Object.prototype, 'toString'),
ES.ToPropertyDescriptor({
configurable: true,
enumerable: false,
value: Object.prototype.toString,
writable: true
}),
'own non-enumerable data property yields expected descriptor'
);
t.test('ES5+', { skip: !Object.defineProperty }, function (st) {
var O = {};
Object.defineProperty(O, 'foo', {
configurable: false,
enumerable: false,
value: O,
writable: true
});
t.deepEqual(
ES.OrdinaryGetOwnProperty(O, 'foo'),
ES.ToPropertyDescriptor({
configurable: false,
enumerable: false,
value: O,
writable: true
}),
'defined own property yields expected descriptor'
);
st.end();
});
t.end();
});
test('OrdinaryDefineOwnProperty', { skip: !Object.defineProperty }, function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.CopyDataProperties(primitive, {}, []); },
TypeError,
'O: ' + debug(primitive) + ' is not an Object'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
t['throws'](
function () { ES.OrdinaryDefineOwnProperty({}, nonPropertyKey, v.genericDescriptor()); },
TypeError,
'P: ' + debug(nonPropertyKey) + ' is not a Property Key'
);
});
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.OrdinaryDefineOwnProperty(primitive, '', v.genericDescriptor()); },
TypeError,
'Desc: ' + debug(primitive) + ' is not a Property Descriptor'
);
});
var O = {};
var P = 'property key';
var Desc = v.accessorDescriptor();
t.equal(
ES.OrdinaryDefineOwnProperty(O, P, Desc),
true,
'operation is successful'
);
t.deepEqual(
Object.getOwnPropertyDescriptor(O, P),
ES.FromPropertyDescriptor(ES.CompletePropertyDescriptor(Desc)),
'expected property descriptor is defined'
);
t.end();
});
test('ArrayCreate', function (t) {
forEach(v.nonIntegerNumbers.concat([-1]), function (nonIntegerNumber) {
t['throws'](
function () { ES.ArrayCreate(nonIntegerNumber); },
TypeError,
'length must be an integer number >= 0'
);
});
t['throws'](
function () { ES.ArrayCreate(Math.pow(2, 32)); },
RangeError,
'length must be < 2**32'
);
t.deepEqual(ES.ArrayCreate(-0), [], 'length of -0 creates an empty array');
t.deepEqual(ES.ArrayCreate(0), [], 'length of +0 creates an empty array');
// eslint-disable-next-line no-sparse-arrays, comma-spacing
t.deepEqual(ES.ArrayCreate(1), [,], 'length of 1 creates a sparse array of length 1');
// eslint-disable-next-line no-sparse-arrays, comma-spacing
t.deepEqual(ES.ArrayCreate(2), [,,], 'length of 2 creates a sparse array of length 2');
// eslint-disable-next-line no-proto
t.test('proto argument', { skip: [].__proto__ !== Array.prototype }, function (st) {
var fakeProto = {
push: { toString: function () { return 'not array push'; } }
};
st.equal(ES.ArrayCreate(0, fakeProto).push, fakeProto.push, 'passing the proto argument works');
st.end();
});
t.end();
});
test('ArraySetLength', function (t) {
forEach(v.primitives.concat(v.objects), function (nonArray) {
t['throws'](
function () { ES.ArraySetLength(nonArray, 0); },
TypeError,
'A: ' + debug(nonArray) + ' is not an Array'
);
});
forEach(v.nonUndefinedPrimitives, function (primitive) {
t['throws'](
function () { ES.ArraySetLength([], primitive); },
TypeError,
'Desc: ' + debug(primitive) + ' is not a Property Descriptor'
);
});
t.test('making length nonwritable', { skip: !Object.defineProperty }, function (st) {
var a = [];
ES.ArraySetLength(a, { '[[Writable]]': false });
st.deepEqual(
Object.getOwnPropertyDescriptor(a, 'length'),
{
configurable: false,
enumerable: false,
value: 0,
writable: false
},
'without a value, length becomes nonwritable'
);
st.end();
});
var arr = [];
ES.ArraySetLength(arr, { '[[Value]]': 7 });
t.equal(arr.length, 7, 'array now has a length of 7');
t.end();
});
test('CreateHTML', function (t) {
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { ES.CreateHTML('', nonString, '', ''); },
TypeError,
'tag: ' + debug(nonString) + ' is not a String'
);
t['throws'](
function () { ES.CreateHTML('', '', nonString, ''); },
TypeError,
'attribute: ' + debug(nonString) + ' is not a String'
);
});
t.equal(
ES.CreateHTML(
{ toString: function () { return 'the string'; } },
'some HTML tag!',
''
),
'<some HTML tag!>the string</some HTML tag!>',
'works with an empty string attribute value'
);
t.equal(
ES.CreateHTML(
{ toString: function () { return 'the string'; } },
'some HTML tag!',
'attr',
'value "with quotes"'
),
'<some HTML tag! attr="value "with quotes"">the string</some HTML tag!>',
'works with an attribute, and a value with quotes'
);
t.end();
});
test('GetOwnPropertyKeys', function (t) {
forEach(v.primitives, function (primitive) {
t['throws'](
function () { ES.GetOwnPropertyKeys(primitive, 'String'); },
TypeError,
'O: ' + debug(primitive) + ' is not an Object'
);
});
t['throws'](
function () { ES.GetOwnPropertyKeys({}, 'not string or symbol'); },
TypeError,
'Type: must be "String" or "Symbol"'
);
t.test('Symbols', { skip: !v.hasSymbols }, function (st) {
var O = { a: 1 };
O[Symbol.iterator] = true;
var s = Symbol('test');
Object.defineProperty(O, s, { enumerable: false, value: true });
st.deepEqual(
ES.GetOwnPropertyKeys(O, 'Symbol'),
[Symbol.iterator, s],
'works with Symbols, enumerable or not'
);
st.end();
});
t.test('non-enumerable names', { skip: !Object.defineProperty }, function (st) {
var O = { a: 1 };
Object.defineProperty(O, 'b', { enumerable: false, value: 2 });
if (v.hasSymbols) {
O[Symbol.iterator] = true;
}
st.deepEqual(
ES.GetOwnPropertyKeys(O, 'String').sort(),
['a', 'b'].sort(),
'works with Strings, enumerable or not'
);
st.end();
});
t.deepEqual(
ES.GetOwnPropertyKeys({ a: 1, b: 2 }, 'String').sort(),
['a', 'b'].sort(),
'works with enumerable keys'
);
t.end();
});
test('SymbolDescriptiveString', function (t) {
forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) {
t['throws'](
function () { ES.SymbolDescriptiveString(nonSymbol); },
TypeError,
debug(nonSymbol) + ' is not a Symbol'
);
});
t.test('Symbols', { skip: !v.hasSymbols }, function (st) {
st.equal(ES.SymbolDescriptiveString(Symbol()), 'Symbol()', 'undefined description');
st.equal(ES.SymbolDescriptiveString(Symbol('')), 'Symbol()', 'empty string description');
st.equal(ES.SymbolDescriptiveString(Symbol.iterator), 'Symbol(Symbol.iterator)', 'well-known symbol');
st.equal(ES.SymbolDescriptiveString(Symbol('foo')), 'Symbol(foo)', 'string description');
st.end();
});
t.end();
});
test('GetSubstitution', { skip: skips && skips.GetSubstitution }, function (t) {
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { ES.GetSubstitution(nonString, '', 0, [], ''); },
TypeError,
'`matched`: ' + debug(nonString) + ' is not a String'
);
t['throws'](
function () { ES.GetSubstitution('', nonString, 0, [], ''); },
TypeError,
'`str`: ' + debug(nonString) + ' is not a String'
);
t['throws'](
function () { ES.GetSubstitution('', '', 0, [], nonString); },
TypeError,
'`replacement`: ' + debug(nonString) + ' is not a String'
);
t['throws'](
function () { ES.GetSubstitution('', '', 0, [nonString], ''); },
TypeError,
'`captures`: ' + debug([nonString]) + ' is not an Array of strings'
);
});
forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) {
t['throws'](
function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], ''); },
TypeError,
'`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer'
);
});
forEach(v.nonArrays, function (nonArray) {
t['throws'](
function () { ES.GetSubstitution('', '', 0, nonArray, ''); },
TypeError,
'`captures`: ' + debug(nonArray) + ' is not an Array'
);
});
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 3, [], '123'),
'123',
'returns the substitution'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '$$2$'),
'$2$',
'supports $$, and trailing $'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$&<'),
'>abcdef<',
'supports $&'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$`<'),
'><',
'supports $` at position 0'
);
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 3, [], '>$`<'),
'>ab<',
'supports $` at position > 0'
);
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 7, [], ">$'<"),
'><',
"supports $' at a position where there's less than `matched.length` chars left"
);
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 3, [], ">$'<"),
'>ghi<',
"supports $' at a position where there's more than `matched.length` chars left"
);
for (var i = 0; i < 100; i += 1) {
var captures = [];
captures[i] = 'test';
if (i > 0) {
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i + '<'),
'>undefined<',
'supports $' + i + ' with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i),
'>undefined',
'supports $' + i + ' at the end of the replacement, with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i + '<'),
'><',
'supports $' + i + ' with a capture at that index'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i),
'>',
'supports $' + i + ' at the end of the replacement, with a capture at that index'
);
}
if (i < 10) {
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i + '<'),
i === 0 ? '><' : '>undefined<',
'supports $0' + i + ' with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i),
i === 0 ? '>' : '>undefined',
'supports $0' + i + ' at the end of the replacement, with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i + '<'),
'><',
'supports $0' + i + ' with a capture at that index'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i),
'>',
'supports $0' + i + ' at the end of the replacement, with a capture at that index'
);
}
}
t.end();
});
};
var es2016 = function ES2016(ES, ops, expectedMissing, skips) {
es2015(ES, ops, expectedMissing, skips);
test('SameValueNonNumber', function (t) {
var willThrow = [
[3, 4],
[NaN, 4],
[4, ''],
['abc', true],
[{}, false]
];
forEach(willThrow, function (nums) {
t['throws'](function () { return ES.SameValueNonNumber.apply(ES, nums); }, TypeError, 'value must be same type and non-number');
});
forEach(v.objects.concat(v.nonNumberPrimitives), function (val) {
t.equal(val === val, ES.SameValueNonNumber(val, val), debug(val) + ' is SameValueNonNumber to itself');
});
t.end();
});
test('IterableToArrayLike', { skip: skips && skips.IterableToArrayLike }, function (t) {
t.test('custom iterables', { skip: !v.hasSymbols }, function (st) {
var O = {};
O[Symbol.iterator] = function () {
var i = -1;
return {
next: function () {
i += 1;
return {
done: i >= 5,
value: i
};
}
};
};
st.deepEqual(
ES.IterableToArrayLike(O),
[0, 1, 2, 3, 4],
'Symbol.iterator method is called and values collected'
);
st.end();
});
t.deepEqual(ES.IterableToArrayLike('abc'), ['a', 'b', 'c'], 'a string of code units spreads');
t.deepEqual(ES.IterableToArrayLike('💩'), ['💩'], 'a string of code points spreads');
t.deepEqual(ES.IterableToArrayLike('a💩c'), ['a', '💩', 'c'], 'a string of code points and units spreads');
var arr = [1, 2, 3];
t.deepEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a similar array');
t.notEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a different, but similar, array');
var O = {};
t.equal(ES.IterableToArrayLike(O), O, 'a non-iterable non-array non-string object is returned directly');
t.end();
});
};
var es2017 = function ES2017(ES, ops, expectedMissing, skips) {
es2016(ES, ops, expectedMissing, assign({}, skips, {
EnumerableOwnNames: true,
IterableToArrayLike: true
}));
test('ToIndex', function (t) {
t.ok(is(ES.ToIndex(), 0), 'no value gives 0');
t.ok(is(ES.ToIndex(undefined), 0), 'undefined value gives 0');
t['throws'](function () { ES.ToIndex(-1); }, RangeError, 'negative numbers throw');
t['throws'](function () { ES.ToIndex(MAX_SAFE_INTEGER + 1); }, RangeError, 'too large numbers throw');
t.equal(ES.ToIndex(3), 3, 'numbers work');
t.equal(ES.ToIndex(v.valueOfOnlyObject), 4, 'coercible objects are coerced');
t.end();
});
test('EnumerableOwnProperties', { skip: skips && skips.EnumerableOwnProperties }, function (t) {
var obj = testEnumerableOwnNames(t, function (O) {
return ES.EnumerableOwnProperties(O, 'key');
});
t.deepEqual(
ES.EnumerableOwnProperties(obj, 'value'),
[obj.own],
'returns enumerable own values'
);
t.deepEqual(
ES.EnumerableOwnProperties(obj, 'key+value'),
[['own', obj.own]],
'returns enumerable own entries'
);
t.end();
});
test('IterableToList', function (t) {
var customIterator = function () {
var i = -1;
return {
next: function () {
i += 1;
return {
done: i >= 5,
value: i
};
}
};
};
t.deepEqual(
ES.IterableToList({}, customIterator),
[0, 1, 2, 3, 4],
'iterator method is called and values collected'
);
t.test('Symbol support', { skip: !v.hasSymbols }, function (st) {
st.deepEqual(ES.IterableToList('abc', String.prototype[Symbol.iterator]), ['a', 'b', 'c'], 'a string of code units spreads');
st.deepEqual(ES.IterableToList('☃', String.prototype[Symbol.iterator]), ['☃'], 'a string of code points spreads');
var arr = [1, 2, 3];
st.deepEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a similar array');
st.notEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a different, but similar, array');
st.end();
});
t['throws'](
function () { ES.IterableToList({}, void 0); },
TypeError,
'non-function iterator method'
);
t.end();
});
};
var es2018 = function ES2018(ES, ops, expectedMissing, skips) {
es2017(ES, ops, expectedMissing, assign({}, skips, {
EnumerableOwnProperties: true,
GetSubstitution: true,
IsPropertyDescriptor: true
}));
test('thisSymbolValue', function (t) {
forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) {
t['throws'](
function () { ES.thisSymbolValue(nonSymbol); },
v.hasSymbols ? TypeError : SyntaxError,
debug(nonSymbol) + ' is not a Symbol'
);
});
t.test('no native Symbols', { skip: v.hasSymbols }, function (st) {
forEach(v.objects.concat(v.primitives), function (value) {
st['throws'](
function () { ES.thisSymbolValue(value); },
SyntaxError,
'Symbols are not supported'
);
});
st.end();
});
t.test('symbol values', { skip: !v.hasSymbols }, function (st) {
forEach(v.symbols, function (symbol) {
st.equal(ES.thisSymbolValue(symbol), symbol, 'Symbol value of ' + debug(symbol) + ' is same symbol');
st.equal(
ES.thisSymbolValue(Object(symbol)),
symbol,
'Symbol value of ' + debug(Object(symbol)) + ' is ' + debug(symbol)
);
});
st.end();
});
t.end();
});
test('IsStringPrefix', function (t) {
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { ES.IsStringPrefix(nonString, 'a'); },
TypeError,
'first arg: ' + debug(nonString) + ' is not a string'
);
t['throws'](
function () { ES.IsStringPrefix('a', nonString); },
TypeError,
'second arg: ' + debug(nonString) + ' is not a string'
);
});
forEach(v.strings, function (string) {
t.equal(ES.IsStringPrefix(string, string), true, debug(string) + ' is a prefix of itself');
t.equal(ES.IsStringPrefix('', string), true, 'the empty string is a prefix of everything');
});
t.equal(ES.IsStringPrefix('abc', 'abcd'), true, '"abc" is a prefix of "abcd"');
t.equal(ES.IsStringPrefix('abcd', 'abc'), false, '"abcd" is not a prefix of "abc"');
t.equal(ES.IsStringPrefix('a', 'bc'), false, '"a" is not a prefix of "bc"');
t.end();
});
test('NumberToString', function (t) {
forEach(v.nonNumbers, function (nonNumber) {
t['throws'](
function () { ES.NumberToString(nonNumber); },
TypeError,
debug(nonNumber) + ' is not a Number'
);
});
forEach(v.numbers, function (number) {
t.equal(ES.NumberToString(number), String(number), debug(number) + ' stringifies to ' + number);
});
t.end();
});
test('CopyDataProperties', function (t) {
t.test('first argument: target', function (st) {
forEach(v.primitives, function (primitive) {
st['throws'](
function () { ES.CopyDataProperties(primitive, {}, []); },
TypeError,
debug(primitive) + ' is not an Object'
);
});
st.end();
});
t.test('second argument: source', function (st) {
var frozenTarget = Object.freeze ? Object.freeze({}) : {};
forEach(v.nullPrimitives, function (nullish) {
st.equal(
ES.CopyDataProperties(frozenTarget, nullish, []),
frozenTarget,
debug(nullish) + ' "source" yields identical, unmodified target'
);
});
forEach(v.nonNullPrimitives, function (objectCoercible) {
var target = {};
var result = ES.CopyDataProperties(target, objectCoercible, []);
st.equal(result, target, 'result === target');
st.deepEqual(keys(result), keys(Object(objectCoercible)), 'target ends up with keys of ' + debug(objectCoercible));
});
st.end();
});
t.test('third argument: excludedItems', function (st) {
forEach(v.objects.concat(v.primitives), function (nonArray) {
st['throws'](
function () { ES.CopyDataProperties({}, {}, nonArray); },
TypeError,
debug(nonArray) + ' is not an Array'
);
});
forEach(v.nonPropertyKeys, function (nonPropertyKey) {
st['throws'](
function () { ES.CopyDataProperties({}, {}, [nonPropertyKey]); },
TypeError,
debug(nonPropertyKey) + ' is not a Property Key'
);
});
var result = ES.CopyDataProperties({}, { a: 1, b: 2, c: 3 }, ['b']);
st.deepEqual(keys(result), ['a', 'c'], 'excluded string keys are excluded');
st.test('excluding symbols', { skip: !v.hasSymbols }, function (s2t) {
var source = {};
forEach(v.symbols, function (symbol) {
source[symbol] = true;
});
var includedSymbols = v.symbols.slice(1);
var excludedSymbols = v.symbols.slice(0, 1);
var target = ES.CopyDataProperties({}, source, excludedSymbols);
forEach(includedSymbols, function (symbol) {
s2t.equal(has(target, symbol), true, debug(symbol) + ' is included');
});
forEach(excludedSymbols, function (symbol) {
s2t.equal(has(target, symbol), false, debug(symbol) + ' is excluded');
});
s2t.end();
});
st.end();
});
t.end();
});
test('PromiseResolve', function (t) {
t.test('Promises unsupported', { skip: typeof Promise === 'function' }, function (st) {
st['throws'](
function () { ES.PromiseResolve(); },
SyntaxError,
'Promises are not supported'
);
st.end();
});
t.test('Promises supported', { skip: typeof Promise !== 'function' }, function (st) {
st.plan(2);
var a = {};
var b = {};
var fulfilled = Promise.resolve(a);
var rejected = Promise.reject(b);
ES.PromiseResolve(Promise, fulfilled).then(function (x) {
st.equal(x, a, 'fulfilled promise resolves to fulfilled');
});
ES.PromiseResolve(Promise, rejected)['catch'](function (e) {
st.equal(e, b, 'rejected promise resolves to rejected');
});
});
t.end();
});
test('EnumerableOwnPropertyNames', { skip: skips && skips.EnumerableOwnPropertyNames }, function (t) {
var obj = testEnumerableOwnNames(t, function (O) {
return ES.EnumerableOwnPropertyNames(O, 'key');
});
t.deepEqual(
ES.EnumerableOwnPropertyNames(obj, 'value'),
[obj.own],
'returns enumerable own values'
);
t.deepEqual(
ES.EnumerableOwnPropertyNames(obj, 'key+value'),
[['own', obj.own]],
'returns enumerable own entries'
);
t.end();
});
test('IsPromise', { skip: typeof Promise !== 'function' }, function (t) {
forEach(v.objects.concat(v.primitives), function (nonPromise) {
t.equal(ES.IsPromise(nonPromise), false, debug(nonPromise) + ' is not a Promise');
});
var thenable = { then: Promise.prototype.then };
t.equal(ES.IsPromise(thenable), false, 'generic thenable is not a Promise');
t.equal(ES.IsPromise(Promise.resolve()), true, 'Promise is a Promise');
t.end();
});
test('GetSubstitution (ES2018+)', function (t) {
forEach(v.nonStrings, function (nonString) {
t['throws'](
function () { ES.GetSubstitution(nonString, '', 0, [], undefined, ''); },
TypeError,
'`matched`: ' + debug(nonString) + ' is not a String'
);
t['throws'](
function () { ES.GetSubstitution('', nonString, 0, [], undefined, ''); },
TypeError,
'`str`: ' + debug(nonString) + ' is not a String'
);
t['throws'](
function () { ES.GetSubstitution('', '', 0, [], undefined, nonString); },
TypeError,
'`replacement`: ' + debug(nonString) + ' is not a String'
);
t['throws'](
function () { ES.GetSubstitution('', '', 0, [nonString], undefined, ''); },
TypeError,
'`captures`: ' + debug([nonString]) + ' is not an Array of strings'
);
});
forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) {
t['throws'](
function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], undefined, ''); },
TypeError,
'`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer'
);
});
forEach(v.nonArrays, function (nonArray) {
t['throws'](
function () { ES.GetSubstitution('', '', 0, nonArray, undefined, ''); },
TypeError,
'`captures`: ' + debug(nonArray) + ' is not an Array'
);
});
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '123'),
'123',
'returns the substitution'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '$$2$'),
'$2$',
'supports $$, and trailing $'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$&<'),
'>abcdef<',
'supports $&'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$`<'),
'><',
'supports $` at position 0'
);
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '>$`<'),
'>ab<',
'supports $` at position > 0'
);
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 7, [], undefined, ">$'<"),
'><',
"supports $' at a position where there's less than `matched.length` chars left"
);
t.equal(
ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, ">$'<"),
'>ghi<',
"supports $' at a position where there's more than `matched.length` chars left"
);
for (var i = 0; i < 100; i += 1) {
var captures = [];
captures[i] = 'test';
if (i > 0) {
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i + '<'),
'>undefined<',
'supports $' + i + ' with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i),
'>undefined',
'supports $' + i + ' at the end of the replacement, with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i + '<'),
'><',
'supports $' + i + ' with a capture at that index'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i),
'>',
'supports $' + i + ' at the end of the replacement, with a capture at that index'
);
}
if (i < 10) {
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i + '<'),
i === 0 ? '><' : '>undefined<',
'supports $0' + i + ' with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i),
i === 0 ? '>' : '>undefined',
'supports $0' + i + ' at the end of the replacement, with no captures'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i + '<'),
'><',
'supports $0' + i + ' with a capture at that index'
);
t.equal(
ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i),
'>',
'supports $0' + i + ' at the end of the replacement, with a capture at that index'
);
}
}
t.end();
});
};
var es2019 = function ES2018(ES, ops, expectedMissing, skips) {
es2018(ES, ops, expectedMissing, assign({}, skips, {
}));
test('AddEntriesFromIterable', function (t) {
t['throws'](
function () { ES.AddEntriesFromIterable({}, undefined, function () {}); },
TypeError,
'iterable must not be undefined'
);
t['throws'](
function () { ES.AddEntriesFromIterable({}, null, function () {}); },
TypeError,
'iterable must not be null'
);
forEach(v.nonFunctions, function (nonFunction) {
t['throws'](
function () { ES.AddEntriesFromIterable({}, {}, nonFunction); },
TypeError,
debug(nonFunction) + ' is not a function'
);
});
t.test('Symbol support', { skip: !v.hasSymbols }, function (st) {
st.plan(4);
var O = {};
st.equal(ES.AddEntriesFromIterable(O, [], function () {}), O, 'returns the target');
var adder = function (key, value) {
st.equal(this, O, 'adder gets proper receiver');
st.equal(key, 0, 'k is key');
st.equal(value, 'a', 'v is value');
};
ES.AddEntriesFromIterable(O, ['a'].entries(), adder);
st.end();
});
t.end();
});
test('FlattenIntoArray', function (t) {
t.test('no mapper function', function (st) {
var testDepth = function testDepth(tt, depth, expected) {
var a = [];
var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays
ES.FlattenIntoArray(a, o, o.length, 0, depth);
tt.deepEqual(a, expected, 'depth: ' + depth);
};
testDepth(st, 1, [1, 2, [3], 4, [[[5]]]]);
testDepth(st, 2, [1, 2, 3, 4, [[5]]]);
testDepth(st, 3, [1, 2, 3, 4, [5]]);
testDepth(st, 4, [1, 2, 3, 4, 5]);
testDepth(st, Infinity, [1, 2, 3, 4, 5]);
st.end();
});
t.test('mapper function', function (st) {
var testMapper = function testMapper(tt, mapper, expected, thisArg) {
var a = [];
var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays
ES.FlattenIntoArray(a, o, o.length, 0, 1, mapper, thisArg);
tt.deepEqual(a, expected);
};
var double = function double(x) {
return typeof x === 'number' ? 2 * x : x;
};
testMapper(
st,
double,
[1, 4, [3], 8, [[[5]]]]
);
testMapper(
st,
function (x) { return [this, double(x)]; },
[42, [1], 42, 4, 42, [[3]], 42, [], 42, 8, 42, [[[[5]]]]],
42
);
st.end();
});
t.end();
});
test('TrimString', function (t) {
t.test('non-object string', function (st) {
forEach(v.nullPrimitives, function (nullish) {
st['throws'](
function () { ES.TrimString(nullish); },
debug(nullish) + ' is not an Object'
);
});
st.end();
});
var string = ' \n abc \n ';
t.equal(ES.TrimString(string, 'start'), string.slice(string.indexOf('a')));
t.equal(ES.TrimString(string, 'end'), string.slice(0, string.lastIndexOf('c') + 1));
t.equal(ES.TrimString(string, 'start+end'), string.slice(string.indexOf('a'), string.lastIndexOf('c') + 1));
t.end();
});
};
module.exports = {
es2015: es2015,
es2016: es2016,
es2017: es2017,
es2018: es2018,
es2019: es2019
};
|
angular
.module('app')
.factory('nodejsService', nodejsService);
nodejsService.$inject = ['$window'];
function nodejsService($window) {
var ok = !!$window.require;
var service = {
ok : ok,
fs : (ok?$window.require('fs'):null),
path : (ok?$window.require('path'):null),
};
return service;
} |
/***************************************************************************************************************************************************************
*
* Initiate app
*
**************************************************************************************************************************************************************/
App.init(); //start the app |
import GroupD8 from '../math/GroupD8';
/**
* A standard object to store the Uvs of a texture
*
* @class
* @private
* @memberof PIXI
*/
export default class TextureUvs
{
/**
*
*/
constructor()
{
this.x0 = 0;
this.y0 = 0;
this.x1 = 1;
this.y1 = 0;
this.x2 = 1;
this.y2 = 1;
this.x3 = 0;
this.y3 = 1;
this.uvsUint32 = new Uint32Array(4);
}
/**
* Sets the texture Uvs based on the given frame information.
*
* @private
* @param {PIXI.Rectangle} frame - The frame of the texture
* @param {PIXI.Rectangle} baseFrame - The base frame of the texture
* @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8}
*/
set(frame, baseFrame, rotate)
{
const tw = baseFrame.width;
const th = baseFrame.height;
if (rotate)
{
// width and height div 2 div baseFrame size
const w2 = frame.width / 2 / tw;
const h2 = frame.height / 2 / th;
// coordinates of center
const cX = (frame.x / tw) + w2;
const cY = (frame.y / th) + h2;
rotate = GroupD8.add(rotate, GroupD8.NW); // NW is top-left corner
this.x0 = cX + (w2 * GroupD8.uX(rotate));
this.y0 = cY + (h2 * GroupD8.uY(rotate));
rotate = GroupD8.add(rotate, 2); // rotate 90 degrees clockwise
this.x1 = cX + (w2 * GroupD8.uX(rotate));
this.y1 = cY + (h2 * GroupD8.uY(rotate));
rotate = GroupD8.add(rotate, 2);
this.x2 = cX + (w2 * GroupD8.uX(rotate));
this.y2 = cY + (h2 * GroupD8.uY(rotate));
rotate = GroupD8.add(rotate, 2);
this.x3 = cX + (w2 * GroupD8.uX(rotate));
this.y3 = cY + (h2 * GroupD8.uY(rotate));
}
else
{
this.x0 = frame.x / tw;
this.y0 = frame.y / th;
this.x1 = (frame.x + frame.width) / tw;
this.y1 = frame.y / th;
this.x2 = (frame.x + frame.width) / tw;
this.y2 = (frame.y + frame.height) / th;
this.x3 = frame.x / tw;
this.y3 = (frame.y + frame.height) / th;
}
this.uvsUint32[0] = ((Math.round(this.y0 * 65535) & 0xFFFF) << 16) | (Math.round(this.x0 * 65535) & 0xFFFF);
this.uvsUint32[1] = ((Math.round(this.y1 * 65535) & 0xFFFF) << 16) | (Math.round(this.x1 * 65535) & 0xFFFF);
this.uvsUint32[2] = ((Math.round(this.y2 * 65535) & 0xFFFF) << 16) | (Math.round(this.x2 * 65535) & 0xFFFF);
this.uvsUint32[3] = ((Math.round(this.y3 * 65535) & 0xFFFF) << 16) | (Math.round(this.x3 * 65535) & 0xFFFF);
}
}
|
/////////////////////////////////////////////////////////////////////
// Viewing.Extension.A360View
// by Philippe Leefsma, Feb 2016
//
/////////////////////////////////////////////////////////////////////
import ToolPanelModal from 'ToolPanelModal/ToolPanelModal'
import Dropdown from 'Dropdown/Dropdown'
import './CreateBucketPanel.scss'
export default class CreateBucketPanel extends ToolPanelModal {
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
constructor (container) {
super(container, {
title: 'Bucket Settings'
})
$(this.container).addClass('create-bucket')
this.dropdownContainerId = ToolPanelModal.guid()
this.inputId = ToolPanelModal.guid()
this.bucketKey = 'forge-' + ToolPanelModal.guid(
'xxxx-xxxx-xxxx')
this.bodyContent(`
<div>
<input id="${this.inputId}" type="text" class="bucket-key"
placeholder=" Bucket Key (${this.bucketKey}) ...">
<div id="${this.dropdownContainerId}">
</div>
</div>
`)
this.dropdown = new Dropdown({
container: '#' + this.dropdownContainerId,
title: 'Bucket Policy',
prompt: 'Bucket Policy',
pos: {
top: 0, left: 0
},
menuItems: [{
name: 'Transient'
}, {
name: 'Temporary'
}, {
name: 'Persistent'
}]
})
this.dropdown.setCurrentItem({
name: 'Transient'
})
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
get PolicyKey() {
return this.dropdown.currentItem.name
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
get BucketKey() {
var $bucketKey = $(`#${this.inputId}`)
return $bucketKey.val().length ?
$bucketKey.val() :
this.bucketKey
}
}
|
import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import { dbCompanies } from '/db/dbCompanies';
import { limitSubscription } from '/server/imports/utils/rateLimit';
import { debug } from '/server/imports/utils/debug';
import { publishTotalCount } from '/server/imports/utils/publishTotalCount';
Meteor.publish('accountManagerTitle', function(userId, offset) {
debug.log('publish accountManagerTitle', { userId, offset });
check(userId, String);
check(offset, Match.Integer);
const filter = { manager: userId, isSeal: false };
publishTotalCount('totalCountOfManagerTitle', dbCompanies.find(filter), this);
return dbCompanies
.find(filter, {
fields: {
isSeal: 1,
manager: 1
},
skip: offset,
limit: 10,
disableOplog: true
});
});
// 一分鐘最多20次
limitSubscription('accountManagerTitle');
|
/**
* @author mrdoob / http://mrdoob.com/
* @author Larry Battle / http://bateru.com/news
* @author bhouston / http://exocortex.com
*/
var loadStatus = 0;
var THREE = { REVISION: '66' };
self.console = self.console || {
info: function () {},
log: function () {},
debug: function () {},
warn: function () {},
error: function () {}
};
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel
// using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
( function () {
var lastTime = 0;
var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
}
if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
self.requestAnimationFrame = function ( callback ) {
var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
lastTime = currTime + timeToCall;
return id;
};
}
if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
}
}() );
// 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;
// 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;
// Compressed texture formats
THREE.RGB_S3TC_DXT1_Format = 2001;
THREE.RGBA_S3TC_DXT1_Format = 2002;
THREE.RGBA_S3TC_DXT3_Format = 2003;
THREE.RGBA_S3TC_DXT5_Format = 2004;
/*
// Potential future PVRTC compressed texture formats
THREE.RGB_PVRTC_4BPPV1_Format = 2100;
THREE.RGB_PVRTC_2BPPV1_Format = 2101;
THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
*/
/**
* @author 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 };
/**
* @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,
_euler: undefined,
_updateEuler: function ( callback ) {
if ( this._euler !== undefined ) {
this._euler.setFromQuaternion( this, undefined, false );
}
},
get x () {
return this._x;
},
set x ( value ) {
this._x = value;
this._updateEuler();
},
get y () {
return this._y;
},
set y ( value ) {
this._y = value;
this._updateEuler();
},
get z () {
return this._z;
},
set z ( value ) {
this._z = value;
this._updateEuler();
},
get w () {
return this._w;
},
set w ( value ) {
this._w = value;
this._updateEuler();
},
set: function ( x, y, z, w ) {
this._x = x;
this._y = y;
this._z = z;
this._w = w;
this._updateEuler();
return this;
},
copy: function ( quaternion ) {
this._x = quaternion._x;
this._y = quaternion._y;
this._z = quaternion._z;
this._w = quaternion._w;
this._updateEuler();
return this;
},
setFromEuler: function ( euler, update ) {
if ( euler instanceof THREE.Euler === false ) {
throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
}
// 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._updateEuler();
return this;
},
setFromAxisAngle: function ( axis, angle ) {
// from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
// axis have to be normalized
var halfAngle = angle / 2, s = Math.sin( halfAngle );
this._x = axis.x * s;
this._y = axis.y * s;
this._z = axis.z * s;
this._w = Math.cos( halfAngle );
this._updateEuler();
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._updateEuler();
return this;
},
inverse: function () {
this.conjugate().normalize();
return this;
},
conjugate: function () {
this._x *= -1;
this._y *= -1;
this._z *= -1;
this._updateEuler();
return this;
},
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;
}
return this;
},
multiply: function ( q, p ) {
if ( p !== undefined ) {
console.warn( 'DEPRECATED: Quaternion\'s .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._updateEuler();
return this;
},
multiplyVector3: function ( vector ) {
console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
return vector.applyQuaternion( this );
},
slerp: function ( qb, t ) {
var x = this._x, y = this._y, z = this._z, w = this._w;
// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
if ( cosHalfTheta < 0 ) {
this._w = -qb._w;
this._x = -qb._x;
this._y = -qb._y;
this._z = -qb._z;
cosHalfTheta = -cosHalfTheta;
} else {
this.copy( qb );
}
if ( cosHalfTheta >= 1.0 ) {
this._w = w;
this._x = x;
this._y = y;
this._z = z;
return this;
}
var halfTheta = Math.acos( cosHalfTheta );
var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
if ( Math.abs( sinHalfTheta ) < 0.001 ) {
this._w = 0.5 * ( w + this._w );
this._x = 0.5 * ( x + this._x );
this._y = 0.5 * ( y + this._y );
this._z = 0.5 * ( z + this._z );
return this;
}
var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
this._w = ( w * ratioA + this._w * ratioB );
this._x = ( x * ratioA + this._x * ratioB );
this._y = ( y * ratioA + this._y * ratioB );
this._z = ( z * ratioA + this._z * ratioB );
this._updateEuler();
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 ) {
this._x = array[ 0 ];
this._y = array[ 1 ];
this._z = array[ 2 ];
this._w = array[ 3 ];
this._updateEuler();
return this;
},
toArray: function () {
return [ this._x, this._y, this._z, this._w ];
},
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 );
}
/**
* @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( 'DEPRECATED: Vector2\'s .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( 'DEPRECATED: Vector2\'s .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;
},
multiplyScalar: function ( s ) {
this.x *= s;
this.y *= s;
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 () {
return this.multiplyScalar( - 1 );
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y;
},
length: function () {
return Math.sqrt( this.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 ) {
this.x = array[ 0 ];
this.y = array[ 1 ];
return this;
},
toArray: function () {
return [ this.x, this.y ];
},
clone: function () {
return new THREE.Vector2( this.x, this.y );
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author *kile / http://kile.stravaganza.org/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Vector3 = function ( x, y, z ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
};
THREE.Vector3.prototype = {
constructor: THREE.Vector3,
set: function ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setZ: function ( z ) {
this.z = z;
return this;
},
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( 'DEPRECATED: Vector3\'s .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( 'DEPRECATED: Vector3\'s .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( 'DEPRECATED: Vector3\'s .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( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
}
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;
},
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 () {
return this.multiplyScalar( - 1 );
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y + this.z * this.z;
},
length: function () {
return Math.sqrt( this.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( 'DEPRECATED: Vector3\'s .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( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
},
setEulerFromQuaternion: function ( q, order ) {
console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
},
getPositionFromMatrix: function ( m ) {
console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
return this.setFromMatrixPosition( m );
},
getScaleFromMatrix: function ( m ) {
console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
return this.setFromMatrixScale( m );
},
getColumnFromMatrix: function ( index, matrix ) {
console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
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 ) {
this.x = array[ 0 ];
this.y = array[ 1 ];
this.z = array[ 2 ];
return this;
},
toArray: function () {
return [ this.x, this.y, this.z ];
},
clone: function () {
return new THREE.Vector3( this.x, this.y, this.z );
}
};
/**
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Vector4 = function ( x, y, z, w ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = ( w !== undefined ) ? w : 1;
};
THREE.Vector4.prototype = {
constructor: THREE.Vector4,
set: function ( x, y, z, w ) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
},
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( 'DEPRECATED: Vector4\'s .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( 'DEPRECATED: Vector4\'s .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 () {
return this.multiplyScalar( -1 );
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
},
lengthSq: function () {
return this.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 ) {
this.x = array[ 0 ];
this.y = array[ 1 ];
this.z = array[ 2 ];
this.w = array[ 3 ];
return this;
},
toArray: function () {
return [ this.x, this.y, this.z, this.w ];
},
clone: function () {
return new THREE.Vector4( this.x, this.y, this.z, this.w );
}
};
/**
* @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,
_quaternion: undefined,
_updateQuaternion: function () {
if ( this._quaternion !== undefined ) {
this._quaternion.setFromEuler( this, false );
}
},
get x () {
return this._x;
},
set x ( value ) {
this._x = value;
this._updateQuaternion();
},
get y () {
return this._y;
},
set y ( value ) {
this._y = value;
this._updateQuaternion();
},
get z () {
return this._z;
},
set z ( value ) {
this._z = value;
this._updateQuaternion();
},
get order () {
return this._order;
},
set order ( value ) {
this._order = value;
this._updateQuaternion();
},
set: function ( x, y, z, order ) {
this._x = x;
this._y = y;
this._z = z;
this._order = order || this._order;
this._updateQuaternion();
return this;
},
copy: function ( euler ) {
this._x = euler._x;
this._y = euler._y;
this._z = euler._z;
this._order = euler._order;
this._updateQuaternion();
return this;
},
setFromRotationMatrix: function ( m, order ) {
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
// clamp, to handle numerical problems
function clamp( x ) {
return Math.min( Math.max( x, -1 ), 1 );
}
var te = m.elements;
var m11 = te[0], m12 = te[4], m13 = te[8];
var m21 = te[1], m22 = te[5], m23 = te[9];
var m31 = te[2], m32 = te[6], m33 = te[10];
order = order || this._order;
if ( order === 'XYZ' ) {
this._y = Math.asin( clamp( m13 ) );
if ( Math.abs( m13 ) < 0.99999 ) {
this._x = Math.atan2( - m23, m33 );
this._z = Math.atan2( - m12, m11 );
} else {
this._x = Math.atan2( m32, m22 );
this._z = 0;
}
} else if ( order === 'YXZ' ) {
this._x = Math.asin( - clamp( m23 ) );
if ( Math.abs( m23 ) < 0.99999 ) {
this._y = Math.atan2( m13, m33 );
this._z = Math.atan2( m21, m22 );
} else {
this._y = Math.atan2( - m31, m11 );
this._z = 0;
}
} else if ( order === 'ZXY' ) {
this._x = Math.asin( clamp( m32 ) );
if ( Math.abs( m32 ) < 0.99999 ) {
this._y = Math.atan2( - m31, m33 );
this._z = Math.atan2( - m12, m22 );
} else {
this._y = 0;
this._z = Math.atan2( m21, m11 );
}
} else if ( order === 'ZYX' ) {
this._y = Math.asin( - clamp( m31 ) );
if ( Math.abs( m31 ) < 0.99999 ) {
this._x = Math.atan2( m32, m33 );
this._z = Math.atan2( m21, m11 );
} else {
this._x = 0;
this._z = Math.atan2( - m12, m22 );
}
} else if ( order === 'YZX' ) {
this._z = Math.asin( clamp( m21 ) );
if ( Math.abs( m21 ) < 0.99999 ) {
this._x = Math.atan2( - m23, m22 );
this._y = Math.atan2( - m31, m11 );
} else {
this._x = 0;
this._y = Math.atan2( m13, m33 );
}
} else if ( order === 'XZY' ) {
this._z = Math.asin( - clamp( m12 ) );
if ( Math.abs( m12 ) < 0.99999 ) {
this._x = Math.atan2( m32, m22 );
this._y = Math.atan2( m13, m11 );
} else {
this._x = Math.atan2( - m23, m33 );
this._y = 0;
}
} else {
console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
}
this._order = order;
this._updateQuaternion();
return this;
},
setFromQuaternion: function ( q, order, update ) {
// q is assumed to be normalized
// clamp, to handle numerical problems
function clamp( x ) {
return Math.min( Math.max( x, -1 ), 1 );
}
// http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
var sqx = q.x * q.x;
var sqy = q.y * q.y;
var sqz = q.z * q.z;
var sqw = q.w * q.w;
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 ) ) );
this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
} else if ( order === 'YXZ' ) {
this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
} else if ( order === 'ZXY' ) {
this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
} else if ( order === 'ZYX' ) {
this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
} else if ( order === 'YZX' ) {
this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
} else if ( order === 'XZY' ) {
this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
} else {
console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
}
this._order = order;
if ( update !== false ) this._updateQuaternion();
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 );
};
}(),
fromArray: function ( array ) {
this._x = array[ 0 ];
this._y = array[ 1 ];
this._z = array[ 2 ];
if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
this._updateQuaternion();
return this;
},
toArray: function () {
return [ this._x, this._y, this._z, this._order ];
},
equals: function ( euler ) {
return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
},
clone: function () {
return new THREE.Euler( this._x, this._y, this._z, this._order );
}
};
/**
* @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 );
}
};
/**
* @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 ) {
if ( points.length > 0 ) {
var point = points[ 0 ];
this.min.copy( point );
this.max.copy( point );
for ( var i = 1, il = points.length; i < il; i ++ ) {
point = points[ i ];
if ( point.x < this.min.x ) {
this.min.x = point.x;
} else if ( point.x > this.max.x ) {
this.max.x = point.x;
}
if ( point.y < this.min.y ) {
this.min.y = point.y;
} else if ( point.y > this.max.y ) {
this.max.y = point.y;
}
}
} else {
this.makeEmpty();
}
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 );
}
};
/**
* @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;
},
addPoint: function ( point ) {
if ( point.x < this.min.x ) {
this.min.x = point.x;
} else if ( point.x > this.max.x ) {
this.max.x = point.x;
}
if ( point.y < this.min.y ) {
this.min.y = point.y;
} else if ( point.y > this.max.y ) {
this.max.y = point.y;
}
if ( point.z < this.min.z ) {
this.min.z = point.z;
} else if ( point.z > this.max.z ) {
this.max.z = point.z;
}
},
setFromPoints: function ( points ) {
if ( points.length > 0 ) {
var point = points[ 0 ];
this.min.copy( point );
this.max.copy( point );
for ( var i = 1, il = points.length; i < il; i ++ ) {
this.addPoint( points[ i ] )
}
} else {
this.makeEmpty();
}
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 ) {
if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
var vertices = node.geometry.vertices;
for ( var i = 0, il = vertices.length; i < il; i++ ) {
v1.copy( vertices[ i ] );
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 );
}
};
/**
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author bhouston / http://exocortex.com
*/
THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
this.elements = new Float32Array(9);
this.set(
( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
);
};
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( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
return vector.applyMatrix3( this );
},
multiplyVector3Array: function() {
var v1 = new THREE.Vector3();
return function ( a ) {
for ( var i = 0, il = a.length; i < il; i += 3 ) {
v1.x = a[ i ];
v1.y = a[ i + 1 ];
v1.z = a[ i + 2 ];
v1.applyMatrix3(this);
a[ i ] = v1.x;
a[ i + 1 ] = v1.y;
a[ i + 2 ] = v1.z;
}
return a;
};
}(),
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;
},
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 () {
var te = this.elements;
return new THREE.Matrix3(
te[0], te[3], te[6],
te[1], te[4], te[7],
te[2], te[5], te[8]
);
}
};
/**
* @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 ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
this.elements = new Float32Array( 16 );
// TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
// we should not support semi specification of Matrix4, it is just weird.
var te = this.elements;
te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
};
THREE.Matrix4.prototype = {
constructor: THREE.Matrix4,
set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
var te = this.elements;
te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
return this;
},
identity: function () {
this.set(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
return this;
},
copy: function ( m ) {
this.elements.set( m.elements );
return this;
},
extractPosition: function ( m ) {
console.warn( 'DEPRECATED: Matrix4\'s .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( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
}
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( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
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( 'DEPRECATED: Matrix4\'s .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( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
return vector.applyProjection( this );
},
multiplyVector4: function ( vector ) {
console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
return vector.applyMatrix4( this );
},
multiplyVector3Array: function() {
var v1 = new THREE.Vector3();
return function ( a ) {
for ( var i = 0, il = a.length; i < il; i += 3 ) {
v1.x = a[ i ];
v1.y = a[ i + 1 ];
v1.z = a[ i + 2 ];
v1.applyProjection( this );
a[ i ] = v1.x;
a[ i + 1 ] = v1.y;
a[ i + 2 ] = v1.z;
}
return a;
};
}(),
rotateAxis: function ( v ) {
console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
v.transformDirection( this );
},
crossVector: function ( vector ) {
console.warn( 'DEPRECATED: Matrix4\'s .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;
},
flattenToArray: function ( flat ) {
var te = this.elements;
flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
return flat;
},
flattenToArrayOffset: function( flat, offset ) {
var te = this.elements;
flat[ offset ] = te[0];
flat[ offset + 1 ] = te[1];
flat[ offset + 2 ] = te[2];
flat[ offset + 3 ] = te[3];
flat[ offset + 4 ] = te[4];
flat[ offset + 5 ] = te[5];
flat[ offset + 6 ] = te[6];
flat[ offset + 7 ] = te[7];
flat[ offset + 8 ] = te[8];
flat[ offset + 9 ] = te[9];
flat[ offset + 10 ] = te[10];
flat[ offset + 11 ] = te[11];
flat[ offset + 12 ] = te[12];
flat[ offset + 13 ] = te[13];
flat[ offset + 14 ] = te[14];
flat[ offset + 15 ] = te[15];
return flat;
},
getPosition: function() {
var v1 = new THREE.Vector3();
return function () {
console.warn( 'DEPRECATED: Matrix4\'s .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( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
},
rotateX: function ( angle ) {
console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
},
rotateY: function ( angle ) {
console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
},
rotateZ: function ( angle ) {
console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
},
rotateByAxis: function ( axis, angle ) {
console.warn( 'DEPRECATED: Matrix4\'s .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 () {
var te = this.elements;
return new THREE.Matrix4(
te[0], te[4], te[8], te[12],
te[1], te[5], te[9], te[13],
te[2], te[6], te[10], te[14],
te[3], te[7], te[11], te[15]
);
}
};
/**
* @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;
},
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 );
}
};
/**
* @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 );
}
};
/**
* @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 );
}
};
/**
* @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 );
}
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
THREE.Math = {
PI2: Math.PI * 2,
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() );
},
sign: function ( x ) {
return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
},
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;
}
};
/**
* Spline from Tween.js, slightly optimized (and trashed)
* http://sole.github.com/tween.js/examples/05_spline.html
*
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Spline = function ( points ) {
this.points = points;
var c = [], v3 = { x: 0, y: 0, z: 0 },
point, intPoint, weight, w2, w3,
pa, pb, pc, pd;
this.initFromArray = function( a ) {
this.points = [];
for ( var i = 0; i < a.length; i++ ) {
this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
}
};
this.getPoint = function ( k ) {
point = ( this.points.length - 1 ) * k;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
pa = this.points[ c[ 0 ] ];
pb = this.points[ c[ 1 ] ];
pc = this.points[ c[ 2 ] ];
pd = this.points[ c[ 3 ] ];
w2 = weight * weight;
w3 = weight * w2;
v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
return v3;
};
this.getControlPointsArray = function () {
var i, p, l = this.points.length,
coords = [];
for ( i = 0; i < l; i ++ ) {
p = this.points[ i ];
coords[ i ] = [ p.x, p.y, p.z ];
}
return coords;
};
// approximate length by summing linear segments
this.getLength = function ( nSubDivisions ) {
var i, index, nSamples, position,
point = 0, intPoint = 0, oldIntPoint = 0,
oldPosition = new THREE.Vector3(),
tmpVec = new THREE.Vector3(),
chunkLengths = [],
totalLength = 0;
// first point has 0 length
chunkLengths[ 0 ] = 0;
if ( !nSubDivisions ) nSubDivisions = 100;
nSamples = this.points.length * nSubDivisions;
oldPosition.copy( this.points[ 0 ] );
for ( i = 1; i < nSamples; i ++ ) {
index = i / nSamples;
position = this.getPoint( index );
tmpVec.copy( position );
totalLength += tmpVec.distanceTo( oldPosition );
oldPosition.copy( position );
point = ( this.points.length - 1 ) * index;
intPoint = Math.floor( point );
if ( intPoint != oldIntPoint ) {
chunkLengths[ intPoint ] = totalLength;
oldIntPoint = intPoint;
}
}
// last point ends with total length
chunkLengths[ chunkLengths.length ] = totalLength;
return { chunks: chunkLengths, total: totalLength };
};
this.reparametrizeByArcLength = function ( samplingCoef ) {
var i, j,
index, indexCurrent, indexNext,
linearDistance, realDistance,
sampling, position,
newpoints = [],
tmpVec = new THREE.Vector3(),
sl = this.getLength();
newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
for ( i = 1; i < this.points.length; i++ ) {
//tmpVec.copy( this.points[ i - 1 ] );
//linearDistance = tmpVec.distanceTo( this.points[ i ] );
realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
sampling = Math.ceil( samplingCoef * realDistance / sl.total );
indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
indexNext = i / ( this.points.length - 1 );
for ( j = 1; j < sampling - 1; j++ ) {
index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
position = this.getPoint( index );
newpoints.push( tmpVec.copy( position ).clone() );
}
newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
}
this.points = newpoints;
};
// Catmull-Rom
function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
var v0 = ( p2 - p0 ) * 0.5,
v1 = ( p3 - p1 ) * 0.5;
return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
};
};
/**
* @author 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 );
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Vertex = function ( v ) {
console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
return v;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.UV = function ( u, v ) {
console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
return new THREE.Vector2( u, v );
};
/**
* @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;
}
};
/**
* 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 () {
var array = [];
return function ( event ) {
if ( this._listeners === undefined ) return;
var listeners = this._listeners;
var listenerArray = listeners[ event.type ];
if ( listenerArray !== undefined ) {
event.target = this;
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 );
}
}
};
}()
};
/**
* @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;
};
var sphere = new THREE.Sphere();
var localRay = new THREE.Ray();
var facePlane = new THREE.Plane();
var intersectPoint = new THREE.Vector3();
var matrixPosition = new THREE.Vector3();
var inverseMatrix = new THREE.Matrix4();
var descSort = function ( a, b ) {
return a.distance - b.distance;
};
var vA = new THREE.Vector3();
var vB = new THREE.Vector3();
var vC = new THREE.Vector3();
var intersectObject = function ( object, raycaster, intersects ) {
if ( object instanceof THREE.Sprite ) {
matrixPosition.setFromMatrixPosition( object.matrixWorld );
var distance = raycaster.ray.distanceToPoint( matrixPosition );
if ( distance > object.scale.x ) {
return intersects;
}
intersects.push( {
distance: distance,
point: object.position,
face: null,
object: object
} );
} else if ( object instanceof THREE.LOD ) {
matrixPosition.setFromMatrixPosition( object.matrixWorld );
var distance = raycaster.ray.origin.distanceTo( matrixPosition );
intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
} else if ( object instanceof THREE.Mesh ) {
var geometry = object.geometry;
// Checking boundingSphere distance to ray
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
sphere.copy( geometry.boundingSphere );
sphere.applyMatrix4( object.matrixWorld );
if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
return intersects;
}
// Check boundingBox before continuing
inverseMatrix.getInverse( object.matrixWorld );
localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
if ( geometry.boundingBox !== null ) {
if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
return intersects;
}
}
if ( geometry instanceof THREE.BufferGeometry ) {
var material = object.material;
if ( material === undefined ) return intersects;
var attributes = geometry.attributes;
var a, b, c;
var precision = raycaster.precision;
if ( attributes.index !== undefined ) {
var offsets = geometry.offsets;
var indices = attributes.index.array;
var positions = attributes.position.array;
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.set(
positions[ a * 3 ],
positions[ a * 3 + 1 ],
positions[ a * 3 + 2 ]
);
vB.set(
positions[ b * 3 ],
positions[ b * 3 + 1 ],
positions[ b * 3 + 2 ]
);
vC.set(
positions[ c * 3 ],
positions[ c * 3 + 1 ],
positions[ c * 3 + 2 ]
);
if ( material.side === THREE.BackSide ) {
var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
} else {
var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
}
if ( intersectionPoint === null ) continue;
intersectionPoint.applyMatrix4( object.matrixWorld );
var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
intersects.push( {
distance: distance,
point: intersectionPoint,
indices: [a, b, c],
face: null,
faceIndex: null,
object: object
} );
}
}
} else {
var offsets = geometry.offsets;
var positions = attributes.position.array;
for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
a = i;
b = i + 1;
c = i + 2;
vA.set(
positions[ a * 3 ],
positions[ a * 3 + 1 ],
positions[ a * 3 + 2 ]
);
vB.set(
positions[ b * 3 ],
positions[ b * 3 + 1 ],
positions[ b * 3 + 2 ]
);
vC.set(
positions[ c * 3 ],
positions[ c * 3 + 1 ],
positions[ c * 3 + 2 ]
);
if ( material.side === THREE.BackSide ) {
var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
} else {
var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
}
if ( intersectionPoint === null ) continue;
intersectionPoint.applyMatrix4( object.matrixWorld );
var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
intersects.push( {
distance: distance,
point: intersectionPoint,
indices: [a, b, c],
face: null,
faceIndex: null,
object: object
} );
}
}
} else if ( geometry instanceof THREE.Geometry ) {
var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
var objectMaterials = isFaceMaterial === true ? object.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 ] : object.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 = object.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 = localRay.intersectTriangle( c, b, a, true );
} else {
var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
}
if ( intersectionPoint === null ) continue;
intersectionPoint.applyMatrix4( object.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: object
} );
}
}
} else if ( object instanceof THREE.Line ) {
var precision = raycaster.linePrecision;
var precisionSq = precision * precision;
var geometry = object.geometry;
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
// Checking boundingSphere distance to ray
sphere.copy( geometry.boundingSphere );
sphere.applyMatrix4( object.matrixWorld );
if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
return intersects;
}
inverseMatrix.getInverse( object.matrixWorld );
localRay.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 = object.type === THREE.LineStrip ? 1 : 2;
for ( var i = 0; i < nbVertices - 1; i = i + step ) {
var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
if ( distSq > precisionSq ) continue;
var distance = localRay.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( object.matrixWorld ),
face: null,
faceIndex: null,
object: object
} );
}
}
}
};
var intersectDescendants = function ( object, raycaster, intersects ) {
var descendants = object.getDescendants();
for ( var i = 0, l = descendants.length; i < l; i ++ ) {
intersectObject( descendants[ i ], raycaster, intersects );
}
};
//
THREE.Raycaster.prototype.precision = 0.0001;
THREE.Raycaster.prototype.linePrecision = 1;
THREE.Raycaster.prototype.set = function ( origin, direction ) {
this.ray.set( origin, direction );
// direction is assumed to be normalized (for accurate distance calculations)
};
THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
var intersects = [];
if ( recursive === true ) {
intersectDescendants( object, this, intersects );
}
intersectObject( object, this, intersects );
intersects.sort( descSort );
return intersects;
};
THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
var intersects = [];
for ( var i = 0, l = objects.length; i < l; i ++ ) {
intersectObject( objects[ i ], this, intersects );
if ( recursive === true ) {
intersectDescendants( objects[ i ], this, intersects );
}
}
intersects.sort( descSort );
return intersects;
};
}( THREE ) );
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Object3D = function () {
this.id = THREE.Object3DIdCount ++;
this.uuid = THREE.Math.generateUUID();
this.name = '';
this.parent = undefined;
this.children = [];
this.up = new THREE.Vector3( 0, 1, 0 );
this.position = new THREE.Vector3();
this._rotation = new THREE.Euler();
this._quaternion = new THREE.Quaternion();
this.scale = new THREE.Vector3( 1, 1, 1 );
// keep rotation and quaternion in sync
this._rotation._quaternion = this.quaternion;
this._quaternion._euler = this.rotation;
this.renderDepth = null;
this.rotationAutoUpdate = true;
this.matrix = new THREE.Matrix4();
this.matrixWorld = new THREE.Matrix4();
this.matrixAutoUpdate = true;
this.matrixWorldNeedsUpdate = true;
this.visible = true;
this.castShadow = false;
this.receiveShadow = false;
this.frustumCulled = true;
this.userData = {};
};
THREE.Object3D.prototype = {
constructor: THREE.Object3D,
get rotation () {
return this._rotation;
},
set rotation ( value ) {
this._rotation = value;
this._rotation._quaternion = this._quaternion;
this._quaternion._euler = this._rotation;
this._rotation._updateQuaternion();
},
get quaternion () {
return this._quaternion;
},
set quaternion ( value ) {
this._quaternion = value;
this._quaternion._euler = this._rotation;
this._rotation._quaternion = this._quaternion;
this._quaternion._updateEuler();
},
get eulerOrder () {
console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
return this.rotation.order;
},
set eulerOrder ( value ) {
console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
this.rotation.order = value;
},
get useQuaternion () {
console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
},
set useQuaternion ( value ) {
console.warn( 'DEPRECATED: Object3D\'s .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 );
v1.applyQuaternion( this.quaternion );
this.position.add( v1.multiplyScalar( distance ) );
return this;
}
}(),
translate: function ( distance, axis ) {
console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
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 ( object === this ) {
console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
return;
}
if ( object instanceof THREE.Object3D ) {
if ( object.parent !== undefined ) {
object.parent.remove( object );
}
object.parent = this;
object.dispatchEvent( { type: 'added' } );
this.children.push( object );
// add to scene
var scene = this;
while ( scene.parent !== undefined ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
scene.__addObject( object );
}
}
},
remove: function ( object ) {
var index = this.children.indexOf( object );
if ( index !== - 1 ) {
object.parent = undefined;
object.dispatchEvent( { type: 'removed' } );
this.children.splice( index, 1 );
// remove from scene
var scene = this;
while ( scene.parent !== undefined ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
scene.__removeObject( object );
}
}
},
traverse: function ( callback ) {
callback( this );
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].traverse( callback );
}
},
getObjectById: function ( id, recursive ) {
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
if ( child.id === id ) {
return child;
}
if ( recursive === true ) {
child = child.getObjectById( id, recursive );
if ( child !== undefined ) {
return child;
}
}
}
return undefined;
},
getObjectByName: function ( name, recursive ) {
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
if ( child.name === name ) {
return child;
}
if ( recursive === true ) {
child = child.getObjectByName( name, recursive );
if ( child !== undefined ) {
return child;
}
}
}
return undefined;
},
getChildByName: function ( name, recursive ) {
console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
return this.getObjectByName( name, recursive );
},
getDescendants: function ( array ) {
if ( array === undefined ) array = [];
Array.prototype.push.apply( array, this.children );
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].getDescendants( array );
}
return array;
},
updateMatrix: function () {
this.matrix.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 );
}
},
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;
/**
* @author mrdoob / http://mrdoob.com/
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author julianwa / https://github.com/julianwa
*/
THREE.Projector = function () {
var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
_vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
_face, _faceCount, _facePool = [], _facePoolLength = 0,
_line, _lineCount, _linePool = [], _linePoolLength = 0,
_sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
_renderData = { objects: [], lights: [], elements: [] },
_vA = new THREE.Vector3(),
_vB = new THREE.Vector3(),
_vC = new THREE.Vector3(),
_vector3 = new THREE.Vector3(),
_vector4 = new THREE.Vector4(),
_clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
_boundingBox = new THREE.Box3(),
_points3 = new Array( 3 ),
_points4 = new Array( 4 ),
_viewMatrix = new THREE.Matrix4(),
_viewProjectionMatrix = new THREE.Matrix4(),
_modelMatrix,
_modelViewProjectionMatrix = new THREE.Matrix4(),
_normalMatrix = new THREE.Matrix3(),
_frustum = new THREE.Frustum(),
_clippedVertex1PositionScreen = new THREE.Vector4(),
_clippedVertex2PositionScreen = new THREE.Vector4();
this.projectVector = function ( vector, camera ) {
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
return vector.applyProjection( _viewProjectionMatrix );
};
this.unprojectVector = function () {
var projectionMatrixInverse = new THREE.Matrix4();
return function ( vector, camera ) {
projectionMatrixInverse.getInverse( camera.projectionMatrix );
_viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
return vector.applyProjection( _viewProjectionMatrix );
};
}();
this.pickingRay = function ( vector, camera ) {
// set two vectors with opposing z values
vector.z = -1.0;
var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
this.unprojectVector( vector, camera );
this.unprojectVector( end, camera );
// find direction from vector to end
end.sub( vector ).normalize();
return new THREE.Raycaster( vector, end );
};
var projectObject = function ( object ) {
if ( object.visible === false ) return;
if ( object instanceof THREE.Light ) {
_renderData.lights.push( object );
} else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
_object = getNextObjectInPool();
_object.id = object.id;
_object.object = object;
if ( object.renderDepth !== null ) {
_object.z = object.renderDepth;
} else {
_vector3.setFromMatrixPosition( object.matrixWorld );
_vector3.applyProjection( _viewProjectionMatrix );
_object.z = _vector3.z;
}
_renderData.objects.push( _object );
}
}
for ( var i = 0, l = object.children.length; i < l; i ++ ) {
projectObject( object.children[ i ] );
}
};
var projectGraph = function ( root, sortObjects ) {
_objectCount = 0;
_renderData.objects.length = 0;
_renderData.lights.length = 0;
projectObject( root );
if ( sortObjects === true ) {
_renderData.objects.sort( painterSort );
}
};
var RenderList = function () {
var normals = [];
var object = null;
var normalMatrix = new THREE.Matrix3();
var setObject = function ( value ) {
object = value;
normalMatrix.getNormalMatrix( object.matrixWorld );
normals.length = 0;
};
var projectVertex = function ( vertex ) {
var position = vertex.position;
var positionWorld = vertex.positionWorld;
var positionScreen = vertex.positionScreen;
positionWorld.copy( position ).applyMatrix4( _modelMatrix );
positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
var invW = 1 / positionScreen.w;
positionScreen.x *= invW;
positionScreen.y *= invW;
positionScreen.z *= invW;
vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
positionScreen.y >= -1 && positionScreen.y <= 1 &&
positionScreen.z >= -1 && positionScreen.z <= 1;
};
var pushVertex = function ( x, y, z ) {
_vertex = getNextVertexInPool();
_vertex.position.set( x, y, z );
projectVertex( _vertex );
};
var pushNormal = function ( x, y, z ) {
normals.push( x, y, z );
};
var checkTriangleVisibility = function ( v1, v2, v3 ) {
_points3[ 0 ] = v1.positionScreen;
_points3[ 1 ] = v2.positionScreen;
_points3[ 2 ] = v3.positionScreen;
if ( v1.visible === true || v2.visible === true || v3.visible === true ||
_clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
( v2.positionScreen.y - v1.positionScreen.y ) -
( v3.positionScreen.y - v1.positionScreen.y ) *
( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
}
return false;
};
var pushLine = function ( a, b ) {
var v1 = _vertexPool[ a ];
var v2 = _vertexPool[ b ];
_line = getNextLineInPool();
_line.id = object.id;
_line.v1.copy( v1 );
_line.v2.copy( v2 );
_line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
_line.material = object.material;
_renderData.elements.push( _line );
};
var pushTriangle = function ( a, b, c ) {
var v1 = _vertexPool[ a ];
var v2 = _vertexPool[ b ];
var v3 = _vertexPool[ c ];
if ( checkTriangleVisibility( v1, v2, v3 ) === true ) {
_face = getNextFaceInPool();
_face.id = object.id;
_face.v1.copy( v1 );
_face.v2.copy( v2 );
_face.v3.copy( v3 );
_face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
for ( var i = 0; i < 3; i ++ ) {
var offset = arguments[ i ] * 3;
var normal = _face.vertexNormalsModel[ i ];
normal.set( normals[ offset + 0 ], normals[ offset + 1 ], normals[ offset + 2 ] );
normal.applyMatrix3( normalMatrix ).normalize();
}
_face.vertexNormalsLength = 3;
_face.material = object.material;
_renderData.elements.push( _face );
}
};
return {
setObject: setObject,
projectVertex: projectVertex,
checkTriangleVisibility: checkTriangleVisibility,
pushVertex: pushVertex,
pushNormal: pushNormal,
pushLine: pushLine,
pushTriangle: pushTriangle
}
};
var renderList = new RenderList();
this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
isFaceMaterial, objectMaterials;
_faceCount = 0;
_lineCount = 0;
_spriteCount = 0;
_renderData.elements.length = 0;
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
if ( camera.parent === undefined ) camera.updateMatrixWorld();
_viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
_viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
_frustum.setFromMatrix( _viewProjectionMatrix );
projectGraph( scene, sortObjects );
for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
object = _renderData.objects[ o ].object;
geometry = object.geometry;
renderList.setObject( object );
_modelMatrix = object.matrixWorld;
_vertexCount = 0;
if ( object instanceof THREE.Mesh ) {
if ( geometry instanceof THREE.BufferGeometry ) {
var attributes = geometry.attributes;
var offsets = geometry.offsets;
if ( attributes.position === undefined ) continue;
var positions = attributes.position.array;
for ( var i = 0, l = positions.length; i < l; i += 3 ) {
renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
}
var normals = attributes.normal.array;
for ( var i = 0, l = normals.length; i < l; i += 3 ) {
renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
}
if ( attributes.index !== undefined ) {
var indices = attributes.index.array;
if ( offsets.length > 0 ) {
for ( var o = 0; o < offsets.length; o ++ ) {
var offset = offsets[ o ];
var index = offset.index;
for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
}
}
} else {
for ( var i = 0, l = indices.length; i < l; i += 3 ) {
renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
}
}
} else {
for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
renderList.pushTriangle( i, i + 1, i + 2 );
}
}
} else if ( geometry instanceof THREE.Geometry ) {
vertices = geometry.vertices;
faces = geometry.faces;
faceVertexUvs = geometry.faceVertexUvs;
_normalMatrix.getNormalMatrix( _modelMatrix );
isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
objectMaterials = isFaceMaterial === true ? object.material : null;
for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
var vertex = vertices[ v ];
renderList.pushVertex( vertex.x, vertex.y, vertex.z );
}
for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
face = faces[ f ];
var material = isFaceMaterial === true
? objectMaterials.materials[ face.materialIndex ]
: object.material;
if ( material === undefined ) continue;
var side = material.side;
var v1 = _vertexPool[ face.a ];
var v2 = _vertexPool[ face.b ];
var v3 = _vertexPool[ face.c ];
if ( material.morphTargets === true ) {
var morphTargets = geometry.morphTargets;
var morphInfluences = object.morphTargetInfluences;
var v1p = v1.position;
var v2p = v2.position;
var v3p = v3.position;
_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 - v1p.x ) * influence;
_vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
_vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
_vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
_vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
_vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
_vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
_vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
_vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
}
v1.position.add( _vA );
v2.position.add( _vB );
v3.position.add( _vC );
renderList.projectVertex( v1 );
renderList.projectVertex( v2 );
renderList.projectVertex( v3 );
}
var visible = renderList.checkTriangleVisibility( v1, v2, v3 );
if ( ( visible === false && side === THREE.FrontSide ) ||
( visible === true && side === THREE.BackSide ) ) continue;
_face = getNextFaceInPool();
_face.id = object.id;
_face.v1.copy( v1 );
_face.v2.copy( v2 );
_face.v3.copy( v3 );
_face.normalModel.copy( face.normal );
if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
_face.normalModel.negate();
}
_face.normalModel.applyMatrix3( _normalMatrix ).normalize();
_face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
faceVertexNormals = face.vertexNormals;
for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
var normalModel = _face.vertexNormalsModel[ n ];
normalModel.copy( faceVertexNormals[ n ] );
if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
normalModel.negate();
}
normalModel.applyMatrix3( _normalMatrix ).normalize();
}
_face.vertexNormalsLength = faceVertexNormals.length;
for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
uvs = faceVertexUvs[ c ][ f ];
if ( uvs === undefined ) continue;
for ( var u = 0, ul = uvs.length; u < ul; u ++ ) {
_face.uvs[ c ][ u ] = uvs[ u ];
}
}
_face.color = face.color;
_face.material = material;
_face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
_renderData.elements.push( _face );
}
}
} else if ( object instanceof THREE.Line ) {
if ( geometry instanceof THREE.BufferGeometry ) {
var attributes = geometry.attributes;
if ( attributes.position !== undefined ) {
var positions = attributes.position.array;
for ( var i = 0, l = positions.length; i < l; i += 3 ) {
renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
}
if ( attributes.index !== undefined ) {
var indices = attributes.index.array;
for ( var i = 0, l = indices.length; i < l; i += 2 ) {
renderList.pushLine( indices[ i ], indices[ i + 1 ] );
}
} else {
for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
renderList.pushLine( i, i + 1 );
}
}
}
} else if ( geometry instanceof THREE.Geometry ) {
_modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
vertices = object.geometry.vertices;
if ( vertices.length === 0 ) continue;
v1 = getNextVertexInPool();
v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
// Handle LineStrip and LinePieces
var step = object.type === THREE.LinePieces ? 2 : 1;
for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
v1 = getNextVertexInPool();
v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
if ( ( v + 1 ) % step > 0 ) continue;
v2 = _vertexPool[ _vertexCount - 2 ];
_clippedVertex1PositionScreen.copy( v1.positionScreen );
_clippedVertex2PositionScreen.copy( v2.positionScreen );
if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
// Perform the perspective divide
_clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
_clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
_line = getNextLineInPool();
_line.id = object.id;
_line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
_line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
_line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
_line.material = object.material;
if ( object.material.vertexColors === THREE.VertexColors ) {
_line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
_line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
}
_renderData.elements.push( _line );
}
}
}
} else if ( object instanceof THREE.Sprite ) {
_vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
_vector4.applyMatrix4( _viewProjectionMatrix );
var invW = 1 / _vector4.w;
_vector4.z *= invW;
if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
_sprite = getNextSpriteInPool();
_sprite.id = object.id;
_sprite.x = _vector4.x * invW;
_sprite.y = _vector4.y * invW;
_sprite.z = _vector4.z;
_sprite.object = object;
_sprite.rotation = object.rotation;
_sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
_sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
_sprite.material = object.material;
_renderData.elements.push( _sprite );
}
}
}
if ( sortElements === true ) _renderData.elements.sort( painterSort );
return _renderData;
};
// Pools
function getNextObjectInPool() {
if ( _objectCount === _objectPoolLength ) {
var object = new THREE.RenderableObject();
_objectPool.push( object );
_objectPoolLength ++;
_objectCount ++;
return object;
}
return _objectPool[ _objectCount ++ ];
}
function getNextVertexInPool() {
if ( _vertexCount === _vertexPoolLength ) {
var vertex = new THREE.RenderableVertex();
_vertexPool.push( vertex );
_vertexPoolLength ++;
_vertexCount ++;
return vertex;
}
return _vertexPool[ _vertexCount ++ ];
}
function getNextFaceInPool() {
if ( _faceCount === _facePoolLength ) {
var face = new THREE.RenderableFace();
_facePool.push( face );
_facePoolLength ++;
_faceCount ++;
return face;
}
return _facePool[ _faceCount ++ ];
}
function getNextLineInPool() {
if ( _lineCount === _linePoolLength ) {
var line = new THREE.RenderableLine();
_linePool.push( line );
_linePoolLength ++;
_lineCount ++
return line;
}
return _linePool[ _lineCount ++ ];
}
function getNextSpriteInPool() {
if ( _spriteCount === _spritePoolLength ) {
var sprite = new THREE.RenderableSprite();
_spritePool.push( sprite );
_spritePoolLength ++;
_spriteCount ++
return sprite;
}
return _spritePool[ _spriteCount ++ ];
}
//
function painterSort( a, b ) {
if ( a.z !== b.z ) {
return b.z - a.z;
} else if ( a.id !== b.id ) {
return a.id - b.id;
} else {
return 0;
}
}
function clipLine( s1, s2 ) {
var alpha1 = 0, alpha2 = 1,
// Calculate the boundary coordinate of each vertex for the near and far clip planes,
// Z = -1 and Z = +1, respectively.
bc1near = s1.z + s1.w,
bc2near = s2.z + s2.w,
bc1far = - s1.z + s1.w,
bc2far = - s2.z + s2.w;
if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
// Both vertices lie entirely within all clip planes.
return true;
} else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
// Both vertices lie entirely outside one of the clip planes.
return false;
} else {
// The line segment spans at least one clip plane.
if ( bc1near < 0 ) {
// v1 lies outside the near plane, v2 inside
alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
} else if ( bc2near < 0 ) {
// v2 lies outside the near plane, v1 inside
alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
}
if ( bc1far < 0 ) {
// v1 lies outside the far plane, v2 inside
alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
} else if ( bc2far < 0 ) {
// v2 lies outside the far plane, v2 inside
alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
}
if ( alpha2 < alpha1 ) {
// The line segment spans two boundaries, but is outside both of them.
// (This can't happen when we're only clipping against just near/far but good
// to leave the check here for future usage if other clip planes are added.)
return false;
} else {
// Update the s1 and s2 vertices to match the clipped line segment.
s1.lerp( s2, alpha1 );
s2.lerp( s1, 1 - alpha2 );
return true;
}
}
}
};
/**
* @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;
this.centroid = new THREE.Vector3();
};
THREE.Face3.prototype = {
constructor: THREE.Face3,
clone: function () {
var face = new THREE.Face3( this.a, this.b, this.c );
face.normal.copy( this.normal );
face.color.copy( this.color );
face.centroid.copy( this.centroid );
face.materialIndex = this.materialIndex;
var i, il;
for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
return face;
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
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 );
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.BufferGeometry = function () {
this.id = THREE.GeometryIdCount ++;
this.uuid = THREE.Math.generateUUID();
this.name = '';
// attributes
this.attributes = {};
// offsets for chunks when using indexed elements
this.offsets = [];
// boundings
this.boundingBox = null;
this.boundingSphere = null;
};
THREE.BufferGeometry.prototype = {
constructor: THREE.BufferGeometry,
addAttribute: function ( name, type, numItems, itemSize ) {
this.attributes[ name ] = {
array: new type( numItems * itemSize ),
itemSize: itemSize
};
return this.attributes[ name ];
},
applyMatrix: function ( matrix ) {
var position = this.attributes.position;
if ( position !== undefined ) {
matrix.multiplyVector3Array( position.array );
position.needsUpdate = true;
}
var normal = this.attributes.normal;
if ( normal !== undefined ) {
var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
normalMatrix.multiplyVector3Array( normal.array );
normal.needsUpdate = true;
}
},
computeBoundingBox: function () {
if ( this.boundingBox === null ) {
this.boundingBox = new THREE.Box3();
}
var positions = this.attributes[ "position" ].array;
if ( positions ) {
var bb = this.boundingBox;
if( positions.length >= 3 ) {
bb.min.x = bb.max.x = positions[ 0 ];
bb.min.y = bb.max.y = positions[ 1 ];
bb.min.z = bb.max.z = positions[ 2 ];
}
for ( var i = 3, il = positions.length; i < il; i += 3 ) {
var x = positions[ i ];
var y = positions[ i + 1 ];
var z = positions[ i + 2 ];
// bounding box
if ( x < bb.min.x ) {
bb.min.x = x;
} else if ( x > bb.max.x ) {
bb.max.x = x;
}
if ( y < bb.min.y ) {
bb.min.y = y;
} else if ( y > bb.max.y ) {
bb.max.y = y;
}
if ( z < bb.min.z ) {
bb.min.z = z;
} else if ( z > bb.max.z ) {
bb.max.z = z;
}
}
}
if ( positions === undefined || positions.length === 0 ) {
this.boundingBox.min.set( 0, 0, 0 );
this.boundingBox.max.set( 0, 0, 0 );
}
},
computeBoundingSphere: function () {
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.addPoint( vector );
}
box.center( center );
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 );
}
}
}(),
computeVertexNormals: function () {
if ( this.attributes[ "position" ] ) {
var i, il;
var j, jl;
var nVertexElements = this.attributes[ "position" ].array.length;
if ( this.attributes[ "normal" ] === undefined ) {
this.attributes[ "normal" ] = {
itemSize: 3,
array: new Float32Array( nVertexElements )
};
} else {
// reset existing normals to zero
for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
this.attributes[ "normal" ].array[ i ] = 0;
}
}
var positions = this.attributes[ "position" ].array;
var normals = this.attributes[ "normal" ].array;
var vA, vB, vC, x, y, z,
pA = new THREE.Vector3(),
pB = new THREE.Vector3(),
pC = new THREE.Vector3(),
cb = new THREE.Vector3(),
ab = new THREE.Vector3();
// indexed elements
if ( this.attributes[ "index" ] ) {
var indices = this.attributes[ "index" ].array;
var offsets = this.offsets;
for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
var start = offsets[ j ].start;
var count = offsets[ j ].count;
var index = offsets[ j ].index;
for ( i = start, il = start + count; i < il; i += 3 ) {
vA = index + indices[ i ];
vB = index + indices[ i + 1 ];
vC = index + indices[ i + 2 ];
x = positions[ vA * 3 ];
y = positions[ vA * 3 + 1 ];
z = positions[ vA * 3 + 2 ];
pA.set( x, y, z );
x = positions[ vB * 3 ];
y = positions[ vB * 3 + 1 ];
z = positions[ vB * 3 + 2 ];
pB.set( x, y, z );
x = positions[ vC * 3 ];
y = positions[ vC * 3 + 1 ];
z = positions[ vC * 3 + 2 ];
pC.set( x, y, z );
cb.subVectors( pC, pB );
ab.subVectors( pA, pB );
cb.cross( ab );
normals[ vA * 3 ] += cb.x;
normals[ vA * 3 + 1 ] += cb.y;
normals[ vA * 3 + 2 ] += cb.z;
normals[ vB * 3 ] += cb.x;
normals[ vB * 3 + 1 ] += cb.y;
normals[ vB * 3 + 2 ] += cb.z;
normals[ vC * 3 ] += cb.x;
normals[ vC * 3 + 1 ] += cb.y;
normals[ vC * 3 + 2 ] += cb.z;
}
}
// non-indexed elements (unconnected triangle soup)
} else {
for ( i = 0, il = positions.length; i < il; i += 9 ) {
x = positions[ i ];
y = positions[ i + 1 ];
z = positions[ i + 2 ];
pA.set( x, y, z );
x = positions[ i + 3 ];
y = positions[ i + 4 ];
z = positions[ i + 5 ];
pB.set( x, y, z );
x = positions[ i + 6 ];
y = positions[ i + 7 ];
z = positions[ i + 8 ];
pC.set( x, y, z );
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();
this.normalsNeedUpdate = true;
}
},
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;
}
},
computeTangents: function () {
// based on http://www.terathon.com/code/tangent.html
// (per vertex tangents)
if ( this.attributes[ "index" ] === undefined ||
this.attributes[ "position" ] === undefined ||
this.attributes[ "normal" ] === undefined ||
this.attributes[ "uv" ] === undefined ) {
console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
return;
}
var indices = this.attributes[ "index" ].array;
var positions = this.attributes[ "position" ].array;
var normals = this.attributes[ "normal" ].array;
var uvs = this.attributes[ "uv" ].array;
var nVertices = positions.length / 3;
if ( this.attributes[ "tangent" ] === undefined ) {
var nTangentElements = 4 * nVertices;
this.attributes[ "tangent" ] = {
itemSize: 4,
array: new Float32Array( nTangentElements )
};
}
var tangents = this.attributes[ "tangent" ].array;
var tan1 = [], tan2 = [];
for ( var k = 0; k < nVertices; k ++ ) {
tan1[ k ] = new THREE.Vector3();
tan2[ k ] = new THREE.Vector3();
}
var xA, yA, zA,
xB, yB, zB,
xC, yC, zC,
uA, vA,
uB, vB,
uC, vC,
x1, x2, y1, y2, z1, z2,
s1, s2, t1, t2, r;
var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
function handleTriangle( a, b, c ) {
xA = positions[ a * 3 ];
yA = positions[ a * 3 + 1 ];
zA = positions[ a * 3 + 2 ];
xB = positions[ b * 3 ];
yB = positions[ b * 3 + 1 ];
zB = positions[ b * 3 + 2 ];
xC = positions[ c * 3 ];
yC = positions[ c * 3 + 1 ];
zC = positions[ c * 3 + 2 ];
uA = uvs[ a * 2 ];
vA = uvs[ a * 2 + 1 ];
uB = uvs[ b * 2 ];
vB = uvs[ b * 2 + 1 ];
uC = uvs[ c * 2 ];
vC = uvs[ c * 2 + 1 ];
x1 = xB - xA;
x2 = xC - xA;
y1 = yB - yA;
y2 = yC - yA;
z1 = zB - zA;
z2 = zC - zA;
s1 = uB - uA;
s2 = uC - uA;
t1 = vB - vA;
t2 = vC - vA;
r = 1.0 / ( s1 * t2 - s2 * t1 );
sdir.set(
( t2 * x1 - t1 * x2 ) * r,
( t2 * y1 - t1 * y2 ) * r,
( t2 * z1 - t1 * z2 ) * r
);
tdir.set(
( s1 * x2 - s2 * x1 ) * r,
( s1 * y2 - s2 * y1 ) * r,
( s1 * z2 - s2 * z1 ) * r
);
tan1[ a ].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;
var offsets = this.offsets;
for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
var start = offsets[ j ].start;
var count = offsets[ j ].count;
var index = offsets[ j ].index;
for ( i = start, il = start + count; i < il; i += 3 ) {
iA = index + indices[ i ];
iB = index + indices[ i + 1 ];
iC = index + indices[ i + 2 ];
handleTriangle( iA, iB, iC );
}
}
var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
var n = new THREE.Vector3(), n2 = new THREE.Vector3();
var w, t, test;
function handleVertex( v ) {
n.x = normals[ v * 3 ];
n.y = normals[ v * 3 + 1 ];
n.z = normals[ v * 3 + 2 ];
n2.copy( n );
t = tan1[ v ];
// Gram-Schmidt orthogonalize
tmp.copy( t );
tmp.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 = offsets.length; j < jl; ++ j ) {
var start = offsets[ j ].start;
var count = offsets[ j ].count;
var index = offsets[ j ].index;
for ( i = start, il = start + count; i < il; i += 3 ) {
iA = index + indices[ i ];
iB = index + indices[ i + 1 ];
iC = index + indices[ i + 2 ];
handleVertex( iA );
handleVertex( iB );
handleVertex( iC );
}
}
},
/*
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;
},
/*
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 = {};
var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
for( var attr in this.attributes ) {
if(attr == 'index')
continue;
var sourceArray = this.attributes[attr].array;
for ( var i = 0, il = types.length; i < il; i++ ) {
var type = types[i];
if (sourceArray instanceof type) {
sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
break;
}
}
}
/* 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;
}
},
clone: function () {
var geometry = new THREE.BufferGeometry();
var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
for ( var attr in this.attributes ) {
var sourceAttr = this.attributes[ attr ];
var sourceArray = sourceAttr.array;
var attribute = {
itemSize: sourceAttr.itemSize,
array: null
};
for ( var i = 0, il = types.length; i < il; i ++ ) {
var type = types[ i ];
if ( sourceArray instanceof type ) {
attribute.array = new type( sourceArray );
break;
}
}
geometry.attributes[ attr ] = attribute;
}
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 );
/**
* @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 () {
this.id = THREE.GeometryIdCount ++;
this.uuid = THREE.Math.generateUUID();
this.name = '';
this.vertices = [];
this.colors = []; // one-to-one vertex colors, used in ParticleSystem 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.buffersNeedUpdate = 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();
}
face.centroid.applyMatrix4( matrix );
}
if ( this.boundingBox instanceof THREE.Box3 ) {
this.computeBoundingBox();
}
if ( this.boundingSphere instanceof THREE.Sphere ) {
this.computeBoundingSphere();
}
},
computeCentroids: function () {
var f, fl, face;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
face.centroid.set( 0, 0, 0 );
face.centroid.add( this.vertices[ face.a ] );
face.centroid.add( this.vertices[ face.b ] );
face.centroid.add( this.vertices[ face.c ] );
face.centroid.divideScalar( 3 );
}
},
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 ++ ) {
face = this.faces[ 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 );
},
/*
* 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;
},
// Geometry splitting
makeGroups: ( function () {
var geometryGroupCounter = 0;
return function ( usesFaceMaterial ) {
var f, fl, face, materialIndex,
groupHash, hash_map = {};
var numMorphTargets = this.morphTargets.length;
var numMorphNormals = this.morphNormals.length;
this.geometryGroups = {};
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
materialIndex = usesFaceMaterial ? face.materialIndex : 0;
if ( ! ( materialIndex in hash_map ) ) {
hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
}
groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
if ( ! ( groupHash in this.geometryGroups ) ) {
this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
}
if ( this.geometryGroups[ groupHash ].vertices + 3 > 65535 ) {
hash_map[ materialIndex ].counter += 1;
groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
if ( ! ( groupHash in this.geometryGroups ) ) {
this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
}
}
this.geometryGroups[ groupHash ].faces3.push( f );
this.geometryGroups[ groupHash ].vertices += 3;
}
this.geometryGroupsList = [];
for ( var g in this.geometryGroups ) {
this.geometryGroups[ g ].id = geometryGroupCounter ++;
this.geometryGroupsList.push( this.geometryGroups[ g ] );
}
};
} )(),
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;
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Geometry2 = function ( size ) {
THREE.BufferGeometry.call( this );
this.vertices = this.addAttribute( 'position', Float32Array, size, 3 ).array;
this.normals = this.addAttribute( 'normal', Float32Array, size, 3 ).array;
this.uvs = this.addAttribute( 'uv', Float32Array, size, 2 ).array;
this.boundingBox = null;
this.boundingSphere = null;
};
THREE.Geometry2.prototype = Object.create( THREE.BufferGeometry.prototype );
/**
* @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.matrixWorldInverse = new THREE.Matrix4();
this.projectionMatrix = new THREE.Matrix4();
};
THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
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;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
THREE.Camera.call( this );
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
this.near = ( near !== undefined ) ? near : 0.1;
this.far = ( far !== undefined ) ? far : 2000;
this.updateProjectionMatrix();
};
THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
};
THREE.OrthographicCamera.prototype.clone = function () {
var camera = new THREE.OrthographicCamera();
THREE.Camera.prototype.clone.call( this, camera );
camera.left = this.left;
camera.right = this.right;
camera.top = this.top;
camera.bottom = this.bottom;
camera.near = this.near;
camera.far = this.far;
return camera;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author greggman / http://games.greggman.com/
* @author zz85 / http://www.lab4games.net/zz85/blog
*/
THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
THREE.Camera.call( this );
this.fov = fov !== undefined ? fov : 50;
this.aspect = aspect !== undefined ? aspect : 1;
this.near = near !== undefined ? near : 0.1;
this.far = far !== undefined ? far : 2000;
this.updateProjectionMatrix();
};
THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
/**
* Uses Focal Length (in mm) to estimate and set FOV
* 35mm (fullframe) camera is used if frame size is not specified;
* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
*/
THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
if ( frameHeight === undefined ) frameHeight = 24;
this.fov = 2 * 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 () {
if ( this.fullWidth ) {
var aspect = this.fullWidth / this.fullHeight;
var top = Math.tan( THREE.Math.degToRad( this.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( this.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.fov = this.fov;
camera.aspect = this.aspect;
camera.near = this.near;
camera.far = this.far;
return camera;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Light = function ( color ) {
THREE.Object3D.call( this );
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;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.AmbientLight = function ( color ) {
THREE.Light.call( this, color );
};
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;
};
/**
* @author MPanknin / http://www.redplant.de/
* @author alteredq / http://alteredqualia.com/
*/
THREE.AreaLight = function ( color, intensity ) {
THREE.Light.call( this, color );
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 );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.DirectionalLight = function ( color, intensity ) {
THREE.Light.call( this, color );
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;
return light;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
THREE.Light.call( this, skyColor );
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;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.PointLight = function ( color, intensity, distance ) {
THREE.Light.call( this, color );
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;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
THREE.Light.call( this, color );
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;
return light;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Loader = function ( showStatus ) {
this.showStatus = showStatus;
this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
this.onLoadStart = function () {};
this.onLoadProgress = function () {};
this.onLoadComplete = function () {};
};
THREE.Loader.prototype = {
constructor: THREE.Loader,
crossOrigin: 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 / 1000 ).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 ] = THREE.Loader.prototype.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 _this = this;
function is_pow2( n ) {
var l = Math.log( n ) / Math.LN2;
return Math.floor( l ) == l;
}
function nearest_pow2( n ) {
var l = Math.log( n ) / Math.LN2;
return Math.pow( 2, Math.round( l ) );
}
function load_image( where, url ) {
loadStatus++;
var image = new Image();
image.onload = function () {
loadStatus--;
if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
var width = nearest_pow2( this.width );
var height = nearest_pow2( this.height );
where.image.width = width;
where.image.height = height;
where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
} else {
where.image = this;
}
where.needsUpdate = true;
};
if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin;
image.src = url;
}
function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
var isCompressed = /\.dds$/i.test( sourceFile );
var fullPath = texturePath + sourceFile;
if ( isCompressed ) {
var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
where[ name ] = texture;
} else {
var texture = document.createElement( 'canvas' );
where[ name ] = new THREE.Texture( texture );
}
where[ name ].sourceFile = sourceFile;
if( repeat ) {
where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
}
if ( offset ) {
where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
}
if ( wrap ) {
var wrapMap = {
"repeat": THREE.RepeatWrapping,
"mirror": THREE.MirroredRepeatWrapping
}
if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
}
if ( anisotropy ) {
where[ name ].anisotropy = anisotropy;
}
if ( ! isCompressed ) {
load_image( where[ name ], fullPath );
}
}
function rgb2hex( rgb ) {
return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
}
// defaults
var mtype = "MeshLambertMaterial";
var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
// parameters from model file
if ( m.shading ) {
var shading = m.shading.toLowerCase();
if ( shading === "phong" ) mtype = "MeshPhongMaterial";
else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
}
if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
mpars.blending = THREE[ m.blending ];
}
if ( m.transparent !== undefined || m.opacity < 1.0 ) {
mpars.transparent = m.transparent;
}
if ( m.depthTest !== undefined ) {
mpars.depthTest = m.depthTest;
}
if ( m.depthWrite !== undefined ) {
mpars.depthWrite = m.depthWrite;
}
if ( m.visible !== undefined ) {
mpars.visible = m.visible;
}
if ( m.flipSided !== undefined ) {
mpars.side = THREE.BackSide;
}
if ( m.doubleSided !== undefined ) {
mpars.side = THREE.DoubleSide;
}
if ( m.wireframe !== undefined ) {
mpars.wireframe = m.wireframe;
}
if ( m.vertexColors !== undefined ) {
if ( m.vertexColors === "face" ) {
mpars.vertexColors = THREE.FaceColors;
} else if ( m.vertexColors ) {
mpars.vertexColors = THREE.VertexColors;
}
}
// colors
if ( m.colorDiffuse ) {
mpars.color = rgb2hex( m.colorDiffuse );
} else if ( m.DbgColor ) {
mpars.color = m.DbgColor;
}
if ( m.colorSpecular ) {
mpars.specular = rgb2hex( m.colorSpecular );
}
if ( m.colorAmbient ) {
mpars.ambient = rgb2hex( m.colorAmbient );
}
// modifiers
if ( m.transparency ) {
mpars.opacity = m.transparency;
}
if ( m.specularCoef ) {
mpars.shininess = m.specularCoef;
}
// textures
if ( m.mapDiffuse && texturePath ) {
create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
}
if ( m.mapLight && texturePath ) {
create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
}
if ( m.mapBump && texturePath ) {
create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
}
if ( m.mapNormal && texturePath ) {
create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
}
if ( m.mapSpecular && texturePath ) {
create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
}
//
if ( m.mapBumpScale ) {
mpars.bumpScale = m.mapBumpScale;
}
// special case for normal mapped material
if ( m.mapNormal ) {
var shader = THREE.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;
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.XHRLoader = function ( manager ) {
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.XHRLoader.prototype = {
constructor: THREE.XHRLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var request = new XMLHttpRequest();
if ( onLoad !== undefined ) {
request.addEventListener( 'load', function ( event ) {
onLoad( event.target.responseText );
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;
request.open( 'GET', url, true );
request.send( null );
scope.manager.itemStart( url );
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.ImageLoader = function ( manager ) {
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.ImageLoader.prototype = {
constructor: THREE.ImageLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var image = document.createElement( 'img' );
if ( onLoad !== undefined ) {
image.addEventListener( 'load', function ( event ) {
scope.manager.itemEnd( url );
onLoad( this );
}, 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;
}
}
/**
* @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 ) {
loadStatus++;
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, function(a, b, c, d){ loadStatus--; callback(a, b, c, d); }, 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.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.computeCentroids();
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() {
if ( json.skinWeights ) {
for ( var i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
var x = json.skinWeights[ i ];
var y = json.skinWeights[ i + 1 ];
var z = 0;
var w = 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 += 2 ) {
var a = json.skinIndices[ i ];
var b = json.skinIndices[ i + 1 ];
var c = 0;
var d = 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 ) {
return { geometry: geometry };
} else {
var materials = this.initMaterials( json.materials, texturePath );
if ( this.needsTangents( materials ) ) {
geometry.computeTangents();
}
return { geometry: geometry, materials: materials };
}
};
/**
* @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();
/**
* @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 ) ) );
} );
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
},
parse: function ( json ) {
var geometry = new THREE.BufferGeometry();
var attributes = json.attributes;
var offsets = json.offsets;
var boundingSphere = json.boundingSphere;
for ( var key in attributes ) {
var attribute = attributes[ key ];
geometry.attributes[ key ] = {
itemSize: attribute.itemSize,
array: new self[ attribute.type ]( attribute.array )
}
}
if ( offsets !== undefined ) {
geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
}
if ( boundingSphere !== undefined ) {
geometry.boundingSphere = new THREE.Sphere(
new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
boundingSphere.radius
);
}
return geometry;
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Geometry2Loader = function ( manager ) {
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.Geometry2Loader.prototype = {
constructor: THREE.Geometry2Loader,
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 ) ) );
} );
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
},
parse: function ( json ) {
var geometry = new THREE.Geometry2( json.vertices.length / 3 );
var attributes = [ 'vertices', 'normals', 'uvs' ];
var boundingSphere = json.boundingSphere;
for ( var key in attributes ) {
var attribute = attributes[ key ];
geometry[ attribute ].set( json[ attribute ] );
}
if ( boundingSphere !== undefined ) {
geometry.boundingSphere = new THREE.Sphere(
new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
boundingSphere.radius
);
}
return geometry;
}
};
/**
* @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 ) ) );
} );
},
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.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
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;
}
};
/**
* @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 ) ) );
} );
},
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 geometry2Loader = new THREE.Geometry2Loader();
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': // DEPRECATED
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 'Geometry2':
geometry = geometry2Loader.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.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
}
if ( material === undefined ) {
console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
}
object = new THREE.Mesh( geometry, material );
break;
case 'Sprite':
var material = materials[ data.material ];
if ( material === undefined ) {
console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
}
object = new THREE.Sprite( material );
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;
}
}()
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.SceneLoader = function () {
this.onLoadStart = function () {};
this.onLoadProgress = function() {};
this.onLoadComplete = function () {};
this.callbackSync = function () {};
this.callbackProgress = function () {};
this.geometryHandlers = {};
this.hierarchyHandlers = {};
this.addGeometryHandler( "ascii", THREE.JSONLoader );
};
THREE.SceneLoader.prototype = {
constructor: THREE.SceneLoader,
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 ) {
scope.parse( JSON.parse( text ), onLoad, url );
} );
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
},
addGeometryHandler: function ( typeID, loaderClass ) {
this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
},
addHierarchyHandler: function ( typeID, loaderClass ) {
this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
},
parse: function ( json, callbackFinished, url ) {
var scope = this;
var urlBase = THREE.Loader.prototype.extractUrlBase( url );
var geometry, material, camera, fog,
texture, images, color,
light, hex, intensity,
counter_models, counter_textures,
total_models, total_textures,
result;
var target_array = [];
var data = json;
// async geometry loaders
for ( var typeID in this.geometryHandlers ) {
var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
}
// async hierachy loaders
for ( var typeID in this.hierarchyHandlers ) {
var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
}
counter_models = 0;
counter_textures = 0;
result = {
scene: new THREE.Scene(),
geometries: {},
face_materials: {},
materials: {},
textures: {},
objects: {},
cameras: {},
lights: {},
fogs: {},
empties: {},
groups: {}
};
if ( data.transform ) {
var position = data.transform.position,
rotation = data.transform.rotation,
scale = data.transform.scale;
if ( position ) {
result.scene.position.fromArray( position );
}
if ( rotation ) {
result.scene.rotation.fromArray( rotation );
}
if ( scale ) {
result.scene.scale.fromArray( scale );
}
if ( position || rotation || scale ) {
result.scene.updateMatrix();
result.scene.updateMatrixWorld();
}
}
function get_url( source_url, url_type ) {
if ( url_type == "relativeToHTML" ) {
return source_url;
} else {
return urlBase + source_url;
}
};
// toplevel loader function, delegates to handle_children
function handle_objects() {
handle_children( result.scene, data.objects );
}
// handle all the children from the loaded json and attach them to given parent
function handle_children( parent, children ) {
var mat, dst, pos, rot, scl, quat;
for ( var objID in children ) {
// check by id if child has already been handled,
// if not, create new object
var object = result.objects[ objID ];
var objJSON = children[ objID ];
if ( object === undefined ) {
// meshes
if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
if ( objJSON.loading === undefined ) {
var reservedTypes = {
"type": 1, "url": 1, "material": 1,
"position": 1, "rotation": 1, "scale" : 1,
"visible": 1, "children": 1, "userData": 1,
"skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
};
var loaderParameters = {};
for ( var parType in objJSON ) {
if ( ! ( parType in reservedTypes ) ) {
loaderParameters[ parType ] = objJSON[ parType ];
}
}
material = result.materials[ objJSON.material ];
objJSON.loading = true;
var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
// ColladaLoader
if ( loader.options ) {
loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
// UTF8Loader
// OBJLoader
} else {
loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
}
}
} else if ( objJSON.geometry !== undefined ) {
geometry = result.geometries[ objJSON.geometry ];
// geometry already loaded
if ( geometry ) {
var needsTangents = false;
material = result.materials[ objJSON.material ];
needsTangents = material instanceof THREE.ShaderMaterial;
pos = objJSON.position;
rot = objJSON.rotation;
scl = objJSON.scale;
mat = objJSON.matrix;
quat = objJSON.quaternion;
// use materials from the model file
// if there is no material specified in the object
if ( ! objJSON.material ) {
material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
}
// use materials from the model file
// if there is just empty face material
// (must create new material as each model has its own face material)
if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
}
if ( material instanceof THREE.MeshFaceMaterial ) {
for ( var i = 0; i < material.materials.length; i ++ ) {
needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
}
}
if ( needsTangents ) {
geometry.computeTangents();
}
if ( objJSON.skin ) {
object = new THREE.SkinnedMesh( geometry, material );
} else if ( objJSON.morph ) {
object = new THREE.MorphAnimMesh( geometry, material );
if ( objJSON.duration !== undefined ) {
object.duration = objJSON.duration;
}
if ( objJSON.time !== undefined ) {
object.time = objJSON.time;
}
if ( objJSON.mirroredLoop !== undefined ) {
object.mirroredLoop = objJSON.mirroredLoop;
}
if ( material.morphNormals ) {
geometry.computeMorphNormals();
}
} else {
object = new THREE.Mesh( geometry, material );
}
object.name = objID;
if ( mat ) {
object.matrixAutoUpdate = false;
object.matrix.set(
mat[0], mat[1], mat[2], mat[3],
mat[4], mat[5], mat[6], mat[7],
mat[8], mat[9], mat[10], mat[11],
mat[12], mat[13], mat[14], mat[15]
);
} else {
object.position.fromArray( pos );
if ( quat ) {
object.quaternion.fromArray( quat );
} else {
object.rotation.fromArray( rot );
}
object.scale.fromArray( scl );
}
object.visible = objJSON.visible;
object.castShadow = objJSON.castShadow;
object.receiveShadow = objJSON.receiveShadow;
parent.add( object );
result.objects[ objID ] = object;
}
// lights
} else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
var color = objJSON.color;
var intensity = objJSON.intensity;
var distance = objJSON.distance;
var position = objJSON.position;
var rotation = objJSON.rotation;
switch ( objJSON.type ) {
case 'AmbientLight':
light = new THREE.AmbientLight( color );
break;
case 'PointLight':
light = new THREE.PointLight( color, intensity, distance );
light.position.fromArray( position );
break;
case 'DirectionalLight':
light = new THREE.DirectionalLight( color, intensity );
light.position.fromArray( objJSON.direction );
break;
case 'SpotLight':
light = new THREE.SpotLight( color, intensity, distance, 1 );
light.angle = objJSON.angle;
light.position.fromArray( position );
light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
break;
case 'HemisphereLight':
light = new THREE.DirectionalLight( color, intensity, distance );
light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
break;
case 'AreaLight':
light = new THREE.AreaLight(color, intensity);
light.position.fromArray( position );
light.width = objJSON.size;
light.height = objJSON.size_y;
break;
}
parent.add( light );
light.name = objID;
result.lights[ objID ] = light;
result.objects[ objID ] = light;
// cameras
} else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
pos = objJSON.position;
rot = objJSON.rotation;
quat = objJSON.quaternion;
if ( objJSON.type === "PerspectiveCamera" ) {
camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
} else if ( objJSON.type === "OrthographicCamera" ) {
camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
}
camera.name = objID;
camera.position.fromArray( pos );
if ( quat !== undefined ) {
camera.quaternion.fromArray( quat );
} else if ( rot !== undefined ) {
camera.rotation.fromArray( rot );
}
parent.add( camera );
result.cameras[ objID ] = camera;
result.objects[ objID ] = camera;
// pure Object3D
} else {
pos = objJSON.position;
rot = objJSON.rotation;
scl = objJSON.scale;
quat = objJSON.quaternion;
object = new THREE.Object3D();
object.name = objID;
object.position.fromArray( pos );
if ( quat ) {
object.quaternion.fromArray( quat );
} else {
object.rotation.fromArray( rot );
}
object.scale.fromArray( scl );
object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
parent.add( object );
result.objects[ objID ] = object;
result.empties[ objID ] = object;
}
if ( object ) {
if ( objJSON.userData !== undefined ) {
for ( var key in objJSON.userData ) {
var value = objJSON.userData[ key ];
object.userData[ key ] = value;
}
}
if ( objJSON.groups !== undefined ) {
for ( var i = 0; i < objJSON.groups.length; i ++ ) {
var groupID = objJSON.groups[ i ];
if ( result.groups[ groupID ] === undefined ) {
result.groups[ groupID ] = [];
}
result.groups[ groupID ].push( objID );
}
}
}
}
if ( object !== undefined && objJSON.children !== undefined ) {
handle_children( object, objJSON.children );
}
}
};
function handle_mesh( geo, mat, id ) {
result.geometries[ id ] = geo;
result.face_materials[ id ] = mat;
handle_objects();
};
function handle_hierarchy( node, id, parent, material, obj ) {
var p = obj.position;
var r = obj.rotation;
var q = obj.quaternion;
var s = obj.scale;
node.position.fromArray( p );
if ( q ) {
node.quaternion.fromArray( q );
} else {
node.rotation.fromArray( r );
}
node.scale.fromArray( s );
// override children materials
// if object material was specified in JSON explicitly
if ( material ) {
node.traverse( function ( child ) {
child.material = material;
} );
}
// override children visibility
// with root node visibility as specified in JSON
var visible = ( obj.visible !== undefined ) ? obj.visible : true;
node.traverse( function ( child ) {
child.visible = visible;
} );
parent.add( node );
node.name = id;
result.objects[ id ] = node;
handle_objects();
};
function create_callback_geometry( id ) {
return function ( geo, mat ) {
geo.name = id;
handle_mesh( geo, mat, id );
counter_models -= 1;
scope.onLoadComplete();
async_callback_gate();
}
};
function create_callback_hierachy( id, parent, material, obj ) {
return function ( event ) {
var result;
// loaders which use EventDispatcher
if ( event.content ) {
result = event.content;
// ColladaLoader
} else if ( event.dae ) {
result = event.scene;
// UTF8Loader
} else {
result = event;
}
handle_hierarchy( result, id, parent, material, obj );
counter_models -= 1;
scope.onLoadComplete();
async_callback_gate();
}
};
function create_callback_embed( id ) {
return function ( geo, mat ) {
geo.name = id;
result.geometries[ id ] = geo;
result.face_materials[ id ] = mat;
}
};
function async_callback_gate() {
var progress = {
totalModels : total_models,
totalTextures : total_textures,
loadedModels : total_models - counter_models,
loadedTextures : total_textures - counter_textures
};
scope.callbackProgress( progress, result );
scope.onLoadProgress();
if ( counter_models === 0 && counter_textures === 0 ) {
finalize();
callbackFinished( result );
}
};
function finalize() {
// take care of targets which could be asynchronously loaded objects
for ( var i = 0; i < target_array.length; i ++ ) {
var ta = target_array[ i ];
var target = result.objects[ ta.targetName ];
if ( target ) {
ta.object.target = target;
} else {
// if there was error and target of specified name doesn't exist in the scene file
// create instead dummy target
// (target must be added to scene explicitly as parent is already added)
ta.object.target = new THREE.Object3D();
result.scene.add( ta.object.target );
}
ta.object.target.userData.targetInverse = ta.object;
}
};
var callbackTexture = function ( count ) {
counter_textures -= count;
async_callback_gate();
scope.onLoadComplete();
};
// must use this instead of just directly calling callbackTexture
// because of closure in the calling context loop
var generateTextureCallback = function ( count ) {
return function () {
callbackTexture( count );
};
};
function traverse_json_hierarchy( objJSON, callback ) {
callback( objJSON );
if ( objJSON.children !== undefined ) {
for ( var objChildID in objJSON.children ) {
traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
}
}
};
// first go synchronous elements
// fogs
var fogID, fogJSON;
for ( fogID in data.fogs ) {
fogJSON = data.fogs[ fogID ];
if ( fogJSON.type === "linear" ) {
fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
} else if ( fogJSON.type === "exp2" ) {
fog = new THREE.FogExp2( 0x000000, fogJSON.density );
}
color = fogJSON.color;
fog.color.setRGB( color[0], color[1], color[2] );
result.fogs[ fogID ] = fog;
}
// now come potentially asynchronous elements
// geometries
// count how many geometries will be loaded asynchronously
var geoID, geoJSON;
for ( geoID in data.geometries ) {
geoJSON = data.geometries[ geoID ];
if ( geoJSON.type in this.geometryHandlers ) {
counter_models += 1;
scope.onLoadStart();
}
}
// count how many hierarchies will be loaded asynchronously
for ( var objID in data.objects ) {
traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
counter_models += 1;
scope.onLoadStart();
}
});
}
total_models = counter_models;
for ( geoID in data.geometries ) {
geoJSON = data.geometries[ geoID ];
if ( geoJSON.type === "cube" ) {
geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
geometry.name = geoID;
result.geometries[ geoID ] = geometry;
} else if ( geoJSON.type === "plane" ) {
geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
geometry.name = geoID;
result.geometries[ geoID ] = geometry;
} else if ( geoJSON.type === "sphere" ) {
geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
geometry.name = geoID;
result.geometries[ geoID ] = geometry;
} else if ( geoJSON.type === "cylinder" ) {
geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
geometry.name = geoID;
result.geometries[ geoID ] = geometry;
} else if ( geoJSON.type === "torus" ) {
geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
geometry.name = geoID;
result.geometries[ geoID ] = geometry;
} else if ( geoJSON.type === "icosahedron" ) {
geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
geometry.name = geoID;
result.geometries[ geoID ] = geometry;
} else if ( geoJSON.type in this.geometryHandlers ) {
var loaderParameters = {};
for ( var parType in geoJSON ) {
if ( parType !== "type" && parType !== "url" ) {
loaderParameters[ parType ] = geoJSON[ parType ];
}
}
var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
} else if ( geoJSON.type === "embedded" ) {
var modelJson = data.embeds[ geoJSON.id ],
texture_path = "";
// pass metadata along to jsonLoader so it knows the format version
modelJson.metadata = data.metadata;
if ( modelJson ) {
var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
var model = jsonLoader.parse( modelJson, texture_path );
create_callback_embed( geoID )( model.geometry, model.materials );
}
}
}
// textures
// count how many textures will be loaded asynchronously
var textureID, textureJSON;
for ( textureID in data.textures ) {
textureJSON = data.textures[ textureID ];
if ( textureJSON.url instanceof Array ) {
counter_textures += textureJSON.url.length;
for( var n = 0; n < textureJSON.url.length; n ++ ) {
scope.onLoadStart();
}
} else {
counter_textures += 1;
scope.onLoadStart();
}
}
total_textures = counter_textures;
for ( textureID in data.textures ) {
textureJSON = data.textures[ textureID ];
if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
textureJSON.mapping = new THREE[ textureJSON.mapping ]();
}
if ( textureJSON.url instanceof Array ) {
var count = textureJSON.url.length;
var url_array = [];
for( var i = 0; i < count; i ++ ) {
url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
}
var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
if ( isCompressed ) {
texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
} else {
texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
}
} else {
var isCompressed = /\.dds$/i.test( textureJSON.url );
var fullUrl = get_url( textureJSON.url, data.urlBaseType );
var textureCallback = generateTextureCallback( 1 );
if ( isCompressed ) {
texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
} else {
texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
}
if ( THREE[ textureJSON.minFilter ] !== undefined )
texture.minFilter = THREE[ textureJSON.minFilter ];
if ( THREE[ textureJSON.magFilter ] !== undefined )
texture.magFilter = THREE[ textureJSON.magFilter ];
if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
if ( textureJSON.repeat ) {
texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
}
if ( textureJSON.offset ) {
texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
}
// handle wrap after repeat so that default repeat can be overriden
if ( textureJSON.wrap ) {
var wrapMap = {
"repeat": THREE.RepeatWrapping,
"mirror": THREE.MirroredRepeatWrapping
}
if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
}
}
result.textures[ textureID ] = texture;
}
// materials
var matID, matJSON;
var parID;
for ( matID in data.materials ) {
matJSON = data.materials[ matID ];
for ( parID in matJSON.parameters ) {
if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
} else if ( parID === "shading" ) {
matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
} else if ( parID === "side" ) {
if ( matJSON.parameters[ parID ] == "double" ) {
matJSON.parameters[ parID ] = THREE.DoubleSide;
} else if ( matJSON.parameters[ parID ] == "back" ) {
matJSON.parameters[ parID ] = THREE.BackSide;
} else {
matJSON.parameters[ parID ] = THREE.FrontSide;
}
} else if ( parID === "blending" ) {
matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
} else if ( parID === "combine" ) {
matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
} else if ( parID === "vertexColors" ) {
if ( matJSON.parameters[ parID ] == "face" ) {
matJSON.parameters[ parID ] = THREE.FaceColors;
// default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
} else if ( matJSON.parameters[ parID ] ) {
matJSON.parameters[ parID ] = THREE.VertexColors;
}
} else if ( parID === "wrapRGB" ) {
var v3 = matJSON.parameters[ parID ];
matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
}
}
if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
matJSON.parameters.transparent = true;
}
if ( matJSON.parameters.normalMap ) {
var shader = THREE.ShaderLib[ "normalmap" ];
var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
var diffuse = matJSON.parameters.color;
var specular = matJSON.parameters.specular;
var ambient = matJSON.parameters.ambient;
var shininess = matJSON.parameters.shininess;
uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
if ( matJSON.parameters.normalScale ) {
uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
}
if ( matJSON.parameters.map ) {
uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
uniforms[ "enableDiffuse" ].value = true;
}
if ( matJSON.parameters.envMap ) {
uniforms[ "tCube" ].value = matJSON.parameters.envMap;
uniforms[ "enableReflection" ].value = true;
uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
}
if ( matJSON.parameters.lightMap ) {
uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
uniforms[ "enableAO" ].value = true;
}
if ( matJSON.parameters.specularMap ) {
uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
uniforms[ "enableSpecular" ].value = true;
}
if ( matJSON.parameters.displacementMap ) {
uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
uniforms[ "enableDisplacement" ].value = true;
uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
}
uniforms[ "diffuse" ].value.setHex( diffuse );
uniforms[ "specular" ].value.setHex( specular );
uniforms[ "ambient" ].value.setHex( ambient );
uniforms[ "shininess" ].value = shininess;
if ( matJSON.parameters.opacity ) {
uniforms[ "opacity" ].value = matJSON.parameters.opacity;
}
var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
material = new THREE.ShaderMaterial( parameters );
} else {
material = new THREE[ matJSON.type ]( matJSON.parameters );
}
material.name = matID;
result.materials[ matID ] = material;
}
// second pass through all materials to initialize MeshFaceMaterials
// that could be referring to other materials out of order
for ( matID in data.materials ) {
matJSON = data.materials[ matID ];
if ( matJSON.parameters.materials ) {
var materialArray = [];
for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
var label = matJSON.parameters.materials[ i ];
materialArray.push( result.materials[ label ] );
}
result.materials[ matID ].materials = materialArray;
}
}
// objects ( synchronous init of procedural primitives )
handle_objects();
// defaults
if ( result.cameras && data.defaults.camera ) {
result.currentCamera = result.cameras[ data.defaults.camera ];
}
if ( result.fogs && data.defaults.fog ) {
result.scene.fog = result.fogs[ data.defaults.fog ];
}
// synchronous callback
scope.callbackSync( result );
// just in case there are no async elements
async_callback_gate();
}
}
/**
* @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 );
}
} );
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Material = function () {
this.id = THREE.MaterialIdCount ++;
this.uuid = THREE.Math.generateUUID();
this.name = '';
this.side = THREE.FrontSide;
this.opacity = 1;
this.transparent = false;
this.blending = THREE.NormalBlending;
this.blendSrc = THREE.SrcAlphaFactor;
this.blendDst = THREE.OneMinusSrcAlphaFactor;
this.blendEquation = THREE.AddEquation;
this.depthTest = true;
this.depthWrite = true;
this.polygonOffset = false;
this.polygonOffsetFactor = 0;
this.polygonOffsetUnits = 0;
this.alphaTest = 0;
this.overdraw = 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;
}
}
}
},
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;
/**
* @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.color = new THREE.Color( 0xffffff );
this.linewidth = 1;
this.linecap = 'round';
this.linejoin = 'round';
this.vertexColors = false;
this.fog = true;
this.setValues( parameters );
};
THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.LineBasicMaterial.prototype.clone = function () {
var material = new THREE.LineBasicMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.linewidth = this.linewidth;
material.linecap = this.linecap;
material.linejoin = this.linejoin;
material.vertexColors = this.vertexColors;
material.fog = this.fog;
return material;
};
/**
* @author 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.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;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
*
* specularMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* 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.color = new THREE.Color( 0xffffff ); // emissive
this.map = null;
this.lightMap = null;
this.specularMap = null;
this.envMap = null;
this.combine = THREE.MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.fog = true;
this.shading = THREE.SmoothShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.vertexColors = THREE.NoColors;
this.skinning = false;
this.morphTargets = false;
this.setValues( parameters );
};
THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshBasicMaterial.prototype.clone = function () {
var material = new THREE.MeshBasicMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.map = this.map;
material.lightMap = this.lightMap;
material.specularMap = this.specularMap;
material.envMap = this.envMap;
material.combine = this.combine;
material.reflectivity = this.reflectivity;
material.refractionRatio = this.refractionRatio;
material.fog = this.fog;
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
material.wireframeLinecap = this.wireframeLinecap;
material.wireframeLinejoin = this.wireframeLinejoin;
material.vertexColors = this.vertexColors;
material.skinning = this.skinning;
material.morphTargets = this.morphTargets;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* ambient: <hex>,
* emissive: <hex>,
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
*
* specularMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* 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.color = new THREE.Color( 0xffffff ); // diffuse
this.ambient = new THREE.Color( 0xffffff );
this.emissive = new THREE.Color( 0x000000 );
this.wrapAround = false;
this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
this.map = null;
this.lightMap = null;
this.specularMap = null;
this.envMap = null;
this.combine = THREE.MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.fog = true;
this.shading = THREE.SmoothShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.vertexColors = THREE.NoColors;
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
};
THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshLambertMaterial.prototype.clone = function () {
var material = new THREE.MeshLambertMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.ambient.copy( this.ambient );
material.emissive.copy( this.emissive );
material.wrapAround = this.wrapAround;
material.wrapRGB.copy( this.wrapRGB );
material.map = this.map;
material.lightMap = this.lightMap;
material.specularMap = this.specularMap;
material.envMap = this.envMap;
material.combine = this.combine;
material.reflectivity = this.reflectivity;
material.refractionRatio = this.refractionRatio;
material.fog = this.fog;
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
material.wireframeLinecap = this.wireframeLinecap;
material.wireframeLinejoin = this.wireframeLinejoin;
material.vertexColors = this.vertexColors;
material.skinning = this.skinning;
material.morphTargets = this.morphTargets;
material.morphNormals = this.morphNormals;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* ambient: <hex>,
* emissive: <hex>,
* specular: <hex>,
* shininess: <float>,
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
*
* bumpMap: new THREE.Texture( <Image> ),
* bumpScale: <float>,
*
* normalMap: new THREE.Texture( <Image> ),
* normalScale: <Vector2>,
*
* specularMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* 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.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.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.envMap = this.envMap;
material.combine = this.combine;
material.reflectivity = this.reflectivity;
material.refractionRatio = this.refractionRatio;
material.fog = this.fog;
material.shading = this.shading;
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
material.wireframeLinecap = this.wireframeLinecap;
material.wireframeLinejoin = this.wireframeLinejoin;
material.vertexColors = this.vertexColors;
material.skinning = this.skinning;
material.morphTargets = this.morphTargets;
material.morphNormals = this.morphNormals;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* opacity: <float>,
*
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* depthWrite: <bool>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>
* }
*/
THREE.MeshDepthMaterial = function ( parameters ) {
THREE.Material.call( this );
this.wireframe = false;
this.wireframeLinewidth = 1;
this.setValues( parameters );
};
THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshDepthMaterial.prototype.clone = function () {
var material = new THREE.MeshDepthMaterial();
THREE.Material.prototype.clone.call( this, material );
material.wireframe = this.wireframe;
material.wireframeLinewidth = this.wireframeLinewidth;
return material;
};
/**
* @author mrdoob / http://mrdoob.com/
*
* parameters = {
* opacity: <float>,
*
* shading: THREE.FlatShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* depthWrite: <bool>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>
* }
*/
THREE.MeshNormalMaterial = function ( parameters ) {
THREE.Material.call( this, parameters );
this.shading = THREE.FlatShading;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.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;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.MeshFaceMaterial = function ( materials ) {
this.materials = materials instanceof Array ? materials : [];
};
THREE.MeshFaceMaterial.prototype.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;
};
/**
* @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.ParticleSystemMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff );
this.map = null;
this.size = 1;
this.sizeAttenuation = true;
this.vertexColors = false;
this.fog = true;
this.setValues( parameters );
};
THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.ParticleSystemMaterial.prototype.clone = function () {
var material = new THREE.ParticleSystemMaterial();
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 = THREE.ParticleSystemMaterial;
/**
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* fragmentShader: <string>,
* vertexShader: <string>,
*
* uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
*
* defines: { "label" : "value" },
*
* shading: THREE.SmoothShading,
* blending: THREE.NormalBlending,
* depthTest: <bool>,
* 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.fragmentShader = "void main() {}";
this.vertexShader = "void main() {}";
this.uniforms = {};
this.defines = {};
this.attributes = null;
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 ]
};
// By default, bind position to attribute index 0. In WebGL, attribute 0
// should always be used to avoid potentially expensive emulation.
this.index0AttributeName = "position";
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;
};
/**
* @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 );
// defaults
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;
};
/**
* @author mrdoob / http://mrdoob.com/
*
* parameters = {
* color: <hex>,
* program: <function>,
* opacity: <float>,
* blending: THREE.NormalBlending
* }
*/
THREE.SpriteCanvasMaterial = function ( parameters ) {
THREE.Material.call( this );
this.color = new THREE.Color( 0xffffff );
this.program = function ( context, color ) {};
this.setValues( parameters );
};
THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.SpriteCanvasMaterial.prototype.clone = function () {
var material = new THREE.SpriteCanvasMaterial();
THREE.Material.prototype.clone.call( this, material );
material.color.copy( this.color );
material.program = this.program;
return material;
};
// backwards compatibility
THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
/**
* @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 ) {
this.id = THREE.TextureIdCount ++;
this.uuid = THREE.Math.generateUUID();
this.name = '';
this.image = image;
this.mipmaps = [];
this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
this.format = format !== undefined ? format : THREE.RGBAFormat;
this.type = type !== undefined ? type : THREE.UnsignedByteType;
this.offset = new THREE.Vector2( 0, 0 );
this.repeat = new THREE.Vector2( 1, 1 );
this.generateMipmaps = true;
this.premultiplyAlpha = false;
this.flipY = true;
this.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.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;
/**
* @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;
this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
};
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;
};
/**
* @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;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ParticleSystem = function ( geometry, material ) {
THREE.Object3D.call( this );
this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
this.sortParticles = false;
this.frustumCulled = false;
};
THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
THREE.ParticleSystem.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
object.sortParticles = this.sortParticles;
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Line = function ( geometry, material, type ) {
THREE.Object3D.call( this );
this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
this.type = ( type !== undefined ) ? type : THREE.LineStrip;
};
THREE.LineStrip = 0;
THREE.LinePieces = 1;
THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
THREE.Line.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author jonobr1 / http://jonobr1.com/
*/
THREE.Mesh = function ( geometry, material ) {
THREE.Object3D.call( this );
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.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Bone = function( belongsToSkin ) {
THREE.Object3D.call( this );
this.skin = belongsToSkin;
this.skinMatrix = new THREE.Matrix4();
};
THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
// update local
if ( this.matrixAutoUpdate ) {
forceUpdate |= this.updateMatrix();
}
// update skin matrix
if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
if( parentSkinMatrix ) {
this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
} else {
this.skinMatrix.copy( this.matrix );
}
this.matrixWorldNeedsUpdate = false;
forceUpdate = true;
}
// update children
var child, i, l = this.children.length;
for ( i = 0; i < l; i ++ ) {
this.children[ i ].update( this.skinMatrix, forceUpdate );
}
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
THREE.Mesh.call( this, geometry, material );
//
this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
// init bones
this.identityMatrix = new THREE.Matrix4();
this.bones = [];
this.boneMatrices = [];
var b, bone, gbone, p, q, s;
if ( this.geometry && this.geometry.bones !== undefined ) {
for ( b = 0; b < this.geometry.bones.length; b ++ ) {
gbone = this.geometry.bones[ b ];
p = gbone.pos;
q = gbone.rotq;
s = gbone.scl;
bone = this.addBone();
bone.name = gbone.name;
bone.position.set( p[0], p[1], p[2] );
bone.quaternion.set( q[0], q[1], q[2], q[3] );
if ( s !== undefined ) {
bone.scale.set( s[0], s[1], s[2] );
} else {
bone.scale.set( 1, 1, 1 );
}
}
for ( b = 0; b < this.bones.length; b ++ ) {
gbone = this.geometry.bones[ b ];
bone = this.bones[ b ];
if ( gbone.parent === -1 ) {
this.add( bone );
} else {
this.bones[ gbone.parent ].add( bone );
}
}
//
var nBones = this.bones.length;
if ( this.useVertexTexture ) {
// layout (1 matrix = 4 pixels)
// RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
// with 8x8 pixel texture max 16 bones (8 * 8 / 4)
// 16x16 pixel texture max 64 bones (16 * 16 / 4)
// 32x32 pixel texture max 256 bones (32 * 32 / 4)
// 64x64 pixel texture max 1024 bones (64 * 64 / 4)
var size;
if ( nBones > 256 )
size = 64;
else if ( nBones > 64 )
size = 32;
else if ( nBones > 16 )
size = 16;
else
size = 8;
this.boneTextureWidth = size;
this.boneTextureHeight = size;
this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
this.boneTexture.minFilter = THREE.NearestFilter;
this.boneTexture.magFilter = THREE.NearestFilter;
this.boneTexture.generateMipmaps = false;
this.boneTexture.flipY = false;
} else {
this.boneMatrices = new Float32Array( 16 * nBones );
}
this.pose();
}
};
THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.SkinnedMesh.prototype.addBone = function( bone ) {
if ( bone === undefined ) {
bone = new THREE.Bone( this );
}
this.bones.push( bone );
return bone;
};
THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
var offsetMatrix = new THREE.Matrix4();
return function ( force ) {
this.matrixAutoUpdate && this.updateMatrix();
// update matrixWorld
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent ) {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
} else {
this.matrixWorld.copy( this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
if ( child instanceof THREE.Bone ) {
child.update( this.identityMatrix, false );
} else {
child.updateMatrixWorld( true );
}
}
// make a snapshot of the bones' rest position
if ( this.boneInverses == undefined ) {
this.boneInverses = [];
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
var inverse = new THREE.Matrix4();
inverse.getInverse( this.bones[ b ].skinMatrix );
this.boneInverses.push( inverse );
}
}
// flatten bone matrices to array
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
// compute the offset between the current and the original transform;
// TODO: we could get rid of this multiplication step if the skinMatrix
// was already representing the offset; however, this requires some
// major changes to the animation system
offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
}
if ( this.useVertexTexture ) {
this.boneTexture.needsUpdate = true;
}
};
}();
THREE.SkinnedMesh.prototype.pose = function () {
this.updateMatrixWorld( true );
this.normalizeSkinWeights();
};
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.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;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MorphAnimMesh = function ( geometry, material ) {
THREE.Mesh.call( this, geometry, material );
// API
this.duration = 1000; // milliseconds
this.mirroredLoop = false;
this.time = 0;
// internals
this.lastKeyframe = 0;
this.currentKeyframe = 0;
this.direction = 1;
this.directionBackwards = false;
this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
};
THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
this.startKeyframe = start;
this.endKeyframe = end;
this.length = this.endKeyframe - this.startKeyframe + 1;
};
THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
this.direction = 1;
this.directionBackwards = false;
};
THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
this.direction = -1;
this.directionBackwards = true;
};
THREE.MorphAnimMesh.prototype.parseAnimations = function () {
var geometry = this.geometry;
if ( ! geometry.animations ) geometry.animations = {};
var firstAnimation, animations = geometry.animations;
var pattern = /([a-z]+)(\d+)/;
for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
var morph = geometry.morphTargets[ i ];
var parts = morph.name.match( pattern );
if ( parts && parts.length > 1 ) {
var label = parts[ 1 ];
var num = parts[ 2 ];
if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
var animation = animations[ label ];
if ( i < animation.start ) animation.start = i;
if ( i > animation.end ) animation.end = i;
if ( ! firstAnimation ) firstAnimation = label;
}
}
geometry.firstAnimation = firstAnimation;
};
THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
if ( ! this.geometry.animations ) this.geometry.animations = {};
this.geometry.animations[ label ] = { start: start, end: end };
};
THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
var animation = this.geometry.animations[ label ];
if ( animation ) {
this.setFrameRange( animation.start, animation.end );
this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
this.time = 0;
} else {
console.warn( "animation[" + label + "] undefined" );
}
};
THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
var frameTime = this.duration / this.length;
this.time += this.direction * delta;
if ( this.mirroredLoop ) {
if ( this.time > this.duration || this.time < 0 ) {
this.direction *= -1;
if ( this.time > this.duration ) {
this.time = this.duration;
this.directionBackwards = true;
}
if ( this.time < 0 ) {
this.time = 0;
this.directionBackwards = false;
}
}
} else {
this.time = this.time % this.duration;
if ( this.time < 0 ) this.time += this.duration;
}
var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
if ( keyframe !== this.currentKeyframe ) {
this.morphTargetInfluences[ this.lastKeyframe ] = 0;
this.morphTargetInfluences[ this.currentKeyframe ] = 1;
this.morphTargetInfluences[ keyframe ] = 0;
this.lastKeyframe = this.currentKeyframe;
this.currentKeyframe = keyframe;
}
var mix = ( this.time % frameTime ) / frameTime;
if ( this.directionBackwards ) {
mix = 1 - mix;
}
this.morphTargetInfluences[ this.currentKeyframe ] = mix;
this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
};
THREE.MorphAnimMesh.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
object.duration = this.duration;
object.mirroredLoop = this.mirroredLoop;
object.time = this.time;
object.lastKeyframe = this.lastKeyframe;
object.currentKeyframe = this.currentKeyframe;
object.direction = this.direction;
object.directionBackwards = this.directionBackwards;
THREE.Mesh.prototype.clone.call( this, object );
return object;
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
THREE.LOD = function () {
THREE.Object3D.call( this );
this.objects = [];
};
THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
THREE.LOD.prototype.addLevel = function ( object, distance ) {
if ( distance === undefined ) distance = 0;
distance = Math.abs( distance );
for ( var l = 0; l < this.objects.length; l ++ ) {
if ( distance < this.objects[ l ].distance ) {
break;
}
}
this.objects.splice( l, 0, { distance: distance, object: object } );
this.add( object );
};
THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
if ( distance < this.objects[ i ].distance ) {
break;
}
}
return this.objects[ i - 1 ].object;
};
THREE.LOD.prototype.update = function () {
var v1 = new THREE.Vector3();
var v2 = new THREE.Vector3();
return function ( camera ) {
if ( this.objects.length > 1 ) {
v1.setFromMatrixPosition( camera.matrixWorld );
v2.setFromMatrixPosition( this.matrixWorld );
var distance = v1.distanceTo( v2 );
this.objects[ 0 ].object.visible = true;
for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
if ( distance >= this.objects[ i ].distance ) {
this.objects[ i - 1 ].object.visible = false;
this.objects[ i ].object.visible = true;
} else {
break;
}
}
for( ; i < l; i ++ ) {
this.objects[ i ].object.visible = false;
}
}
};
}();
THREE.LOD.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.LOD();
THREE.Object3D.prototype.clone.call( this, object );
for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
var x = this.objects[i].object.clone();
x.visible = i === 0;
object.addLevel( x, this.objects[i].distance );
}
return object;
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Sprite = ( function () {
var geometry = new THREE.Geometry2( 3 );
geometry.vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
return function ( material ) {
THREE.Object3D.call( this );
this.geometry = geometry;
this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
};
} )();
THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
/*
* Custom update matrix
*/
THREE.Sprite.prototype.updateMatrix = function () {
this.matrix.compose( this.position, this.quaternion, this.scale );
this.matrixWorldNeedsUpdate = true;
};
THREE.Sprite.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Sprite( this.material );
THREE.Object3D.prototype.clone.call( this, object );
return object;
};
// Backwards compatibility
THREE.Particle = THREE.Sprite;
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Scene = function () {
THREE.Object3D.call( this );
this.fog = null;
this.overrideMaterial = null;
this.autoUpdate = true; // checked by the renderer
this.matrixAutoUpdate = false;
this.__lights = [];
this.__objectsAdded = [];
this.__objectsRemoved = [];
};
THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
THREE.Scene.prototype.__addObject = function ( object ) {
if ( object instanceof THREE.Light ) {
if ( this.__lights.indexOf( object ) === - 1 ) {
this.__lights.push( object );
}
if ( object.target && object.target.parent === undefined ) {
this.add( object.target );
}
} else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
this.__objectsAdded.push( object );
// check if previously removed
var i = this.__objectsRemoved.indexOf( object );
if ( i !== -1 ) {
this.__objectsRemoved.splice( i, 1 );
}
}
this.dispatchEvent( { type: 'objectAdded', object: object } );
object.dispatchEvent( { type: 'addedToScene', scene: this } );
for ( var c = 0; c < object.children.length; c ++ ) {
this.__addObject( object.children[ c ] );
}
};
THREE.Scene.prototype.__removeObject = function ( object ) {
if ( object instanceof THREE.Light ) {
var i = this.__lights.indexOf( object );
if ( i !== -1 ) {
this.__lights.splice( i, 1 );
}
if ( object.shadowCascadeArray ) {
for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
this.__removeObject( object.shadowCascadeArray[ x ] );
}
}
} else if ( !( object instanceof THREE.Camera ) ) {
this.__objectsRemoved.push( object );
// check if previously added
var i = this.__objectsAdded.indexOf( object );
if ( i !== -1 ) {
this.__objectsAdded.splice( i, 1 );
}
}
this.dispatchEvent( { type: 'objectRemoved', object: object } );
object.dispatchEvent( { type: 'removedFromScene', scene: this } );
for ( var c = 0; c < object.children.length; c ++ ) {
this.__removeObject( object.children[ c ] );
}
};
THREE.Scene.prototype.clone = function ( object ) {
if ( object === undefined ) object = new THREE.Scene();
THREE.Object3D.prototype.clone.call(this, object);
if ( this.fog !== null ) object.fog = this.fog.clone();
if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
object.autoUpdate = this.autoUpdate;
object.matrixAutoUpdate = this.matrixAutoUpdate;
return object;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Fog = function ( color, near, far ) {
this.name = '';
this.color = new THREE.Color( color );
this.near = ( near !== undefined ) ? near : 1;
this.far = ( far !== undefined ) ? far : 1000;
};
THREE.Fog.prototype.clone = function () {
return new THREE.Fog( this.color.getHex(), this.near, this.far );
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.FogExp2 = function ( color, density ) {
this.name = '';
this.color = new THREE.Color( color );
this.density = ( density !== undefined ) ? density : 0.00025;
};
THREE.FogExp2.prototype.clone = function () {
return new THREE.FogExp2( this.color.getHex(), this.density );
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.CanvasRenderer = function ( parameters ) {
console.log( 'THREE.CanvasRenderer', THREE.REVISION );
var smoothstep = THREE.Math.smoothstep;
parameters = parameters || {};
var _this = this,
_renderData, _elements, _lights,
_projector = new THREE.Projector(),
_canvas = parameters.canvas !== undefined
? parameters.canvas
: document.createElement( 'canvas' ),
_canvasWidth = _canvas.width,
_canvasHeight = _canvas.height,
_canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
_canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
_context = _canvas.getContext( '2d', {
alpha: parameters.alpha === true
} ),
_clearColor = new THREE.Color( 0x000000 ),
_clearAlpha = 0,
_contextGlobalAlpha = 1,
_contextGlobalCompositeOperation = 0,
_contextStrokeStyle = null,
_contextFillStyle = null,
_contextLineWidth = null,
_contextLineCap = null,
_contextLineJoin = null,
_contextDashSize = null,
_contextGapSize = 0,
_camera,
_v1, _v2, _v3, _v4,
_v5 = new THREE.RenderableVertex(),
_v6 = new THREE.RenderableVertex(),
_v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
_v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
_color = new THREE.Color(),
_color1 = new THREE.Color(),
_color2 = new THREE.Color(),
_color3 = new THREE.Color(),
_color4 = new THREE.Color(),
_diffuseColor = new THREE.Color(),
_emissiveColor = new THREE.Color(),
_lightColor = new THREE.Color(),
_patterns = {},
_near, _far,
_image, _uvs,
_uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
_clipBox = new THREE.Box2(),
_clearBox = new THREE.Box2(),
_elemBox = new THREE.Box2(),
_ambientLight = new THREE.Color(),
_directionalLights = new THREE.Color(),
_pointLights = new THREE.Color(),
_vector3 = new THREE.Vector3(), // Needed for PointLight
_normal = new THREE.Vector3(),
_normalViewMatrix = new THREE.Matrix3(),
_pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
_gradientMap, _gradientMapContext, _gradientMapQuality = 16;
_pixelMap = document.createElement( 'canvas' );
_pixelMap.width = _pixelMap.height = 2;
_pixelMapContext = _pixelMap.getContext( '2d' );
_pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
_pixelMapContext.fillRect( 0, 0, 2, 2 );
_pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
_pixelMapData = _pixelMapImage.data;
_gradientMap = document.createElement( 'canvas' );
_gradientMap.width = _gradientMap.height = _gradientMapQuality;
_gradientMapContext = _gradientMap.getContext( '2d' );
_gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
_gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
_gradientMapQuality --; // Fix UVs
// dash+gap fallbacks for Firefox and everything else
if ( _context.setLineDash === undefined ) {
if ( _context.mozDash !== undefined ) {
_context.setLineDash = function ( values ) {
_context.mozDash = values[ 0 ] !== null ? values : null;
}
} else {
_context.setLineDash = function () {}
}
}
this.domElement = _canvas;
this.devicePixelRatio = parameters.devicePixelRatio !== undefined
? parameters.devicePixelRatio
: self.devicePixelRatio !== undefined
? self.devicePixelRatio
: 1;
this.autoClear = true;
this.sortObjects = true;
this.sortElements = true;
this.info = {
render: {
vertices: 0,
faces: 0
}
}
// WebGLRenderer compatibility
this.supportsVertexTextures = function () {};
this.setFaceCulling = function () {};
this.setSize = function ( width, height, updateStyle ) {
_canvasWidth = width * this.devicePixelRatio;
_canvasHeight = height * this.devicePixelRatio;
_canvasWidthHalf = Math.floor( _canvasWidth / 2 );
_canvasHeightHalf = Math.floor( _canvasHeight / 2 );
_canvas.width = _canvasWidth;
_canvas.height = _canvasHeight;
if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
_canvas.style.width = width + 'px';
_canvas.style.height = height + 'px';
}
_clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
_clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
_clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
_clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
_contextGlobalAlpha = 1;
_contextGlobalCompositeOperation = 0;
_contextStrokeStyle = null;
_contextFillStyle = null;
_contextLineWidth = null;
_contextLineCap = null;
_contextLineJoin = null;
};
this.setClearColor = function ( color, alpha ) {
_clearColor.set( color );
_clearAlpha = alpha !== undefined ? alpha : 1;
_clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
_clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
};
this.setClearColorHex = function ( hex, alpha ) {
console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
this.setClearColor( hex, alpha );
};
this.getMaxAnisotropy = function () {
return 0;
};
this.clear = function () {
_context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
if ( _clearBox.empty() === false ) {
_clearBox.intersect( _clipBox );
_clearBox.expandByScalar( 2 );
if ( _clearAlpha < 1 ) {
_context.clearRect(
_clearBox.min.x | 0,
_clearBox.min.y | 0,
( _clearBox.max.x - _clearBox.min.x ) | 0,
( _clearBox.max.y - _clearBox.min.y ) | 0
);
}
if ( _clearAlpha > 0 ) {
setBlending( THREE.NormalBlending );
setOpacity( 1 );
setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
_context.fillRect(
_clearBox.min.x | 0,
_clearBox.min.y | 0,
( _clearBox.max.x - _clearBox.min.x ) | 0,
( _clearBox.max.y - _clearBox.min.y ) | 0
);
}
_clearBox.makeEmpty();
}
};
// compatibility
this.clearColor = function () {};
this.clearDepth = function () {};
this.clearStencil = function () {};
this.render = function ( scene, camera ) {
if ( camera instanceof THREE.Camera === false ) {
console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
return;
}
if ( this.autoClear === true ) this.clear();
_context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
_this.info.render.vertices = 0;
_this.info.render.faces = 0;
_renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
_elements = _renderData.elements;
_lights = _renderData.lights;
_camera = camera;
_normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
/* DEBUG
setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
_context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
*/
calculateLights();
for ( var e = 0, el = _elements.length; e < el; e ++ ) {
var element = _elements[ e ];
var material = element.material;
if ( material === undefined || material.visible === false ) continue;
_elemBox.makeEmpty();
if ( element instanceof THREE.RenderableSprite ) {
_v1 = element;
_v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
renderSprite( _v1, element, material );
} else if ( element instanceof THREE.RenderableLine ) {
_v1 = element.v1; _v2 = element.v2;
_v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
_v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
_elemBox.setFromPoints( [
_v1.positionScreen,
_v2.positionScreen
] );
if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
renderLine( _v1, _v2, element, material );
}
} else if ( element instanceof THREE.RenderableFace ) {
_v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
_v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
_v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
_v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
if ( material.overdraw > 0 ) {
expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
}
_elemBox.setFromPoints( [
_v1.positionScreen,
_v2.positionScreen,
_v3.positionScreen
] );
if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
}
}
/* DEBUG
setLineWidth( 1 );
setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
_context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
*/
_clearBox.union( _elemBox );
}
/* DEBUG
setLineWidth( 1 );
setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
_context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
*/
_context.setTransform( 1, 0, 0, 1, 0, 0 );
};
//
function calculateLights() {
_ambientLight.setRGB( 0, 0, 0 );
_directionalLights.setRGB( 0, 0, 0 );
_pointLights.setRGB( 0, 0, 0 );
for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
var light = _lights[ l ];
var lightColor = light.color;
if ( light instanceof THREE.AmbientLight ) {
_ambientLight.add( lightColor );
} else if ( light instanceof THREE.DirectionalLight ) {
// for sprites
_directionalLights.add( lightColor );
} else if ( light instanceof THREE.PointLight ) {
// for sprites
_pointLights.add( lightColor );
}
}
}
function calculateLight( position, normal, color ) {
for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
var light = _lights[ l ];
_lightColor.copy( light.color );
if ( light instanceof THREE.DirectionalLight ) {
var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
var amount = normal.dot( lightPosition );
if ( amount <= 0 ) continue;
amount *= light.intensity;
color.add( _lightColor.multiplyScalar( amount ) );
} else if ( light instanceof THREE.PointLight ) {
var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
if ( amount <= 0 ) continue;
amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
if ( amount == 0 ) continue;
amount *= light.intensity;
color.add( _lightColor.multiplyScalar( amount ) );
}
}
}
function renderSprite( v1, element, material ) {
setOpacity( material.opacity );
setBlending( material.blending );
var scaleX = element.scale.x * _canvasWidthHalf;
var scaleY = element.scale.y * _canvasHeightHalf;
var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
_elemBox.min.set( v1.x - dist, v1.y - dist );
_elemBox.max.set( v1.x + dist, v1.y + dist );
if ( material instanceof THREE.SpriteMaterial ||
material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
var texture = material.map;
if ( texture !== null ) {
if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
if ( texture.image !== undefined && texture.image.width > 0 ) {
textureToPattern( texture );
}
texture.addEventListener( 'update', onTextureUpdate );
}
var pattern = _patterns[ texture.id ];
if ( pattern !== undefined ) {
setFillStyle( pattern );
} else {
setFillStyle( 'rgba( 0, 0, 0, 1 )' );
}
//
var bitmap = texture.image;
var ox = bitmap.width * texture.offset.x;
var oy = bitmap.height * texture.offset.y;
var sx = bitmap.width * texture.repeat.x;
var sy = bitmap.height * texture.repeat.y;
var cx = scaleX / sx;
var cy = scaleY / sy;
_context.save();
_context.translate( v1.x, v1.y );
if ( material.rotation !== 0 ) _context.rotate( material.rotation );
_context.translate( - scaleX / 2, - scaleY / 2 );
_context.scale( cx, cy );
_context.translate( - ox, - oy );
_context.fillRect( ox, oy, sx, sy );
_context.restore();
} else { // no texture
setFillStyle( material.color.getStyle() );
_context.save();
_context.translate( v1.x, v1.y );
if ( material.rotation !== 0 ) _context.rotate( material.rotation );
_context.scale( scaleX, - scaleY );
_context.fillRect( - 0.5, - 0.5, 1, 1 );
_context.restore();
}
} else if ( material instanceof THREE.SpriteCanvasMaterial ) {
setStrokeStyle( material.color.getStyle() );
setFillStyle( material.color.getStyle() );
_context.save();
_context.translate( v1.x, v1.y );
if ( material.rotation !== 0 ) _context.rotate( material.rotation );
_context.scale( scaleX, scaleY );
material.program( _context );
_context.restore();
}
/* DEBUG
setStrokeStyle( 'rgb(255,255,0)' );
_context.beginPath();
_context.moveTo( v1.x - 10, v1.y );
_context.lineTo( v1.x + 10, v1.y );
_context.moveTo( v1.x, v1.y - 10 );
_context.lineTo( v1.x, v1.y + 10 );
_context.stroke();
*/
}
function renderLine( v1, v2, element, material ) {
setOpacity( material.opacity );
setBlending( material.blending );
_context.beginPath();
_context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
_context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
if ( material instanceof THREE.LineBasicMaterial ) {
setLineWidth( material.linewidth );
setLineCap( material.linecap );
setLineJoin( material.linejoin );
if ( material.vertexColors !== THREE.VertexColors ) {
setStrokeStyle( material.color.getStyle() );
} else {
var colorStyle1 = element.vertexColors[0].getStyle();
var colorStyle2 = element.vertexColors[1].getStyle();
if ( colorStyle1 === colorStyle2 ) {
setStrokeStyle( colorStyle1 );
} else {
try {
var grad = _context.createLinearGradient(
v1.positionScreen.x,
v1.positionScreen.y,
v2.positionScreen.x,
v2.positionScreen.y
);
grad.addColorStop( 0, colorStyle1 );
grad.addColorStop( 1, colorStyle2 );
} catch ( exception ) {
grad = colorStyle1;
}
setStrokeStyle( grad );
}
}
_context.stroke();
_elemBox.expandByScalar( material.linewidth * 2 );
} else if ( material instanceof THREE.LineDashedMaterial ) {
setLineWidth( material.linewidth );
setLineCap( material.linecap );
setLineJoin( material.linejoin );
setStrokeStyle( material.color.getStyle() );
setDashAndGap( material.dashSize, material.gapSize );
_context.stroke();
_elemBox.expandByScalar( material.linewidth * 2 );
setDashAndGap( null, null );
}
}
function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
_this.info.render.vertices += 3;
_this.info.render.faces ++;
setOpacity( material.opacity );
setBlending( material.blending );
_v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
_v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
_v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
_diffuseColor.copy( material.color );
_emissiveColor.copy( material.emissive );
if ( material.vertexColors === THREE.FaceColors ) {
_diffuseColor.multiply( element.color );
}
if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
_color1.copy( _ambientLight );
_color2.copy( _ambientLight );
_color3.copy( _ambientLight );
calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
_color1.multiply( _diffuseColor ).add( _emissiveColor );
_color2.multiply( _diffuseColor ).add( _emissiveColor );
_color3.multiply( _diffuseColor ).add( _emissiveColor );
_color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
_image = getGradientTexture( _color1, _color2, _color3, _color4 );
clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
} else {
_color.copy( _ambientLight );
calculateLight( element.centroidModel, element.normalModel, _color );
_color.multiply( _diffuseColor ).add( _emissiveColor );
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
}
} else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
if ( material.map !== null ) {
if ( material.map.mapping instanceof THREE.UVMapping ) {
_uvs = element.uvs[ 0 ];
patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
}
} else if ( material.envMap !== null ) {
if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
_normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
_uv1x = 0.5 * _normal.x + 0.5;
_uv1y = 0.5 * _normal.y + 0.5;
_normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
_uv2x = 0.5 * _normal.x + 0.5;
_uv2y = 0.5 * _normal.y + 0.5;
_normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
_uv3x = 0.5 * _normal.x + 0.5;
_uv3y = 0.5 * _normal.y + 0.5;
patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
}/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
}*/
} else {
_color.copy( material.color );
if ( material.vertexColors === THREE.FaceColors ) {
_color.multiply( element.color );
}
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
}
} else if ( material instanceof THREE.MeshDepthMaterial ) {
_near = _camera.near;
_far = _camera.far;
_color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
_color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
_color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
_color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
_image = getGradientTexture( _color1, _color2, _color3, _color4 );
clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
} else if ( material instanceof THREE.MeshNormalMaterial ) {
if ( material.shading === THREE.FlatShading ) {
_normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
_color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
material.wireframe === true
? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
: fillPath( _color );
} else if ( material.shading === THREE.SmoothShading ) {
_normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
_color1.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
_normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
_color2.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
_normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
_color3.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
_color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
_image = getGradientTexture( _color1, _color2, _color3, _color4 );
clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
}
}
}
//
function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
_context.beginPath();
_context.moveTo( x0, y0 );
_context.lineTo( x1, y1 );
_context.lineTo( x2, y2 );
_context.closePath();
}
function strokePath( color, linewidth, linecap, linejoin ) {
setLineWidth( linewidth );
setLineCap( linecap );
setLineJoin( linejoin );
setStrokeStyle( color.getStyle() );
_context.stroke();
_elemBox.expandByScalar( linewidth * 2 );
}
function fillPath( color ) {
setFillStyle( color.getStyle() );
_context.fill();
}
function onTextureUpdate ( event ) {
textureToPattern( event.target );
}
function textureToPattern( texture ) {
var repeatX = texture.wrapS === THREE.RepeatWrapping;
var repeatY = texture.wrapT === THREE.RepeatWrapping;
var image = texture.image;
var canvas = document.createElement( 'canvas' );
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext( '2d' );
context.setTransform( 1, 0, 0, - 1, 0, image.height );
context.drawImage( image, 0, 0 );
_patterns[ texture.id ] = _context.createPattern(
canvas, repeatX === true && repeatY === true
? 'repeat'
: repeatX === true && repeatY === false
? 'repeat-x'
: repeatX === false && repeatY === true
? 'repeat-y'
: 'no-repeat'
);
}
function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
if ( texture instanceof THREE.DataTexture ) return;
if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
if ( texture.image !== undefined && texture.image.width > 0 ) {
textureToPattern( texture );
}
texture.addEventListener( 'update', onTextureUpdate );
}
var pattern = _patterns[ texture.id ];
if ( pattern !== undefined ) {
setFillStyle( pattern );
} else {
setFillStyle( 'rgba(0,0,0,1)' );
_context.fill();
return;
}
// http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
var a, b, c, d, e, f, det, idet,
offsetX = texture.offset.x / texture.repeat.x,
offsetY = texture.offset.y / texture.repeat.y,
width = texture.image.width * texture.repeat.x,
height = texture.image.height * texture.repeat.y;
u0 = ( u0 + offsetX ) * width;
v0 = ( v0 + offsetY ) * height;
u1 = ( u1 + offsetX ) * width;
v1 = ( v1 + offsetY ) * height;
u2 = ( u2 + offsetX ) * width;
v2 = ( v2 + offsetY ) * height;
x1 -= x0; y1 -= y0;
x2 -= x0; y2 -= y0;
u1 -= u0; v1 -= v0;
u2 -= u0; v2 -= v0;
det = u1 * v2 - u2 * v1;
if ( det === 0 ) return;
idet = 1 / det;
a = ( v2 * x1 - v1 * x2 ) * idet;
b = ( v2 * y1 - v1 * y2 ) * idet;
c = ( u1 * x2 - u2 * x1 ) * idet;
d = ( u1 * y2 - u2 * y1 ) * idet;
e = x0 - a * u0 - c * v0;
f = y0 - b * u0 - d * v0;
_context.save();
_context.transform( a, b, c, d, e, f );
_context.fill();
_context.restore();
}
function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
// http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
var a, b, c, d, e, f, det, idet,
width = image.width - 1,
height = image.height - 1;
u0 *= width; v0 *= height;
u1 *= width; v1 *= height;
u2 *= width; v2 *= height;
x1 -= x0; y1 -= y0;
x2 -= x0; y2 -= y0;
u1 -= u0; v1 -= v0;
u2 -= u0; v2 -= v0;
det = u1 * v2 - u2 * v1;
idet = 1 / det;
a = ( v2 * x1 - v1 * x2 ) * idet;
b = ( v2 * y1 - v1 * y2 ) * idet;
c = ( u1 * x2 - u2 * x1 ) * idet;
d = ( u1 * y2 - u2 * y1 ) * idet;
e = x0 - a * u0 - c * v0;
f = y0 - b * u0 - d * v0;
_context.save();
_context.transform( a, b, c, d, e, f );
_context.clip();
_context.drawImage( image, 0, 0 );
_context.restore();
}
function getGradientTexture( color1, color2, color3, color4 ) {
// http://mrdoob.com/blog/post/710
_pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
_pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
_pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
_pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
_pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
_pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
_pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
_pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
_pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
_pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
_pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
_pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
_pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
_gradientMapContext.drawImage( _pixelMap, 0, 0 );
return _gradientMap;
}
// Hide anti-alias gaps
function expand( v1, v2, pixels ) {
var x = v2.x - v1.x, y = v2.y - v1.y,
det = x * x + y * y, idet;
if ( det === 0 ) return;
idet = pixels / Math.sqrt( det );
x *= idet; y *= idet;
v2.x += x; v2.y += y;
v1.x -= x; v1.y -= y;
}
// Context cached methods.
function setOpacity( value ) {
if ( _contextGlobalAlpha !== value ) {
_context.globalAlpha = value;
_contextGlobalAlpha = value;
}
}
function setBlending( value ) {
if ( _contextGlobalCompositeOperation !== value ) {
if ( value === THREE.NormalBlending ) {
_context.globalCompositeOperation = 'source-over';
} else if ( value === THREE.AdditiveBlending ) {
_context.globalCompositeOperation = 'lighter';
} else if ( value === THREE.SubtractiveBlending ) {
_context.globalCompositeOperation = 'darker';
}
_contextGlobalCompositeOperation = value;
}
}
function setLineWidth( value ) {
if ( _contextLineWidth !== value ) {
_context.lineWidth = value;
_contextLineWidth = value;
}
}
function setLineCap( value ) {
// "butt", "round", "square"
if ( _contextLineCap !== value ) {
_context.lineCap = value;
_contextLineCap = value;
}
}
function setLineJoin( value ) {
// "round", "bevel", "miter"
if ( _contextLineJoin !== value ) {
_context.lineJoin = value;
_contextLineJoin = value;
}
}
function setStrokeStyle( value ) {
if ( _contextStrokeStyle !== value ) {
_context.strokeStyle = value;
_contextStrokeStyle = value;
}
}
function setFillStyle( value ) {
if ( _contextFillStyle !== value ) {
_context.fillStyle = value;
_contextFillStyle = value;
}
}
function setDashAndGap( dashSizeValue, gapSizeValue ) {
if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
_context.setLineDash( [ dashSizeValue, gapSizeValue ] );
_contextDashSize = dashSizeValue;
_contextGapSize = gapSizeValue;
}
}
};
/**
* Shader chunks for WebLG Shader library
*
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
*/
THREE.ShaderChunk = {
// FOG
fog_pars_fragment: [
"#ifdef USE_FOG",
"uniform vec3 fogColor;",
"#ifdef FOG_EXP2",
"uniform float fogDensity;",
"#else",
"uniform float fogNear;",
"uniform float fogFar;",
"#endif",
"#endif"
].join("\n"),
fog_fragment: [
"#ifdef USE_FOG",
"float depth = gl_FragCoord.z / gl_FragCoord.w;",
"#ifdef FOG_EXP2",
"const float LOG2 = 1.442695;",
"float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
"fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
"#else",
"float fogFactor = smoothstep( fogNear, fogFar, depth );",
"#endif",
"gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
"#endif"
].join("\n"),
// ENVIRONMENT MAP
envmap_pars_fragment: [
"#ifdef USE_ENVMAP",
"uniform float reflectivity;",
"uniform samplerCube envMap;",
"uniform float flipEnvMap;",
"uniform int combine;",
"#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
"uniform bool useRefract;",
"uniform float refractionRatio;",
"#else",
"varying vec3 vReflect;",
"#endif",
"#endif"
].join("\n"),
envmap_fragment: [
"#ifdef USE_ENVMAP",
"vec3 reflectVec;",
"#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
"vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
"if ( useRefract ) {",
"reflectVec = refract( cameraToVertex, normal, refractionRatio );",
"} else { ",
"reflectVec = reflect( cameraToVertex, normal );",
"}",
"#else",
"reflectVec = vReflect;",
"#endif",
"#ifdef DOUBLE_SIDED",
"float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
"vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
"#else",
"vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
"#endif",
"#ifdef GAMMA_INPUT",
"cubeColor.xyz *= cubeColor.xyz;",
"#endif",
"if ( combine == 1 ) {",
"gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
"} else if ( combine == 2 ) {",
"gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
"} else {",
"gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
"}",
"#endif"
].join("\n"),
envmap_pars_vertex: [
"#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
"varying vec3 vReflect;",
"uniform float refractionRatio;",
"uniform bool useRefract;",
"#endif"
].join("\n"),
worldpos_vertex : [
"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
"#ifdef USE_SKINNING",
"vec4 worldPosition = modelMatrix * skinned;",
"#endif",
"#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
"vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
"#endif",
"#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"#endif",
"#endif"
].join("\n"),
envmap_vertex : [
"#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
"vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
"worldNormal = normalize( worldNormal );",
"vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
"if ( useRefract ) {",
"vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
"} else {",
"vReflect = reflect( cameraToVertex, worldNormal );",
"}",
"#endif"
].join("\n"),
// COLOR MAP (particles)
map_particle_pars_fragment: [
"#ifdef USE_MAP",
"uniform sampler2D map;",
"#endif"
].join("\n"),
map_particle_fragment: [
"#ifdef USE_MAP",
"gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
"#endif"
].join("\n"),
// COLOR MAP (triangles)
map_pars_vertex: [
"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
"varying vec2 vUv;",
"uniform vec4 offsetRepeat;",
"#endif"
].join("\n"),
map_pars_fragment: [
"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
"varying vec2 vUv;",
"#endif",
"#ifdef USE_MAP",
"uniform sampler2D map;",
"#endif"
].join("\n"),
map_vertex: [
"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
"vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
"#endif"
].join("\n"),
map_fragment: [
"#ifdef USE_MAP",
"vec4 texelColor = texture2D( map, vUv );",
"#ifdef GAMMA_INPUT",
"texelColor.xyz *= texelColor.xyz;",
"#endif",
"gl_FragColor = gl_FragColor * texelColor;",
"#endif"
].join("\n"),
// LIGHT MAP
lightmap_pars_fragment: [
"#ifdef USE_LIGHTMAP",
"varying vec2 vUv2;",
"uniform sampler2D lightMap;",
"#endif"
].join("\n"),
lightmap_pars_vertex: [
"#ifdef USE_LIGHTMAP",
"varying vec2 vUv2;",
"#endif"
].join("\n"),
lightmap_fragment: [
"#ifdef USE_LIGHTMAP",
"gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
"#endif"
].join("\n"),
lightmap_vertex: [
"#ifdef USE_LIGHTMAP",
"vUv2 = uv2;",
"#endif"
].join("\n"),
// BUMP MAP
bumpmap_pars_fragment: [
"#ifdef USE_BUMPMAP",
"uniform sampler2D bumpMap;",
"uniform float bumpScale;",
// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
"vec2 dHdxy_fwd() {",
"vec2 dSTdx = dFdx( vUv );",
"vec2 dSTdy = dFdy( vUv );",
"float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
"float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
"float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
"return vec2( dBx, dBy );",
"}",
"vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
"vec3 vSigmaX = dFdx( surf_pos );",
"vec3 vSigmaY = dFdy( surf_pos );",
"vec3 vN = surf_norm;", // normalized
"vec3 R1 = cross( vSigmaY, vN );",
"vec3 R2 = cross( vN, vSigmaX );",
"float fDet = dot( vSigmaX, R1 );",
"vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
"return normalize( abs( fDet ) * surf_norm - vGrad );",
"}",
"#endif"
].join("\n"),
// NORMAL MAP
normalmap_pars_fragment: [
"#ifdef USE_NORMALMAP",
"uniform sampler2D normalMap;",
"uniform vec2 normalScale;",
// Per-Pixel Tangent Space Normal Mapping
// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
"vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
"vec3 q0 = dFdx( eye_pos.xyz );",
"vec3 q1 = dFdy( eye_pos.xyz );",
"vec2 st0 = dFdx( vUv.st );",
"vec2 st1 = dFdy( vUv.st );",
"vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
"vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
"vec3 N = normalize( surf_norm );",
"vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
"mapN.xy = normalScale * mapN.xy;",
"mat3 tsn = mat3( S, T, N );",
"return normalize( tsn * mapN );",
"}",
"#endif"
].join("\n"),
// SPECULAR MAP
specularmap_pars_fragment: [
"#ifdef USE_SPECULARMAP",
"uniform sampler2D specularMap;",
"#endif"
].join("\n"),
specularmap_fragment: [
"float specularStrength;",
"#ifdef USE_SPECULARMAP",
"vec4 texelSpecular = texture2D( specularMap, vUv );",
"specularStrength = texelSpecular.r;",
"#else",
"specularStrength = 1.0;",
"#endif"
].join("\n"),
// LIGHTS LAMBERT
lights_lambert_pars_vertex: [
"uniform vec3 ambient;",
"uniform vec3 diffuse;",
"uniform vec3 emissive;",
"uniform vec3 ambientLightColor;",
"#if MAX_DIR_LIGHTS > 0",
"uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
"uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
"uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
"uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
"#endif",
"#ifdef WRAP_AROUND",
"uniform vec3 wrapRGB;",
"#endif"
].join("\n"),
lights_lambert_vertex: [
"vLightFront = vec3( 0.0 );",
"#ifdef DOUBLE_SIDED",
"vLightBack = vec3( 0.0 );",
"#endif",
"transformedNormal = normalize( transformedNormal );",
"#if MAX_DIR_LIGHTS > 0",
"for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
"vec3 dirVector = normalize( lDirection.xyz );",
"float dotProduct = dot( transformedNormal, dirVector );",
"vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
"#ifdef DOUBLE_SIDED",
"vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
"#ifdef WRAP_AROUND",
"vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
"#endif",
"#endif",
"#ifdef WRAP_AROUND",
"vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
"directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
"#ifdef DOUBLE_SIDED",
"directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
"#endif",
"#endif",
"vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
"#ifdef DOUBLE_SIDED",
"vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
"#endif",
"}",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz - mvPosition.xyz;",
"float lDistance = 1.0;",
"if ( pointLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
"lVector = normalize( lVector );",
"float dotProduct = dot( transformedNormal, lVector );",
"vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
"#ifdef DOUBLE_SIDED",
"vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
"#ifdef WRAP_AROUND",
"vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
"#endif",
"#endif",
"#ifdef WRAP_AROUND",
"vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
"pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
"#ifdef DOUBLE_SIDED",
"pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
"#endif",
"#endif",
"vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
"#ifdef DOUBLE_SIDED",
"vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
"#endif",
"}",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz - mvPosition.xyz;",
"float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
"if ( spotEffect > spotLightAngleCos[ i ] ) {",
"spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
"float lDistance = 1.0;",
"if ( spotLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
"lVector = normalize( lVector );",
"float dotProduct = dot( transformedNormal, lVector );",
"vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
"#ifdef DOUBLE_SIDED",
"vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
"#ifdef WRAP_AROUND",
"vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
"#endif",
"#endif",
"#ifdef WRAP_AROUND",
"vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
"spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
"#ifdef DOUBLE_SIDED",
"spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
"#endif",
"#endif",
"vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
"#ifdef DOUBLE_SIDED",
"vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
"#endif",
"}",
"}",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
"vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
"vec3 lVector = normalize( lDirection.xyz );",
"float dotProduct = dot( transformedNormal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
"vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
"#ifdef DOUBLE_SIDED",
"vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
"#endif",
"}",
"#endif",
"vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
"#ifdef DOUBLE_SIDED",
"vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
"#endif"
].join("\n"),
// LIGHTS PHONG
lights_phong_pars_vertex: [
"#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
"varying vec3 vWorldPosition;",
"#endif"
].join("\n"),
lights_phong_vertex: [
"#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
"vWorldPosition = worldPosition.xyz;",
"#endif"
].join("\n"),
lights_phong_pars_fragment: [
"uniform vec3 ambientLightColor;",
"#if MAX_DIR_LIGHTS > 0",
"uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
"uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
"uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
"uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
"#endif",
"#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
"varying vec3 vWorldPosition;",
"#endif",
"#ifdef WRAP_AROUND",
"uniform vec3 wrapRGB;",
"#endif",
"varying vec3 vViewPosition;",
"varying vec3 vNormal;"
].join("\n"),
lights_phong_fragment: [
"vec3 normal = normalize( vNormal );",
"vec3 viewPosition = normalize( vViewPosition );",
"#ifdef DOUBLE_SIDED",
"normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
"#endif",
"#ifdef USE_NORMALMAP",
"normal = perturbNormal2Arb( -vViewPosition, normal );",
"#elif defined( USE_BUMPMAP )",
"normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"vec3 pointDiffuse = vec3( 0.0 );",
"vec3 pointSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
"float lDistance = 1.0;",
"if ( pointLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
"lVector = normalize( lVector );",
// diffuse
"float dotProduct = dot( normal, lVector );",
"#ifdef WRAP_AROUND",
"float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
"float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
"vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
"#else",
"float pointDiffuseWeight = max( dotProduct, 0.0 );",
"#endif",
"pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
// specular
"vec3 pointHalfVector = normalize( lVector + viewPosition );",
"float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
"float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
"pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
"}",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"vec3 spotDiffuse = vec3( 0.0 );",
"vec3 spotSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
"vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
"float lDistance = 1.0;",
"if ( spotLightDistance[ i ] > 0.0 )",
"lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
"lVector = normalize( lVector );",
"float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
"if ( spotEffect > spotLightAngleCos[ i ] ) {",
"spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
// diffuse
"float dotProduct = dot( normal, lVector );",
"#ifdef WRAP_AROUND",
"float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
"float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
"vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
"#else",
"float spotDiffuseWeight = max( dotProduct, 0.0 );",
"#endif",
"spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
// specular
"vec3 spotHalfVector = normalize( lVector + viewPosition );",
"float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
"float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
"spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
"}",
"}",
"#endif",
"#if MAX_DIR_LIGHTS > 0",
"vec3 dirDiffuse = vec3( 0.0 );",
"vec3 dirSpecular = vec3( 0.0 );" ,
"for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
"vec3 dirVector = normalize( lDirection.xyz );",
// diffuse
"float dotProduct = dot( normal, dirVector );",
"#ifdef WRAP_AROUND",
"float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
"float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
"vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
"#else",
"float dirDiffuseWeight = max( dotProduct, 0.0 );",
"#endif",
"dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
// specular
"vec3 dirHalfVector = normalize( dirVector + viewPosition );",
"float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
"float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
/*
// fresnel term from skin shader
"const float F0 = 0.128;",
"float base = 1.0 - dot( viewPosition, dirHalfVector );",
"float exponential = pow( base, 5.0 );",
"float fresnel = exponential + F0 * ( 1.0 - exponential );",
*/
/*
// fresnel term from fresnel shader
"const float mFresnelBias = 0.08;",
"const float mFresnelScale = 0.3;",
"const float mFresnelPower = 5.0;",
"float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
*/
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
//"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
"dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
"}",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"vec3 hemiDiffuse = vec3( 0.0 );",
"vec3 hemiSpecular = vec3( 0.0 );" ,
"for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
"vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
"vec3 lVector = normalize( lDirection.xyz );",
// diffuse
"float dotProduct = dot( normal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
"hemiDiffuse += diffuse * hemiColor;",
// specular (sky light)
"vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
"float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
"float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
// specular (ground light)
"vec3 lVectorGround = -lVector;",
"vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
"float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
"float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
"float dotProductGround = dot( normal, lVectorGround );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
"vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
"hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
"}",
"#endif",
"vec3 totalDiffuse = vec3( 0.0 );",
"vec3 totalSpecular = vec3( 0.0 );",
"#if MAX_DIR_LIGHTS > 0",
"totalDiffuse += dirDiffuse;",
"totalSpecular += dirSpecular;",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"totalDiffuse += hemiDiffuse;",
"totalSpecular += hemiSpecular;",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"totalDiffuse += pointDiffuse;",
"totalSpecular += pointSpecular;",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"totalDiffuse += spotDiffuse;",
"totalSpecular += spotSpecular;",
"#endif",
"#ifdef METAL",
"gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
"#else",
"gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
"#endif"
].join("\n"),
// VERTEX COLORS
color_pars_fragment: [
"#ifdef USE_COLOR",
"varying vec3 vColor;",
"#endif"
].join("\n"),
color_fragment: [
"#ifdef USE_COLOR",
"gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
"#endif"
].join("\n"),
color_pars_vertex: [
"#ifdef USE_COLOR",
"varying vec3 vColor;",
"#endif"
].join("\n"),
color_vertex: [
"#ifdef USE_COLOR",
"#ifdef GAMMA_INPUT",
"vColor = color * color;",
"#else",
"vColor = color;",
"#endif",
"#endif"
].join("\n"),
// SKINNING
skinning_pars_vertex: [
"#ifdef USE_SKINNING",
"#ifdef BONE_TEXTURE",
"uniform sampler2D boneTexture;",
"uniform int boneTextureWidth;",
"uniform int boneTextureHeight;",
"mat4 getBoneMatrix( const in float i ) {",
"float j = i * 4.0;",
"float x = mod( j, float( boneTextureWidth ) );",
"float y = floor( j / float( boneTextureWidth ) );",
"float dx = 1.0 / float( boneTextureWidth );",
"float dy = 1.0 / float( boneTextureHeight );",
"y = dy * ( y + 0.5 );",
"vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
"vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
"vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
"vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
"mat4 bone = mat4( v1, v2, v3, v4 );",
"return bone;",
"}",
"#else",
"uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
"mat4 getBoneMatrix( const in float i ) {",
"mat4 bone = boneGlobalMatrices[ int(i) ];",
"return bone;",
"}",
"#endif",
"#endif"
].join("\n"),
skinbase_vertex: [
"#ifdef USE_SKINNING",
"mat4 boneMatX = getBoneMatrix( skinIndex.x );",
"mat4 boneMatY = getBoneMatrix( skinIndex.y );",
"mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
"mat4 boneMatW = getBoneMatrix( skinIndex.w );",
"#endif"
].join("\n"),
skinning_vertex: [
"#ifdef USE_SKINNING",
"#ifdef USE_MORPHTARGETS",
"vec4 skinVertex = vec4( morphed, 1.0 );",
"#else",
"vec4 skinVertex = vec4( position, 1.0 );",
"#endif",
"vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
"skinned += boneMatY * skinVertex * skinWeight.y;",
"skinned += boneMatZ * skinVertex * skinWeight.z;",
"skinned += boneMatW * skinVertex * skinWeight.w;",
"#endif"
].join("\n"),
// MORPHING
morphtarget_pars_vertex: [
"#ifdef USE_MORPHTARGETS",
"#ifndef USE_MORPHNORMALS",
"uniform float morphTargetInfluences[ 8 ];",
"#else",
"uniform float morphTargetInfluences[ 4 ];",
"#endif",
"#endif"
].join("\n"),
morphtarget_vertex: [
"#ifdef USE_MORPHTARGETS",
"vec3 morphed = vec3( 0.0 );",
"morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
"morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
"morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
"morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
"#ifndef USE_MORPHNORMALS",
"morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
"morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
"morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
"morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
"#endif",
"morphed += position;",
"#endif"
].join("\n"),
default_vertex : [
"vec4 mvPosition;",
"#ifdef USE_SKINNING",
"mvPosition = modelViewMatrix * skinned;",
"#endif",
"#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
"mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
"#endif",
"#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
"mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"#endif",
"gl_Position = projectionMatrix * mvPosition;"
].join("\n"),
morphnormal_vertex: [
"#ifdef USE_MORPHNORMALS",
"vec3 morphedNormal = vec3( 0.0 );",
"morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
"morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
"morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
"morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
"morphedNormal += normal;",
"#endif"
].join("\n"),
skinnormal_vertex: [
"#ifdef USE_SKINNING",
"mat4 skinMatrix = skinWeight.x * boneMatX;",
"skinMatrix += skinWeight.y * boneMatY;",
"#ifdef USE_MORPHNORMALS",
"vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
"#else",
"vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
"#endif",
"#endif"
].join("\n"),
defaultnormal_vertex: [
"vec3 objectNormal;",
"#ifdef USE_SKINNING",
"objectNormal = skinnedNormal.xyz;",
"#endif",
"#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
"objectNormal = morphedNormal;",
"#endif",
"#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
"objectNormal = normal;",
"#endif",
"#ifdef FLIP_SIDED",
"objectNormal = -objectNormal;",
"#endif",
"vec3 transformedNormal = normalMatrix * objectNormal;"
].join("\n"),
// SHADOW MAP
// based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
// http://spidergl.org/example.php?id=6
// http://fabiensanglard.net/shadowmapping
shadowmap_pars_fragment: [
"#ifdef USE_SHADOWMAP",
"uniform sampler2D shadowMap[ MAX_SHADOWS ];",
"uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
"uniform float shadowDarkness[ MAX_SHADOWS ];",
"uniform float shadowBias[ MAX_SHADOWS ];",
"varying vec4 vShadowCoord[ MAX_SHADOWS ];",
"float unpackDepth( const in vec4 rgba_depth ) {",
"const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
"float depth = dot( rgba_depth, bit_shift );",
"return depth;",
"}",
"#endif"
].join("\n"),
shadowmap_fragment: [
"#ifdef USE_SHADOWMAP",
"#ifdef SHADOWMAP_DEBUG",
"vec3 frustumColors[3];",
"frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
"frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
"frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
"#endif",
"#ifdef SHADOWMAP_CASCADE",
"int inFrustumCount = 0;",
"#endif",
"float fDepth;",
"vec3 shadowColor = vec3( 1.0 );",
"for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
"vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
// "if ( something && something )" breaks ATI OpenGL shader compiler
// "if ( all( something, something ) )" using this instead
"bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
"bool inFrustum = all( inFrustumVec );",
// don't shadow pixels outside of light frustum
// use just first frustum (for cascades)
// don't shadow pixels behind far plane of light frustum
"#ifdef SHADOWMAP_CASCADE",
"inFrustumCount += int( inFrustum );",
"bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
"#else",
"bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
"#endif",
"bool frustumTest = all( frustumTestVec );",
"if ( frustumTest ) {",
"shadowCoord.z += shadowBias[ i ];",
"#if defined( SHADOWMAP_TYPE_PCF )",
// Percentage-close filtering
// (9 pixel kernel)
// http://fabiensanglard.net/shadowmappingPCF/
"float shadow = 0.0;",
/*
// nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
// must enroll loop manually
"for ( float y = -1.25; y <= 1.25; y += 1.25 )",
"for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
"vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
// doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
//"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
"float fDepth = unpackDepth( rgbaDepth );",
"if ( fDepth < shadowCoord.z )",
"shadow += 1.0;",
"}",
"shadow /= 9.0;",
*/
"const float shadowDelta = 1.0 / 9.0;",
"float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
"float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
"float dx0 = -1.25 * xPixelOffset;",
"float dy0 = -1.25 * yPixelOffset;",
"float dx1 = 1.25 * xPixelOffset;",
"float dy1 = 1.25 * yPixelOffset;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
"if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
"shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
"#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
// Percentage-close filtering
// (9 pixel kernel)
// http://fabiensanglard.net/shadowmappingPCF/
"float shadow = 0.0;",
"float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
"float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
"float dx0 = -1.0 * xPixelOffset;",
"float dy0 = -1.0 * yPixelOffset;",
"float dx1 = 1.0 * xPixelOffset;",
"float dy1 = 1.0 * yPixelOffset;",
"mat3 shadowKernel;",
"mat3 depthKernel;",
"depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
"depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
"depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
"depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
"depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
"depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
"depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
"depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
"depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
"vec3 shadowZ = vec3( shadowCoord.z );",
"shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
"shadowKernel[0] *= vec3(0.25);",
"shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
"shadowKernel[1] *= vec3(0.25);",
"shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
"shadowKernel[2] *= vec3(0.25);",
"vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
"shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
"shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
"vec4 shadowValues;",
"shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
"shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
"shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
"shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
"shadow = dot( shadowValues, vec4( 1.0 ) );",
"shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
"#else",
"vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
"float fDepth = unpackDepth( rgbaDepth );",
"if ( fDepth < shadowCoord.z )",
// spot with multiple shadows is darker
"shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
// spot with multiple shadows has the same color as single shadow spot
//"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
"#endif",
"}",
"#ifdef SHADOWMAP_DEBUG",
"#ifdef SHADOWMAP_CASCADE",
"if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
"#else",
"if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
"#endif",
"#endif",
"}",
"#ifdef GAMMA_OUTPUT",
"shadowColor *= shadowColor;",
"#endif",
"gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
"#endif"
].join("\n"),
shadowmap_pars_vertex: [
"#ifdef USE_SHADOWMAP",
"varying vec4 vShadowCoord[ MAX_SHADOWS ];",
"uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
"#endif"
].join("\n"),
shadowmap_vertex: [
"#ifdef USE_SHADOWMAP",
"for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
"vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
"}",
"#endif"
].join("\n"),
// ALPHATEST
alphatest_fragment: [
"#ifdef ALPHATEST",
"if ( gl_FragColor.a < ALPHATEST ) discard;",
"#endif"
].join("\n"),
// LINEAR SPACE
linear_to_gamma_fragment: [
"#ifdef GAMMA_OUTPUT",
"gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
"#endif"
].join("\n")
};
/**
* Uniform Utilities
*/
THREE.UniformsUtils = {
merge: function ( uniforms ) {
var u, p, tmp, merged = {};
for ( u = 0; u < uniforms.length; u ++ ) {
tmp = this.clone( uniforms[ u ] );
for ( p in tmp ) {
merged[ p ] = tmp[ p ];
}
}
return merged;
},
clone: function ( uniforms_src ) {
var u, p, parameter, parameter_src, uniforms_dst = {};
for ( u in uniforms_src ) {
uniforms_dst[ u ] = {};
for ( p in uniforms_src[ u ] ) {
parameter_src = uniforms_src[ u ][ p ];
if ( parameter_src instanceof THREE.Color ||
parameter_src instanceof THREE.Vector2 ||
parameter_src instanceof THREE.Vector3 ||
parameter_src instanceof THREE.Vector4 ||
parameter_src instanceof THREE.Matrix4 ||
parameter_src instanceof THREE.Texture ) {
uniforms_dst[ u ][ p ] = parameter_src.clone();
} else if ( parameter_src instanceof Array ) {
uniforms_dst[ u ][ p ] = parameter_src.slice();
} else {
uniforms_dst[ u ][ p ] = parameter_src;
}
}
}
return uniforms_dst;
}
};
/**
* Uniforms library for shared webgl shaders
*/
THREE.UniformsLib = {
common: {
"diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
"opacity" : { type: "f", value: 1.0 },
"map" : { type: "t", value: null },
"offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
"lightMap" : { type: "t", value: null },
"specularMap" : { type: "t", value: null },
"envMap" : { type: "t", value: null },
"flipEnvMap" : { type: "f", value: -1 },
"useRefract" : { type: "i", value: 0 },
"reflectivity" : { type: "f", value: 1.0 },
"refractionRatio" : { type: "f", value: 0.98 },
"combine" : { type: "i", value: 0 },
"morphTargetInfluences" : { type: "f", value: 0 }
},
bump: {
"bumpMap" : { type: "t", value: null },
"bumpScale" : { type: "f", value: 1 }
},
normalmap: {
"normalMap" : { type: "t", value: null },
"normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
},
fog : {
"fogDensity" : { type: "f", value: 0.00025 },
"fogNear" : { type: "f", value: 1 },
"fogFar" : { type: "f", value: 2000 },
"fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
},
lights: {
"ambientLightColor" : { type: "fv", value: [] },
"directionalLightDirection" : { type: "fv", value: [] },
"directionalLightColor" : { type: "fv", value: [] },
"hemisphereLightDirection" : { type: "fv", value: [] },
"hemisphereLightSkyColor" : { type: "fv", value: [] },
"hemisphereLightGroundColor" : { type: "fv", value: [] },
"pointLightColor" : { type: "fv", value: [] },
"pointLightPosition" : { type: "fv", value: [] },
"pointLightDistance" : { type: "fv1", value: [] },
"spotLightColor" : { type: "fv", value: [] },
"spotLightPosition" : { type: "fv", value: [] },
"spotLightDirection" : { type: "fv", value: [] },
"spotLightDistance" : { type: "fv1", value: [] },
"spotLightAngleCos" : { type: "fv1", value: [] },
"spotLightExponent" : { type: "fv1", value: [] }
},
particle: {
"psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
"opacity" : { type: "f", value: 1.0 },
"size" : { type: "f", value: 1.0 },
"scale" : { type: "f", value: 1.0 },
"map" : { type: "t", value: null },
"fogDensity" : { type: "f", value: 0.00025 },
"fogNear" : { type: "f", value: 1 },
"fogFar" : { type: "f", value: 2000 },
"fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
},
shadowmap: {
"shadowMap": { type: "tv", value: [] },
"shadowMapSize": { type: "v2v", value: [] },
"shadowBias" : { type: "fv1", value: [] },
"shadowDarkness": { type: "fv1", value: [] },
"shadowMatrix" : { type: "m4v", value: [] }
}
};
/**
* Webgl Shader Library for three.js
*
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
*/
THREE.ShaderLib = {
'basic': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "common" ],
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "shadowmap" ]
] ),
vertexShader: [
THREE.ShaderChunk[ "map_pars_vertex" ],
THREE.ShaderChunk[ "lightmap_pars_vertex" ],
THREE.ShaderChunk[ "envmap_pars_vertex" ],
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "map_vertex" ],
THREE.ShaderChunk[ "lightmap_vertex" ],
THREE.ShaderChunk[ "color_vertex" ],
THREE.ShaderChunk[ "skinbase_vertex" ],
"#ifdef USE_ENVMAP",
THREE.ShaderChunk[ "morphnormal_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
THREE.ShaderChunk[ "defaultnormal_vertex" ],
"#endif",
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "envmap_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform float opacity;",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_pars_fragment" ],
THREE.ShaderChunk[ "lightmap_pars_fragment" ],
THREE.ShaderChunk[ "envmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "specularmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( diffuse, opacity );",
THREE.ShaderChunk[ "map_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "specularmap_fragment" ],
THREE.ShaderChunk[ "lightmap_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "envmap_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'lambert': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "common" ],
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
THREE.UniformsLib[ "shadowmap" ],
{
"ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
"emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
"wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
}
] ),
vertexShader: [
"#define LAMBERT",
"varying vec3 vLightFront;",
"#ifdef DOUBLE_SIDED",
"varying vec3 vLightBack;",
"#endif",
THREE.ShaderChunk[ "map_pars_vertex" ],
THREE.ShaderChunk[ "lightmap_pars_vertex" ],
THREE.ShaderChunk[ "envmap_pars_vertex" ],
THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "map_vertex" ],
THREE.ShaderChunk[ "lightmap_vertex" ],
THREE.ShaderChunk[ "color_vertex" ],
THREE.ShaderChunk[ "morphnormal_vertex" ],
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
THREE.ShaderChunk[ "defaultnormal_vertex" ],
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "envmap_vertex" ],
THREE.ShaderChunk[ "lights_lambert_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform float opacity;",
"varying vec3 vLightFront;",
"#ifdef DOUBLE_SIDED",
"varying vec3 vLightBack;",
"#endif",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_pars_fragment" ],
THREE.ShaderChunk[ "lightmap_pars_fragment" ],
THREE.ShaderChunk[ "envmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "specularmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
THREE.ShaderChunk[ "map_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "specularmap_fragment" ],
"#ifdef DOUBLE_SIDED",
//"float isFront = float( gl_FrontFacing );",
//"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
"if ( gl_FrontFacing )",
"gl_FragColor.xyz *= vLightFront;",
"else",
"gl_FragColor.xyz *= vLightBack;",
"#else",
"gl_FragColor.xyz *= vLightFront;",
"#endif",
THREE.ShaderChunk[ "lightmap_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "envmap_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'phong': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "common" ],
THREE.UniformsLib[ "bump" ],
THREE.UniformsLib[ "normalmap" ],
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
THREE.UniformsLib[ "shadowmap" ],
{
"ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
"emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
"specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
"shininess": { type: "f", value: 30 },
"wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
}
] ),
vertexShader: [
"#define PHONG",
"varying vec3 vViewPosition;",
"varying vec3 vNormal;",
THREE.ShaderChunk[ "map_pars_vertex" ],
THREE.ShaderChunk[ "lightmap_pars_vertex" ],
THREE.ShaderChunk[ "envmap_pars_vertex" ],
THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "map_vertex" ],
THREE.ShaderChunk[ "lightmap_vertex" ],
THREE.ShaderChunk[ "color_vertex" ],
THREE.ShaderChunk[ "morphnormal_vertex" ],
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
THREE.ShaderChunk[ "defaultnormal_vertex" ],
"vNormal = normalize( transformedNormal );",
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
"vViewPosition = -mvPosition.xyz;",
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "envmap_vertex" ],
THREE.ShaderChunk[ "lights_phong_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform float opacity;",
"uniform vec3 ambient;",
"uniform vec3 emissive;",
"uniform vec3 specular;",
"uniform float shininess;",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_pars_fragment" ],
THREE.ShaderChunk[ "lightmap_pars_fragment" ],
THREE.ShaderChunk[ "envmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
THREE.ShaderChunk[ "normalmap_pars_fragment" ],
THREE.ShaderChunk[ "specularmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
THREE.ShaderChunk[ "map_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "specularmap_fragment" ],
THREE.ShaderChunk[ "lights_phong_fragment" ],
THREE.ShaderChunk[ "lightmap_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "envmap_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'particle_basic': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "particle" ],
THREE.UniformsLib[ "shadowmap" ]
] ),
vertexShader: [
"uniform float size;",
"uniform float scale;",
THREE.ShaderChunk[ "color_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "color_vertex" ],
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"#ifdef USE_SIZEATTENUATION",
"gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
"#else",
"gl_PointSize = size;",
"#endif",
"gl_Position = projectionMatrix * mvPosition;",
THREE.ShaderChunk[ "worldpos_vertex" ],
THREE.ShaderChunk[ "shadowmap_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 psColor;",
"uniform float opacity;",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "map_particle_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( psColor, opacity );",
THREE.ShaderChunk[ "map_particle_fragment" ],
THREE.ShaderChunk[ "alphatest_fragment" ],
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'dashed': {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "common" ],
THREE.UniformsLib[ "fog" ],
{
"scale": { type: "f", value: 1 },
"dashSize": { type: "f", value: 1 },
"totalSize": { type: "f", value: 2 }
}
] ),
vertexShader: [
"uniform float scale;",
"attribute float lineDistance;",
"varying float vLineDistance;",
THREE.ShaderChunk[ "color_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "color_vertex" ],
"vLineDistance = scale * lineDistance;",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"gl_Position = projectionMatrix * mvPosition;",
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform float opacity;",
"uniform float dashSize;",
"uniform float totalSize;",
"varying float vLineDistance;",
THREE.ShaderChunk[ "color_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
"void main() {",
"if ( mod( vLineDistance, totalSize ) > dashSize ) {",
"discard;",
"}",
"gl_FragColor = vec4( diffuse, opacity );",
THREE.ShaderChunk[ "color_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n")
},
'depth': {
uniforms: {
"mNear": { type: "f", value: 1.0 },
"mFar" : { type: "f", value: 2000.0 },
"opacity" : { type: "f", value: 1.0 }
},
vertexShader: [
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform float mNear;",
"uniform float mFar;",
"uniform float opacity;",
"void main() {",
"float depth = gl_FragCoord.z / gl_FragCoord.w;",
"float color = 1.0 - smoothstep( mNear, mFar, depth );",
"gl_FragColor = vec4( vec3( color ), opacity );",
"}"
].join("\n")
},
'normal': {
uniforms: {
"opacity" : { type: "f", value: 1.0 }
},
vertexShader: [
"varying vec3 vNormal;",
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
"void main() {",
"vNormal = normalize( normalMatrix * normal );",
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"uniform float opacity;",
"varying vec3 vNormal;",
"void main() {",
"gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
"}"
].join("\n")
},
/* -------------------------------------------------------------------------
// Normal map shader
// - Blinn-Phong
// - normal + diffuse + specular + AO + displacement + reflection + shadow maps
// - point and directional lights (use with "lights: true" material option)
------------------------------------------------------------------------- */
'normalmap' : {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
THREE.UniformsLib[ "shadowmap" ],
{
"enableAO" : { type: "i", value: 0 },
"enableDiffuse" : { type: "i", value: 0 },
"enableSpecular" : { type: "i", value: 0 },
"enableReflection": { type: "i", value: 0 },
"enableDisplacement": { type: "i", value: 0 },
"tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
"tDiffuse" : { type: "t", value: null },
"tCube" : { type: "t", value: null },
"tNormal" : { type: "t", value: null },
"tSpecular" : { type: "t", value: null },
"tAO" : { type: "t", value: null },
"uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
"uDisplacementBias": { type: "f", value: 0.0 },
"uDisplacementScale": { type: "f", value: 1.0 },
"diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
"specular": { type: "c", value: new THREE.Color( 0x111111 ) },
"ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
"shininess": { type: "f", value: 30 },
"opacity": { type: "f", value: 1 },
"useRefract": { type: "i", value: 0 },
"refractionRatio": { type: "f", value: 0.98 },
"reflectivity": { type: "f", value: 0.5 },
"uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
"uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
"wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
}
] ),
fragmentShader: [
"uniform vec3 ambient;",
"uniform vec3 diffuse;",
"uniform vec3 specular;",
"uniform float shininess;",
"uniform float opacity;",
"uniform bool enableDiffuse;",
"uniform bool enableSpecular;",
"uniform bool enableAO;",
"uniform bool enableReflection;",
"uniform sampler2D tDiffuse;",
"uniform sampler2D tNormal;",
"uniform sampler2D tSpecular;",
"uniform sampler2D tAO;",
"uniform samplerCube tCube;",
"uniform vec2 uNormalScale;",
"uniform bool useRefract;",
"uniform float refractionRatio;",
"uniform float reflectivity;",
"varying vec3 vTangent;",
"varying vec3 vBinormal;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"uniform vec3 ambientLightColor;",
"#if MAX_DIR_LIGHTS > 0",
"uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
"uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
"uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
"uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
"uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
"uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
"uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
"#endif",
"#ifdef WRAP_AROUND",
"uniform vec3 wrapRGB;",
"#endif",
"varying vec3 vWorldPosition;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
"void main() {",
"gl_FragColor = vec4( vec3( 1.0 ), opacity );",
"vec3 specularTex = vec3( 1.0 );",
"vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
"normalTex.xy *= uNormalScale;",
"normalTex = normalize( normalTex );",
"if( enableDiffuse ) {",
"#ifdef GAMMA_INPUT",
"vec4 texelColor = texture2D( tDiffuse, vUv );",
"texelColor.xyz *= texelColor.xyz;",
"gl_FragColor = gl_FragColor * texelColor;",
"#else",
"gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
"#endif",
"}",
"if( enableAO ) {",
"#ifdef GAMMA_INPUT",
"vec4 aoColor = texture2D( tAO, vUv );",
"aoColor.xyz *= aoColor.xyz;",
"gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
"#else",
"gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
"#endif",
"}",
"if( enableSpecular )",
"specularTex = texture2D( tSpecular, vUv ).xyz;",
"mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
"vec3 finalNormal = tsb * normalTex;",
"#ifdef FLIP_SIDED",
"finalNormal = -finalNormal;",
"#endif",
"vec3 normal = normalize( finalNormal );",
"vec3 viewPosition = normalize( vViewPosition );",
// point lights
"#if MAX_POINT_LIGHTS > 0",
"vec3 pointDiffuse = vec3( 0.0 );",
"vec3 pointSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
"vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
"float pointDistance = 1.0;",
"if ( pointLightDistance[ i ] > 0.0 )",
"pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
"pointVector = normalize( pointVector );",
// diffuse
"#ifdef WRAP_AROUND",
"float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
"float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
"vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
"#else",
"float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
"#endif",
"pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
// specular
"vec3 pointHalfVector = normalize( pointVector + viewPosition );",
"float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
"float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
"pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
"}",
"#endif",
// spot lights
"#if MAX_SPOT_LIGHTS > 0",
"vec3 spotDiffuse = vec3( 0.0 );",
"vec3 spotSpecular = vec3( 0.0 );",
"for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
"vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
"vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
"float spotDistance = 1.0;",
"if ( spotLightDistance[ i ] > 0.0 )",
"spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
"spotVector = normalize( spotVector );",
"float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
"if ( spotEffect > spotLightAngleCos[ i ] ) {",
"spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
// diffuse
"#ifdef WRAP_AROUND",
"float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
"float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
"vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
"#else",
"float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
"#endif",
"spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
// specular
"vec3 spotHalfVector = normalize( spotVector + viewPosition );",
"float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
"float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
"spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
"}",
"}",
"#endif",
// directional lights
"#if MAX_DIR_LIGHTS > 0",
"vec3 dirDiffuse = vec3( 0.0 );",
"vec3 dirSpecular = vec3( 0.0 );",
"for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
"vec3 dirVector = normalize( lDirection.xyz );",
// diffuse
"#ifdef WRAP_AROUND",
"float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
"float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
"vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
"#else",
"float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
"#endif",
"dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
// specular
"vec3 dirHalfVector = normalize( dirVector + viewPosition );",
"float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
"float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
"dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
"}",
"#endif",
// hemisphere lights
"#if MAX_HEMI_LIGHTS > 0",
"vec3 hemiDiffuse = vec3( 0.0 );",
"vec3 hemiSpecular = vec3( 0.0 );" ,
"for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
"vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
"vec3 lVector = normalize( lDirection.xyz );",
// diffuse
"float dotProduct = dot( normal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
"hemiDiffuse += diffuse * hemiColor;",
// specular (sky light)
"vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
"float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
"float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
// specular (ground light)
"vec3 lVectorGround = -lVector;",
"vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
"float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
"float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
"float dotProductGround = dot( normal, lVectorGround );",
// 2.0 => 2.0001 is hack to work around ANGLE bug
"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
"vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
"vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
"hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
"}",
"#endif",
// all lights contribution summation
"vec3 totalDiffuse = vec3( 0.0 );",
"vec3 totalSpecular = vec3( 0.0 );",
"#if MAX_DIR_LIGHTS > 0",
"totalDiffuse += dirDiffuse;",
"totalSpecular += dirSpecular;",
"#endif",
"#if MAX_HEMI_LIGHTS > 0",
"totalDiffuse += hemiDiffuse;",
"totalSpecular += hemiSpecular;",
"#endif",
"#if MAX_POINT_LIGHTS > 0",
"totalDiffuse += pointDiffuse;",
"totalSpecular += pointSpecular;",
"#endif",
"#if MAX_SPOT_LIGHTS > 0",
"totalDiffuse += spotDiffuse;",
"totalSpecular += spotSpecular;",
"#endif",
"#ifdef METAL",
"gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
"#else",
"gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
"#endif",
"if ( enableReflection ) {",
"vec3 vReflect;",
"vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
"if ( useRefract ) {",
"vReflect = refract( cameraToVertex, normal, refractionRatio );",
"} else {",
"vReflect = reflect( cameraToVertex, normal );",
"}",
"vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
"#ifdef GAMMA_INPUT",
"cubeColor.xyz *= cubeColor.xyz;",
"#endif",
"gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
"}",
THREE.ShaderChunk[ "shadowmap_fragment" ],
THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join("\n"),
vertexShader: [
"attribute vec4 tangent;",
"uniform vec2 uOffset;",
"uniform vec2 uRepeat;",
"uniform bool enableDisplacement;",
"#ifdef VERTEX_TEXTURES",
"uniform sampler2D tDisplacement;",
"uniform float uDisplacementScale;",
"uniform float uDisplacementBias;",
"#endif",
"varying vec3 vTangent;",
"varying vec3 vBinormal;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vWorldPosition;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "skinning_pars_vertex" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "skinnormal_vertex" ],
// normal, tangent and binormal vectors
"#ifdef USE_SKINNING",
"vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
"vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
"vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
"#else",
"vNormal = normalize( normalMatrix * normal );",
"vTangent = normalize( normalMatrix * tangent.xyz );",
"#endif",
"vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
"vUv = uv * uRepeat + uOffset;",
// displacement mapping
"vec3 displacedPosition;",
"#ifdef VERTEX_TEXTURES",
"if ( enableDisplacement ) {",
"vec3 dv = texture2D( tDisplacement, uv ).xyz;",
"float df = uDisplacementScale * dv.x + uDisplacementBias;",
"displacedPosition = position + normalize( normal ) * df;",
"} else {",
"#ifdef USE_SKINNING",
"vec4 skinVertex = vec4( position, 1.0 );",
"vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
"skinned += boneMatY * skinVertex * skinWeight.y;",
"displacedPosition = skinned.xyz;",
"#else",
"displacedPosition = position;",
"#endif",
"}",
"#else",
"#ifdef USE_SKINNING",
"vec4 skinVertex = vec4( position, 1.0 );",
"vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
"skinned += boneMatY * skinVertex * skinWeight.y;",
"displacedPosition = skinned.xyz;",
"#else",
"displacedPosition = position;",
"#endif",
"#endif",
//
"vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
"vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
"gl_Position = projectionMatrix * mvPosition;",
//
"vWorldPosition = worldPosition.xyz;",
"vViewPosition = -mvPosition.xyz;",
// shadows
"#ifdef USE_SHADOWMAP",
"for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
"vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
"}",
"#endif",
"}"
].join("\n")
},
/* -------------------------------------------------------------------------
// Cube map shader
------------------------------------------------------------------------- */
'cube': {
uniforms: { "tCube": { type: "t", value: null },
"tFlip": { type: "f", value: -1 } },
vertexShader: [
"varying vec3 vWorldPosition;",
"void main() {",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vWorldPosition = worldPosition.xyz;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform samplerCube tCube;",
"uniform float tFlip;",
"varying vec3 vWorldPosition;",
"void main() {",
"gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
"}"
].join("\n")
},
// Depth encoding into RGBA texture
// based on SpiderGL shadow map example
// http://spidergl.org/example.php?id=6
// originally from
// http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
// see also here:
// http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
'depthRGBA': {
uniforms: {},
vertexShader: [
THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
THREE.ShaderChunk[ "skinning_pars_vertex" ],
"void main() {",
THREE.ShaderChunk[ "skinbase_vertex" ],
THREE.ShaderChunk[ "morphtarget_vertex" ],
THREE.ShaderChunk[ "skinning_vertex" ],
THREE.ShaderChunk[ "default_vertex" ],
"}"
].join("\n"),
fragmentShader: [
"vec4 pack_depth( const in float depth ) {",
"const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
"const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
"vec4 res = fract( depth * bit_shift );",
"res -= res.xxyz * bit_mask;",
"return res;",
"}",
"void main() {",
"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
//"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
//"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
//"gl_FragData[ 0 ] = pack_depth( z );",
//"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
"}"
].join("\n")
}
};
/**
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author szimek / https://github.com/szimek/
*/
THREE.WebGLRenderer = function ( parameters ) {
console.log( 'THREE.WebGLRenderer', THREE.REVISION );
parameters = parameters || {};
var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
_context = parameters.context !== undefined ? parameters.context : null,
_precision = parameters.precision !== undefined ? parameters.precision : 'highp',
_buffers = {},
_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
_clearColor = new THREE.Color( 0x000000 ),
_clearAlpha = 0;
// public properties
this.domElement = _canvas;
this.context = null;
this.devicePixelRatio = parameters.devicePixelRatio !== undefined
? parameters.devicePixelRatio
: self.devicePixelRatio !== undefined
? self.devicePixelRatio
: 1;
// clearing
this.autoClear = true;
this.autoClearColor = true;
this.autoClearDepth = true;
this.autoClearStencil = true;
// scene graph
this.sortObjects = true;
this.autoUpdateObjects = true;
// physically based shading
this.gammaInput = false;
this.gammaOutput = false;
// shadow map
this.shadowMapEnabled = false;
this.shadowMapAutoUpdate = true;
this.shadowMapType = THREE.PCFShadowMap;
this.shadowMapCullFace = THREE.CullFaceFront;
this.shadowMapDebug = false;
this.shadowMapCascade = false;
// morphs
this.maxMorphTargets = 8;
this.maxMorphNormals = 4;
// flags
this.autoScaleCubemaps = true;
// custom render plugins
this.renderPluginsPre = [];
this.renderPluginsPost = [];
// info
this.info = {
memory: {
programs: 0,
geometries: 0,
textures: 0
},
render: {
calls: 0,
vertices: 0,
faces: 0,
points: 0
}
};
// internal properties
var _this = this,
_programs = [],
_programs_counter = 0,
// internal state cache
_currentProgram = null,
_currentFramebuffer = null,
_currentMaterialId = -1,
_currentGeometryGroupHash = null,
_currentCamera = null,
_usedTextureUnits = 0,
// GL state cache
_oldDoubleSided = -1,
_oldFlipSided = -1,
_oldBlending = -1,
_oldBlendEquation = -1,
_oldBlendSrc = -1,
_oldBlendDst = -1,
_oldDepthTest = -1,
_oldDepthWrite = -1,
_oldPolygonOffset = null,
_oldPolygonOffsetFactor = null,
_oldPolygonOffsetUnits = null,
_oldLineWidth = null,
_viewportX = 0,
_viewportY = 0,
_viewportWidth = _canvas.width,
_viewportHeight = _canvas.height,
_currentWidth = 0,
_currentHeight = 0,
_enabledAttributes = new Uint8Array( 16 ),
// frustum
_frustum = new THREE.Frustum(),
// camera matrices cache
_projScreenMatrix = new THREE.Matrix4(),
_projScreenMatrixPS = new THREE.Matrix4(),
_vector3 = new THREE.Vector3(),
// light arrays cache
_direction = new THREE.Vector3(),
_lightsNeedUpdate = true,
_lights = {
ambient: [ 0, 0, 0 ],
directional: { length: 0, colors: new Array(), positions: new Array() },
point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
};
// initialize
var _gl;
var _glExtensionTextureFloat;
var _glExtensionTextureFloatLinear;
var _glExtensionStandardDerivatives;
var _glExtensionTextureFilterAnisotropic;
var _glExtensionCompressedTextureS3TC;
initGL();
setDefaultGLState();
this.context = _gl;
// GPU capabilities
var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
var _supportsVertexTextures = ( _maxVertexTextures > 0 );
var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
//
var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
// clamp precision to maximum available
var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
if ( _precision === "highp" && ! highpAvailable ) {
if ( mediumpAvailable ) {
_precision = "mediump";
console.warn( "WebGLRenderer: highp not supported, using mediump" );
} else {
_precision = "lowp";
console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
}
}
if ( _precision === "mediump" && ! mediumpAvailable ) {
_precision = "lowp";
console.warn( "WebGLRenderer: mediump not supported, using lowp" );
}
// API
this.getContext = function () {
return _gl;
};
this.supportsVertexTextures = function () {
return _supportsVertexTextures;
};
this.supportsFloatTextures = function () {
return _glExtensionTextureFloat;
};
this.supportsStandardDerivatives = function () {
return _glExtensionStandardDerivatives;
};
this.supportsCompressedTextureS3TC = function () {
return _glExtensionCompressedTextureS3TC;
};
this.getMaxAnisotropy = function () {
return _maxAnisotropy;
};
this.getPrecision = function () {
return _precision;
};
this.setSize = function ( width, height, updateStyle ) {
_canvas.width = width * this.devicePixelRatio;
_canvas.height = height * this.devicePixelRatio;
if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
_canvas.style.width = width + 'px';
_canvas.style.height = height + 'px';
}
this.setViewport( 0, 0, width, height );
};
this.setViewport = function ( x, y, width, height ) {
_viewportX = x * this.devicePixelRatio;
_viewportY = y * this.devicePixelRatio;
_viewportWidth = width * this.devicePixelRatio;
_viewportHeight = height * this.devicePixelRatio;
_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
};
this.setScissor = function ( x, y, width, height ) {
_gl.scissor(
x * this.devicePixelRatio,
y * this.devicePixelRatio,
width * this.devicePixelRatio,
height * this.devicePixelRatio
);
};
this.enableScissorTest = function ( enable ) {
enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
};
// Clearing
this.setClearColor = function ( color, alpha ) {
_clearColor.set( color );
_clearAlpha = alpha !== undefined ? alpha : 1;
_gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
};
this.setClearColorHex = function ( hex, alpha ) {
console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
this.setClearColor( hex, alpha );
};
this.getClearColor = function () {
return _clearColor;
};
this.getClearAlpha = function () {
return _clearAlpha;
};
this.clear = function ( color, depth, stencil ) {
var bits = 0;
if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
_gl.clear( bits );
};
this.clearColor = function () {
_gl.clear( _gl.COLOR_BUFFER_BIT );
};
this.clearDepth = function () {
_gl.clear( _gl.DEPTH_BUFFER_BIT );
};
this.clearStencil = function () {
_gl.clear( _gl.STENCIL_BUFFER_BIT );
};
this.clearTarget = function ( renderTarget, color, depth, stencil ) {
this.setRenderTarget( renderTarget );
this.clear( color, depth, stencil );
};
// Plugins
this.addPostPlugin = function ( plugin ) {
plugin.init( this );
this.renderPluginsPost.push( plugin );
};
this.addPrePlugin = function ( plugin ) {
plugin.init( this );
this.renderPluginsPre.push( plugin );
};
// Rendering
this.updateShadowMap = function ( scene, camera ) {
_currentProgram = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
_oldDoubleSided = -1;
_oldFlipSided = -1;
this.shadowMapPlugin.update( scene, camera );
};
// Internal functions
// Buffer allocation
function createParticleBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
_this.info.memory.geometries ++;
};
function createLineBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
geometry.__webglLineDistanceBuffer = _gl.createBuffer();
_this.info.memory.geometries ++;
};
function createMeshBuffers ( geometryGroup ) {
geometryGroup.__webglVertexBuffer = _gl.createBuffer();
geometryGroup.__webglNormalBuffer = _gl.createBuffer();
geometryGroup.__webglTangentBuffer = _gl.createBuffer();
geometryGroup.__webglColorBuffer = _gl.createBuffer();
geometryGroup.__webglUVBuffer = _gl.createBuffer();
geometryGroup.__webglUV2Buffer = _gl.createBuffer();
geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
geometryGroup.__webglFaceBuffer = _gl.createBuffer();
geometryGroup.__webglLineBuffer = _gl.createBuffer();
var m, ml;
if ( geometryGroup.numMorphTargets ) {
geometryGroup.__webglMorphTargetsBuffers = [];
for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
}
}
if ( geometryGroup.numMorphNormals ) {
geometryGroup.__webglMorphNormalsBuffers = [];
for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
}
}
_this.info.memory.geometries ++;
};
// Events
var onGeometryDispose = function ( event ) {
var geometry = event.target;
geometry.removeEventListener( 'dispose', onGeometryDispose );
deallocateGeometry( geometry );
};
var onTextureDispose = function ( event ) {
var texture = event.target;
texture.removeEventListener( 'dispose', onTextureDispose );
deallocateTexture( texture );
_this.info.memory.textures --;
};
var onRenderTargetDispose = function ( event ) {
var renderTarget = event.target;
renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
deallocateRenderTarget( renderTarget );
_this.info.memory.textures --;
};
var onMaterialDispose = function ( event ) {
var material = event.target;
material.removeEventListener( 'dispose', onMaterialDispose );
deallocateMaterial( material );
};
// Buffer deallocation
var deleteBuffers = function ( geometry ) {
if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
// custom attributes
if ( geometry.__webglCustomAttributesList !== undefined ) {
for ( var id in geometry.__webglCustomAttributesList ) {
_gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
}
}
_this.info.memory.geometries --;
};
var deallocateGeometry = function ( geometry ) {
geometry.__webglInit = undefined;
if ( geometry instanceof THREE.BufferGeometry ) {
var attributes = geometry.attributes;
for ( var key in attributes ) {
if ( attributes[ key ].buffer !== undefined ) {
_gl.deleteBuffer( attributes[ key ].buffer );
}
}
_this.info.memory.geometries --;
} else {
if ( geometry.geometryGroups !== undefined ) {
for ( var g in geometry.geometryGroups ) {
var geometryGroup = geometry.geometryGroups[ g ];
if ( geometryGroup.numMorphTargets !== undefined ) {
for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
_gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
}
}
if ( geometryGroup.numMorphNormals !== undefined ) {
for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
_gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
}
}
deleteBuffers( geometryGroup );
}
} else {
deleteBuffers( geometry );
}
}
};
var deallocateTexture = function ( texture ) {
if ( texture.image && texture.image.__webglTextureCube ) {
// cube texture
_gl.deleteTexture( texture.image.__webglTextureCube );
} else {
// 2D texture
if ( ! texture.__webglInit ) return;
texture.__webglInit = false;
_gl.deleteTexture( texture.__webglTexture );
}
};
var deallocateRenderTarget = function ( renderTarget ) {
if ( !renderTarget || ! renderTarget.__webglTexture ) return;
_gl.deleteTexture( renderTarget.__webglTexture );
if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
for ( var i = 0; i < 6; i ++ ) {
_gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
_gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
}
} else {
_gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
_gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
}
};
var deallocateMaterial = function ( material ) {
var program = material.program;
if ( program === undefined ) return;
material.program = undefined;
// only deallocate GL program if this was the last use of shared program
// assumed there is only single copy of any program in the _programs list
// (that's how it's constructed)
var i, il, programInfo;
var deleteProgram = false;
for ( i = 0, il = _programs.length; i < il; i ++ ) {
programInfo = _programs[ i ];
if ( programInfo.program === program ) {
programInfo.usedTimes --;
if ( programInfo.usedTimes === 0 ) {
deleteProgram = true;
}
break;
}
}
if ( deleteProgram === true ) {
// avoid using array.splice, this is costlier than creating new array from scratch
var newPrograms = [];
for ( i = 0, il = _programs.length; i < il; i ++ ) {
programInfo = _programs[ i ];
if ( programInfo.program !== program ) {
newPrograms.push( programInfo );
}
}
_programs = newPrograms;
_gl.deleteProgram( program );
_this.info.memory.programs --;
}
};
// Buffer initialization
function initCustomAttributes ( geometry, object ) {
var nvertices = geometry.vertices.length;
var material = object.material;
if ( material.attributes ) {
if ( geometry.__webglCustomAttributesList === undefined ) {
geometry.__webglCustomAttributesList = [];
}
for ( var a in material.attributes ) {
var attribute = material.attributes[ a ];
if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
attribute.__webglInitialized = true;
var size = 1; // "f" and "i"
if ( attribute.type === "v2" ) size = 2;
else if ( attribute.type === "v3" ) size = 3;
else if ( attribute.type === "v4" ) size = 4;
else if ( attribute.type === "c" ) size = 3;
attribute.size = size;
attribute.array = new Float32Array( nvertices * size );
attribute.buffer = _gl.createBuffer();
attribute.buffer.belongsToAttribute = a;
attribute.needsUpdate = true;
}
geometry.__webglCustomAttributesList.push( attribute );
}
}
};
function initParticleBuffers ( geometry, object ) {
var nvertices = geometry.vertices.length;
geometry.__vertexArray = new Float32Array( nvertices * 3 );
geometry.__colorArray = new Float32Array( nvertices * 3 );
geometry.__sortArray = [];
geometry.__webglParticleCount = nvertices;
initCustomAttributes ( geometry, object );
};
function initLineBuffers ( geometry, object ) {
var nvertices = geometry.vertices.length;
geometry.__vertexArray = new Float32Array( nvertices * 3 );
geometry.__colorArray = new Float32Array( nvertices * 3 );
geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
geometry.__webglLineCount = nvertices;
initCustomAttributes ( geometry, object );
};
function initMeshBuffers ( geometryGroup, object ) {
var geometry = object.geometry,
faces3 = geometryGroup.faces3,
nvertices = faces3.length * 3,
ntris = faces3.length * 1,
nlines = faces3.length * 3,
material = getBufferMaterial( object, geometryGroup ),
uvType = bufferGuessUVType( material ),
normalType = bufferGuessNormalType( material ),
vertexColorType = bufferGuessVertexColorType( material );
// console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
if ( normalType ) {
geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
}
if ( geometry.hasTangents ) {
geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
}
if ( vertexColorType ) {
geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
}
if ( uvType ) {
if ( geometry.faceVertexUvs.length > 0 ) {
geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
}
if ( geometry.faceVertexUvs.length > 1 ) {
geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
}
}
if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
}
geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
var m, ml;
if ( geometryGroup.numMorphTargets ) {
geometryGroup.__morphTargetsArrays = [];
for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
}
}
if ( geometryGroup.numMorphNormals ) {
geometryGroup.__morphNormalsArrays = [];
for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
}
}
geometryGroup.__webglFaceCount = ntris * 3;
geometryGroup.__webglLineCount = nlines * 2;
// custom attributes
if ( material.attributes ) {
if ( geometryGroup.__webglCustomAttributesList === undefined ) {
geometryGroup.__webglCustomAttributesList = [];
}
for ( var a in material.attributes ) {
// Do a shallow copy of the attribute object so different geometryGroup chunks use different
// attribute buffers which are correctly indexed in the setMeshBuffers function
var originalAttribute = material.attributes[ a ];
var attribute = {};
for ( var property in originalAttribute ) {
attribute[ property ] = originalAttribute[ property ];
}
if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
attribute.__webglInitialized = true;
var size = 1; // "f" and "i"
if( attribute.type === "v2" ) size = 2;
else if( attribute.type === "v3" ) size = 3;
else if( attribute.type === "v4" ) size = 4;
else if( attribute.type === "c" ) size = 3;
attribute.size = size;
attribute.array = new Float32Array( nvertices * size );
attribute.buffer = _gl.createBuffer();
attribute.buffer.belongsToAttribute = a;
originalAttribute.needsUpdate = true;
attribute.__original = originalAttribute;
}
geometryGroup.__webglCustomAttributesList.push( attribute );
}
}
geometryGroup.__inittedArrays = true;
};
function getBufferMaterial( object, geometryGroup ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ geometryGroup.materialIndex ]
: object.material;
};
function materialNeedsSmoothNormals ( material ) {
return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
};
function bufferGuessNormalType ( material ) {
// only MeshBasicMaterial and MeshDepthMaterial don't need normals
if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
return false;
}
if ( materialNeedsSmoothNormals( material ) ) {
return THREE.SmoothShading;
} else {
return THREE.FlatShading;
}
};
function bufferGuessVertexColorType( material ) {
if ( material.vertexColors ) {
return material.vertexColors;
}
return false;
};
function bufferGuessUVType( material ) {
// material must use some texture to require uvs
if ( material.map ||
material.lightMap ||
material.bumpMap ||
material.normalMap ||
material.specularMap ||
material instanceof THREE.ShaderMaterial ) {
return true;
}
return false;
};
//
function initDirectBuffers( geometry ) {
var a, attribute, type;
for ( a in geometry.attributes ) {
if ( a === "index" ) {
type = _gl.ELEMENT_ARRAY_BUFFER;
} else {
type = _gl.ARRAY_BUFFER;
}
attribute = geometry.attributes[ a ];
attribute.buffer = _gl.createBuffer();
_gl.bindBuffer( type, attribute.buffer );
_gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
}
};
// Buffer setting
function setParticleBuffers ( geometry, hint, object ) {
var v, c, vertex, offset, index, color,
vertices = geometry.vertices,
vl = vertices.length,
colors = geometry.colors,
cl = colors.length,
vertexArray = geometry.__vertexArray,
colorArray = geometry.__colorArray,
sortArray = geometry.__sortArray,
dirtyVertices = geometry.verticesNeedUpdate,
dirtyElements = geometry.elementsNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
customAttributes = geometry.__webglCustomAttributesList,
i, il,
a, ca, cal, value,
customAttribute;
if ( object.sortParticles ) {
_projScreenMatrixPS.copy( _projScreenMatrix );
_projScreenMatrixPS.multiply( object.matrixWorld );
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
_vector3.copy( vertex );
_vector3.applyProjection( _projScreenMatrixPS );
sortArray[ v ] = [ _vector3.z, v ];
}
sortArray.sort( numericalSort );
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ sortArray[v][1] ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
for ( c = 0; c < cl; c ++ ) {
offset = c * 3;
color = colors[ sortArray[c][1] ];
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
offset = 0;
cal = customAttribute.value.length;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
customAttribute.array[ ca ] = customAttribute.value[ index ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
}
}
} else {
if ( dirtyVertices ) {
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
}
if ( dirtyColors ) {
for ( c = 0; c < cl; c ++ ) {
color = colors[ c ];
offset = c * 3;
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate &&
( customAttribute.boundTo === undefined ||
customAttribute.boundTo === "vertices") ) {
cal = customAttribute.value.length;
offset = 0;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
customAttribute.array[ ca ] = customAttribute.value[ ca ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
}
}
}
}
if ( dirtyVertices || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyColors || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
}
};
function setLineBuffers ( geometry, hint ) {
var v, c, d, vertex, offset, color,
vertices = geometry.vertices,
colors = geometry.colors,
lineDistances = geometry.lineDistances,
vl = vertices.length,
cl = colors.length,
dl = lineDistances.length,
vertexArray = geometry.__vertexArray,
colorArray = geometry.__colorArray,
lineDistanceArray = geometry.__lineDistanceArray,
dirtyVertices = geometry.verticesNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
dirtyLineDistances = geometry.lineDistancesNeedUpdate,
customAttributes = geometry.__webglCustomAttributesList,
i, il,
a, ca, cal, value,
customAttribute;
if ( dirtyVertices ) {
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyColors ) {
for ( c = 0; c < cl; c ++ ) {
color = colors[ c ];
offset = c * 3;
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
if ( dirtyLineDistances ) {
for ( d = 0; d < dl; d ++ ) {
lineDistanceArray[ d ] = lineDistances[ d ];
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate &&
( customAttribute.boundTo === undefined ||
customAttribute.boundTo === "vertices" ) ) {
offset = 0;
cal = customAttribute.value.length;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
customAttribute.array[ ca ] = customAttribute.value[ ca ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
}
};
function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
if ( ! geometryGroup.__inittedArrays ) {
return;
}
var normalType = bufferGuessNormalType( material ),
vertexColorType = bufferGuessVertexColorType( material ),
uvType = bufferGuessUVType( material ),
needsSmoothNormals = ( normalType === THREE.SmoothShading );
var f, fl, fi, face,
vertexNormals, faceNormal, normal,
vertexColors, faceColor,
vertexTangents,
uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
c1, c2, c3, c4,
sw1, sw2, sw3, sw4,
si1, si2, si3, si4,
sa1, sa2, sa3, sa4,
sb1, sb2, sb3, sb4,
m, ml, i, il,
vn, uvi, uv2i,
vk, vkl, vka,
nka, chf, faceVertexNormals,
a,
vertexIndex = 0,
offset = 0,
offset_uv = 0,
offset_uv2 = 0,
offset_face = 0,
offset_normal = 0,
offset_tangent = 0,
offset_line = 0,
offset_color = 0,
offset_skin = 0,
offset_morphTarget = 0,
offset_custom = 0,
offset_customSrc = 0,
value,
vertexArray = geometryGroup.__vertexArray,
uvArray = geometryGroup.__uvArray,
uv2Array = geometryGroup.__uv2Array,
normalArray = geometryGroup.__normalArray,
tangentArray = geometryGroup.__tangentArray,
colorArray = geometryGroup.__colorArray,
skinIndexArray = geometryGroup.__skinIndexArray,
skinWeightArray = geometryGroup.__skinWeightArray,
morphTargetsArrays = geometryGroup.__morphTargetsArrays,
morphNormalsArrays = geometryGroup.__morphNormalsArrays,
customAttributes = geometryGroup.__webglCustomAttributesList,
customAttribute,
faceArray = geometryGroup.__faceArray,
lineArray = geometryGroup.__lineArray,
geometry = object.geometry, // this is shared for all chunks
dirtyVertices = geometry.verticesNeedUpdate,
dirtyElements = geometry.elementsNeedUpdate,
dirtyUvs = geometry.uvsNeedUpdate,
dirtyNormals = geometry.normalsNeedUpdate,
dirtyTangents = geometry.tangentsNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
vertices = geometry.vertices,
chunk_faces3 = geometryGroup.faces3,
obj_faces = geometry.faces,
obj_uvs = geometry.faceVertexUvs[ 0 ],
obj_uvs2 = geometry.faceVertexUvs[ 1 ],
obj_colors = geometry.colors,
obj_skinIndices = geometry.skinIndices,
obj_skinWeights = geometry.skinWeights,
morphTargets = geometry.morphTargets,
morphNormals = geometry.morphNormals;
if ( dirtyVertices ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = vertices[ face.a ];
v2 = vertices[ face.b ];
v3 = vertices[ face.c ];
vertexArray[ offset ] = v1.x;
vertexArray[ offset + 1 ] = v1.y;
vertexArray[ offset + 2 ] = v1.z;
vertexArray[ offset + 3 ] = v2.x;
vertexArray[ offset + 4 ] = v2.y;
vertexArray[ offset + 5 ] = v2.z;
vertexArray[ offset + 6 ] = v3.x;
vertexArray[ offset + 7 ] = v3.y;
vertexArray[ offset + 8 ] = v3.z;
offset += 9;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyMorphTargets ) {
for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
offset_morphTarget = 0;
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
chf = chunk_faces3[ f ];
face = obj_faces[ chf ];
// morph positions
v1 = morphTargets[ vk ].vertices[ face.a ];
v2 = morphTargets[ vk ].vertices[ face.b ];
v3 = morphTargets[ vk ].vertices[ face.c ];
vka = morphTargetsArrays[ vk ];
vka[ offset_morphTarget ] = v1.x;
vka[ offset_morphTarget + 1 ] = v1.y;
vka[ offset_morphTarget + 2 ] = v1.z;
vka[ offset_morphTarget + 3 ] = v2.x;
vka[ offset_morphTarget + 4 ] = v2.y;
vka[ offset_morphTarget + 5 ] = v2.z;
vka[ offset_morphTarget + 6 ] = v3.x;
vka[ offset_morphTarget + 7 ] = v3.y;
vka[ offset_morphTarget + 8 ] = v3.z;
// morph normals
if ( material.morphNormals ) {
if ( needsSmoothNormals ) {
faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
n1 = faceVertexNormals.a;
n2 = faceVertexNormals.b;
n3 = faceVertexNormals.c;
} else {
n1 = morphNormals[ vk ].faceNormals[ chf ];
n2 = n1;
n3 = n1;
}
nka = morphNormalsArrays[ vk ];
nka[ offset_morphTarget ] = n1.x;
nka[ offset_morphTarget + 1 ] = n1.y;
nka[ offset_morphTarget + 2 ] = n1.z;
nka[ offset_morphTarget + 3 ] = n2.x;
nka[ offset_morphTarget + 4 ] = n2.y;
nka[ offset_morphTarget + 5 ] = n2.z;
nka[ offset_morphTarget + 6 ] = n3.x;
nka[ offset_morphTarget + 7 ] = n3.y;
nka[ offset_morphTarget + 8 ] = n3.z;
}
//
offset_morphTarget += 9;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
_gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
if ( material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
_gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
}
}
}
if ( obj_skinWeights.length ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
// weights
sw1 = obj_skinWeights[ face.a ];
sw2 = obj_skinWeights[ face.b ];
sw3 = obj_skinWeights[ face.c ];
skinWeightArray[ offset_skin ] = sw1.x;
skinWeightArray[ offset_skin + 1 ] = sw1.y;
skinWeightArray[ offset_skin + 2 ] = sw1.z;
skinWeightArray[ offset_skin + 3 ] = sw1.w;
skinWeightArray[ offset_skin + 4 ] = sw2.x;
skinWeightArray[ offset_skin + 5 ] = sw2.y;
skinWeightArray[ offset_skin + 6 ] = sw2.z;
skinWeightArray[ offset_skin + 7 ] = sw2.w;
skinWeightArray[ offset_skin + 8 ] = sw3.x;
skinWeightArray[ offset_skin + 9 ] = sw3.y;
skinWeightArray[ offset_skin + 10 ] = sw3.z;
skinWeightArray[ offset_skin + 11 ] = sw3.w;
// indices
si1 = obj_skinIndices[ face.a ];
si2 = obj_skinIndices[ face.b ];
si3 = obj_skinIndices[ face.c ];
skinIndexArray[ offset_skin ] = si1.x;
skinIndexArray[ offset_skin + 1 ] = si1.y;
skinIndexArray[ offset_skin + 2 ] = si1.z;
skinIndexArray[ offset_skin + 3 ] = si1.w;
skinIndexArray[ offset_skin + 4 ] = si2.x;
skinIndexArray[ offset_skin + 5 ] = si2.y;
skinIndexArray[ offset_skin + 6 ] = si2.z;
skinIndexArray[ offset_skin + 7 ] = si2.w;
skinIndexArray[ offset_skin + 8 ] = si3.x;
skinIndexArray[ offset_skin + 9 ] = si3.y;
skinIndexArray[ offset_skin + 10 ] = si3.z;
skinIndexArray[ offset_skin + 11 ] = si3.w;
offset_skin += 12;
}
if ( offset_skin > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
}
}
if ( dirtyColors && vertexColorType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexColors = face.vertexColors;
faceColor = face.color;
if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
c1 = vertexColors[ 0 ];
c2 = vertexColors[ 1 ];
c3 = vertexColors[ 2 ];
} else {
c1 = faceColor;
c2 = faceColor;
c3 = faceColor;
}
colorArray[ offset_color ] = c1.r;
colorArray[ offset_color + 1 ] = c1.g;
colorArray[ offset_color + 2 ] = c1.b;
colorArray[ offset_color + 3 ] = c2.r;
colorArray[ offset_color + 4 ] = c2.g;
colorArray[ offset_color + 5 ] = c2.b;
colorArray[ offset_color + 6 ] = c3.r;
colorArray[ offset_color + 7 ] = c3.g;
colorArray[ offset_color + 8 ] = c3.b;
offset_color += 9;
}
if ( offset_color > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
}
if ( dirtyTangents && geometry.hasTangents ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexTangents = face.vertexTangents;
t1 = vertexTangents[ 0 ];
t2 = vertexTangents[ 1 ];
t3 = vertexTangents[ 2 ];
tangentArray[ offset_tangent ] = t1.x;
tangentArray[ offset_tangent + 1 ] = t1.y;
tangentArray[ offset_tangent + 2 ] = t1.z;
tangentArray[ offset_tangent + 3 ] = t1.w;
tangentArray[ offset_tangent + 4 ] = t2.x;
tangentArray[ offset_tangent + 5 ] = t2.y;
tangentArray[ offset_tangent + 6 ] = t2.z;
tangentArray[ offset_tangent + 7 ] = t2.w;
tangentArray[ offset_tangent + 8 ] = t3.x;
tangentArray[ offset_tangent + 9 ] = t3.y;
tangentArray[ offset_tangent + 10 ] = t3.z;
tangentArray[ offset_tangent + 11 ] = t3.w;
offset_tangent += 12;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
}
if ( dirtyNormals && normalType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexNormals = face.vertexNormals;
faceNormal = face.normal;
if ( vertexNormals.length === 3 && needsSmoothNormals ) {
for ( i = 0; i < 3; i ++ ) {
vn = vertexNormals[ i ];
normalArray[ offset_normal ] = vn.x;
normalArray[ offset_normal + 1 ] = vn.y;
normalArray[ offset_normal + 2 ] = vn.z;
offset_normal += 3;
}
} else {
for ( i = 0; i < 3; i ++ ) {
normalArray[ offset_normal ] = faceNormal.x;
normalArray[ offset_normal + 1 ] = faceNormal.y;
normalArray[ offset_normal + 2 ] = faceNormal.z;
offset_normal += 3;
}
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
}
if ( dirtyUvs && obj_uvs && uvType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
fi = chunk_faces3[ f ];
uv = obj_uvs[ fi ];
if ( uv === undefined ) continue;
for ( i = 0; i < 3; i ++ ) {
uvi = uv[ i ];
uvArray[ offset_uv ] = uvi.x;
uvArray[ offset_uv + 1 ] = uvi.y;
offset_uv += 2;
}
}
if ( offset_uv > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
}
}
if ( dirtyUvs && obj_uvs2 && uvType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
fi = chunk_faces3[ f ];
uv2 = obj_uvs2[ fi ];
if ( uv2 === undefined ) continue;
for ( i = 0; i < 3; i ++ ) {
uv2i = uv2[ i ];
uv2Array[ offset_uv2 ] = uv2i.x;
uv2Array[ offset_uv2 + 1 ] = uv2i.y;
offset_uv2 += 2;
}
}
if ( offset_uv2 > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
}
}
if ( dirtyElements ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
faceArray[ offset_face ] = vertexIndex;
faceArray[ offset_face + 1 ] = vertexIndex + 1;
faceArray[ offset_face + 2 ] = vertexIndex + 2;
offset_face += 3;
lineArray[ offset_line ] = vertexIndex;
lineArray[ offset_line + 1 ] = vertexIndex + 1;
lineArray[ offset_line + 2 ] = vertexIndex;
lineArray[ offset_line + 3 ] = vertexIndex + 2;
lineArray[ offset_line + 4 ] = vertexIndex + 1;
lineArray[ offset_line + 5 ] = vertexIndex + 2;
offset_line += 6;
vertexIndex += 3;
}
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( ! customAttribute.__original.needsUpdate ) continue;
offset_custom = 0;
offset_customSrc = 0;
if ( customAttribute.size === 1 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
offset_custom += 3;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
customAttribute.array[ offset_custom ] = value;
customAttribute.array[ offset_custom + 1 ] = value;
customAttribute.array[ offset_custom + 2 ] = value;
offset_custom += 3;
}
}
} else if ( customAttribute.size === 2 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
offset_custom += 6;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
offset_custom += 6;
}
}
} else if ( customAttribute.size === 3 ) {
var pp;
if ( customAttribute.type === "c" ) {
pp = [ "r", "g", "b" ];
} else {
pp = [ "x", "y", "z" ];
}
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
} else if ( customAttribute.boundTo === "faceVertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
}
} else if ( customAttribute.size === 4 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
} else if ( customAttribute.boundTo === "faceVertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
if ( dispose ) {
delete geometryGroup.__inittedArrays;
delete geometryGroup.__colorArray;
delete geometryGroup.__normalArray;
delete geometryGroup.__tangentArray;
delete geometryGroup.__uvArray;
delete geometryGroup.__uv2Array;
delete geometryGroup.__faceArray;
delete geometryGroup.__vertexArray;
delete geometryGroup.__lineArray;
delete geometryGroup.__skinIndexArray;
delete geometryGroup.__skinWeightArray;
}
};
// used by renderBufferDirect for THREE.Line
function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
var attributeItem, attributeName, attributePointer, attributeSize;
for ( attributeName in programAttributes ) {
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
} else if ( material.defaultAttributeValues ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
}
function setDirectBuffers( geometry, hint ) {
var attributes = geometry.attributes;
var attributeName, attributeItem;
for ( attributeName in attributes ) {
attributeItem = attributes[ attributeName ];
if ( attributeItem.needsUpdate ) {
if ( attributeName === 'index' ) {
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
} else {
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
}
attributeItem.needsUpdate = false;
}
}
}
// Buffer rendering
this.renderBufferImmediate = function ( object, program, material ) {
if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
if ( object.hasPositions ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.position );
_gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
if ( material.shading === THREE.FlatShading ) {
var nx, ny, nz,
nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
normalArray,
i, il = object.count * 3;
for( i = 0; i < il; i += 9 ) {
normalArray = object.normalArray;
nax = normalArray[ i ];
nay = normalArray[ i + 1 ];
naz = normalArray[ i + 2 ];
nbx = normalArray[ i + 3 ];
nby = normalArray[ i + 4 ];
nbz = normalArray[ i + 5 ];
ncx = normalArray[ i + 6 ];
ncy = normalArray[ i + 7 ];
ncz = normalArray[ i + 8 ];
nx = ( nax + nbx + ncx ) / 3;
ny = ( nay + nby + ncy ) / 3;
nz = ( naz + nbz + ncz ) / 3;
normalArray[ i ] = nx;
normalArray[ i + 1 ] = ny;
normalArray[ i + 2 ] = nz;
normalArray[ i + 3 ] = nx;
normalArray[ i + 4 ] = ny;
normalArray[ i + 5 ] = nz;
normalArray[ i + 6 ] = nx;
normalArray[ i + 7 ] = ny;
normalArray[ i + 8 ] = nz;
}
}
_gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.normal );
_gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasUvs && material.map ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.uv );
_gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.color );
_gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
}
_gl.drawArrays( _gl.TRIANGLES, 0, object.count );
object.count = 0;
};
this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
if ( material.visible === false ) return;
var linewidth, a, attribute;
var attributeItem, attributeName, attributePointer, attributeSize;
var program = setProgram( camera, lights, fog, material, object );
var programAttributes = program.attributes;
var geometryAttributes = geometry.attributes;
var updateBuffers = false,
wireframeBit = material.wireframe ? 1 : 0,
geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
if ( geometryHash !== _currentGeometryGroupHash ) {
_currentGeometryGroupHash = geometryHash;
updateBuffers = true;
}
if ( updateBuffers ) {
disableAttributes();
}
// render mesh
if ( object instanceof THREE.Mesh ) {
var index = geometryAttributes[ "index" ];
// indexed triangles
if ( index ) {
var offsets = geometry.offsets;
// if there is more than 1 chunk
// must set attribute pointers to use new offsets for each chunk
// even if geometry and materials didn't change
if ( offsets.length > 1 ) updateBuffers = true;
for ( var i = 0, il = offsets.length; i < il; i ++ ) {
var startIndex = offsets[ i ].index;
if ( updateBuffers ) {
for ( attributeName in programAttributes ) {
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
} else if ( material.defaultAttributeValues ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
// indices
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
}
// render indexed triangles
_gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
_this.info.render.calls ++;
_this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
_this.info.render.faces += offsets[ i ].count / 3;
}
// non-indexed triangles
} else {
if ( updateBuffers ) {
for ( attributeName in programAttributes ) {
if ( attributeName === 'index') continue;
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
}
var position = geometry.attributes[ "position" ];
// render non-indexed triangles
_gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
_this.info.render.calls ++;
_this.info.render.vertices += position.array.length / 3;
_this.info.render.faces += position.array.length / 3 / 3;
}
// render particles
} else if ( object instanceof THREE.ParticleSystem ) {
if ( updateBuffers ) {
for ( attributeName in programAttributes ) {
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
}
var position = geometryAttributes[ "position" ];
// render particles
_gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
_this.info.render.calls ++;
_this.info.render.points += position.array.length / 3;
} else if ( object instanceof THREE.Line ) {
var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
setLineWidth( material.linewidth );
var index = geometryAttributes[ "index" ];
// indexed lines
if ( index ) {
var offsets = geometry.offsets;
// if there is more than 1 chunk
// must set attribute pointers to use new offsets for each chunk
// even if geometry and materials didn't change
if ( offsets.length > 1 ) updateBuffers = true;
for ( var i = 0, il = offsets.length; i < il; i ++ ) {
var startIndex = offsets[ i ].index;
if ( updateBuffers ) {
setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex);
// indices
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
}
// render indexed lines
_gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array
_this.info.render.calls ++;
_this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
}
}
// non-indexed lines
else {
if ( updateBuffers ) {
setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0);
}
var position = geometryAttributes[ "position" ];
_gl.drawArrays( primitives, 0, position.array.length / 3 );
_this.info.render.calls ++;
_this.info.render.points += position.array.length;
}
}
};
this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
if ( material.visible === false ) return;
var linewidth, a, attribute, i, il;
var program = setProgram( camera, lights, fog, material, object );
var attributes = program.attributes;
var updateBuffers = false,
wireframeBit = material.wireframe ? 1 : 0,
geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
if ( geometryGroupHash !== _currentGeometryGroupHash ) {
_currentGeometryGroupHash = geometryGroupHash;
updateBuffers = true;
}
if ( updateBuffers ) {
disableAttributes();
}
// vertices
if ( !material.morphTargets && attributes.position >= 0 ) {
if ( updateBuffers ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
enableAttribute( attributes.position );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
} else {
if ( object.morphTargetBase ) {
setupMorphTargets( material, geometryGroup, object );
}
}
if ( updateBuffers ) {
// custom attributes
// Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
if ( geometryGroup.__webglCustomAttributesList ) {
for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
attribute = geometryGroup.__webglCustomAttributesList[ i ];
if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
_gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
}
}
}
// colors
if ( attributes.color >= 0 ) {
if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
enableAttribute( attributes.color );
_gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues ) {
_gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
}
}
// normals
if ( attributes.normal >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
enableAttribute( attributes.normal );
_gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
}
// tangents
if ( attributes.tangent >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
enableAttribute( attributes.tangent );
_gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
}
// uvs
if ( attributes.uv >= 0 ) {
if ( object.geometry.faceVertexUvs[0] ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
enableAttribute( attributes.uv );
_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues ) {
_gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
}
}
if ( attributes.uv2 >= 0 ) {
if ( object.geometry.faceVertexUvs[1] ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
enableAttribute( attributes.uv2 );
_gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues ) {
_gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
}
}
if ( material.skinning &&
attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
enableAttribute( attributes.skinIndex );
_gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
enableAttribute( attributes.skinWeight );
_gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
}
// line distances
if ( attributes.lineDistance >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
enableAttribute( attributes.lineDistance );
_gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
}
}
// render mesh
if ( object instanceof THREE.Mesh ) {
// wireframe
if ( material.wireframe ) {
setLineWidth( material.wireframeLinewidth );
if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
_gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
// triangles
} else {
if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
_gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
}
_this.info.render.calls ++;
_this.info.render.vertices += geometryGroup.__webglFaceCount;
_this.info.render.faces += geometryGroup.__webglFaceCount / 3;
// render lines
} else if ( object instanceof THREE.Line ) {
var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
setLineWidth( material.linewidth );
_gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
_this.info.render.calls ++;
// render particles
} else if ( object instanceof THREE.ParticleSystem ) {
_gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
_this.info.render.calls ++;
_this.info.render.points += geometryGroup.__webglParticleCount;
}
};
function enableAttribute( attribute ) {
if ( _enabledAttributes[ attribute ] === 0 ) {
_gl.enableVertexAttribArray( attribute );
_enabledAttributes[ attribute ] = 1;
}
};
function disableAttributes() {
for ( var attribute in _enabledAttributes ) {
if ( _enabledAttributes[ attribute ] === 1 ) {
_gl.disableVertexAttribArray( attribute );
_enabledAttributes[ attribute ] = 0;
}
}
};
function setupMorphTargets ( material, geometryGroup, object ) {
// set base
var attributes = material.program.attributes;
if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
enableAttribute( attributes.position );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
} else if ( attributes.position >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
enableAttribute( attributes.position );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.morphTargetForcedOrder.length ) {
// set forced order
var m = 0;
var order = object.morphTargetForcedOrder;
var influences = object.morphTargetInfluences;
while ( m < material.numSupportedMorphTargets && m < order.length ) {
if ( attributes[ "morphTarget" + m ] >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
enableAttribute( attributes[ "morphTarget" + m ] );
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
enableAttribute( attributes[ "morphNormal" + m ] );
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
m ++;
}
} else {
// find the most influencing
var influence, activeInfluenceIndices = [];
var influences = object.morphTargetInfluences;
var i, il = influences.length;
for ( i = 0; i < il; i ++ ) {
influence = influences[ i ];
if ( influence > 0 ) {
activeInfluenceIndices.push( [ influence, i ] );
}
}
if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
activeInfluenceIndices.sort( numericalSort );
activeInfluenceIndices.length = material.numSupportedMorphTargets;
} else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
activeInfluenceIndices.sort( numericalSort );
} else if ( activeInfluenceIndices.length === 0 ) {
activeInfluenceIndices.push( [ 0, 0 ] );
};
var influenceIndex, m = 0;
while ( m < material.numSupportedMorphTargets ) {
if ( activeInfluenceIndices[ m ] ) {
influenceIndex = activeInfluenceIndices[ m ][ 1 ];
if ( attributes[ "morphTarget" + m ] >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
enableAttribute( attributes[ "morphTarget" + m ] );
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
enableAttribute( attributes[ "morphNormal" + m ] );
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
} else {
/*
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
if ( material.morphNormals ) {
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
*/
object.__webglMorphTargetInfluences[ m ] = 0;
}
m ++;
}
}
// load updated influences uniform
if ( material.program.uniforms.morphTargetInfluences !== null ) {
_gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
}
};
// Sorting
function painterSortStable ( a, b ) {
if ( a.z !== b.z ) {
return b.z - a.z;
} else {
return a.id - b.id;
}
};
function numericalSort ( a, b ) {
return b[ 0 ] - a[ 0 ];
};
// Rendering
this.render = function ( scene, camera, renderTarget, forceClear ) {
if ( camera instanceof THREE.Camera === false ) {
console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
return;
}
var i, il,
webglObject, object,
renderList,
lights = scene.__lights,
fog = scene.fog;
// reset caching for this frame
_currentMaterialId = -1;
_lightsNeedUpdate = true;
// update scene graph
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
// update camera matrices and frustum
if ( camera.parent === undefined ) camera.updateMatrixWorld();
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// update WebGL objects
if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
// custom render plugins (pre pass)
renderPlugins( this.renderPluginsPre, scene, camera );
//
_this.info.render.calls = 0;
_this.info.render.vertices = 0;
_this.info.render.faces = 0;
_this.info.render.points = 0;
this.setRenderTarget( renderTarget );
if ( this.autoClear || forceClear ) {
this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
}
// set matrices for regular objects (frustum culled)
renderList = scene.__webglObjects;
for ( i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
webglObject.id = i;
webglObject.render = false;
if ( object.visible ) {
if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
setupMatrices( object, camera );
unrollBufferMaterial( webglObject );
webglObject.render = true;
if ( this.sortObjects === true ) {
if ( object.renderDepth !== null ) {
webglObject.z = object.renderDepth;
} else {
_vector3.setFromMatrixPosition( object.matrixWorld );
_vector3.applyProjection( _projScreenMatrix );
webglObject.z = _vector3.z;
}
}
}
}
}
if ( this.sortObjects ) {
renderList.sort( painterSortStable );
}
// set matrices for immediate objects
renderList = scene.__webglObjectsImmediate;
for ( i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
if ( object.visible ) {
setupMatrices( object, camera );
unrollImmediateBufferMaterial( webglObject );
}
}
if ( scene.overrideMaterial ) {
var material = scene.overrideMaterial;
this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
this.setDepthTest( material.depthTest );
this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
} else {
var material = null;
// opaque pass (front-to-back order)
this.setBlending( THREE.NoBlending );
renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
// transparent pass (back-to-front order)
renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
}
// custom render plugins (post pass)
renderPlugins( this.renderPluginsPost, scene, camera );
// Generate mipmap if we're using any kind of mipmap filtering
if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
updateRenderTargetMipmap( renderTarget );
}
// Ensure depth buffer writing is enabled so it can be cleared on next render
this.setDepthTest( true );
this.setDepthWrite( true );
// _gl.finish();
};
function renderPlugins( plugins, scene, camera ) {
if ( ! plugins.length ) return;
for ( var i = 0, il = plugins.length; i < il; i ++ ) {
// reset state for plugin (to start from clean slate)
_currentProgram = null;
_currentCamera = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_oldDoubleSided = -1;
_oldFlipSided = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
// reset state after plugin (anything could have changed)
_currentProgram = null;
_currentCamera = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_oldDoubleSided = -1;
_oldFlipSided = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
}
};
function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
var webglObject, object, buffer, material, start, end, delta;
if ( reverse ) {
start = renderList.length - 1;
end = -1;
delta = -1;
} else {
start = 0;
end = renderList.length;
delta = 1;
}
for ( var i = start; i !== end; i += delta ) {
webglObject = renderList[ i ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
if ( overrideMaterial ) {
material = overrideMaterial;
} else {
material = webglObject[ materialType ];
if ( ! material ) continue;
if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
_this.setDepthTest( material.depthTest );
_this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
}
_this.setMaterialFaces( material );
if ( buffer instanceof THREE.BufferGeometry ) {
_this.renderBufferDirect( camera, lights, fog, material, buffer, object );
} else {
_this.renderBuffer( camera, lights, fog, material, buffer, object );
}
}
}
};
function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
var webglObject, object, material, program;
for ( var i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
if ( object.visible ) {
if ( overrideMaterial ) {
material = overrideMaterial;
} else {
material = webglObject[ materialType ];
if ( ! material ) continue;
if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
_this.setDepthTest( material.depthTest );
_this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
}
_this.renderImmediateObject( camera, lights, fog, material, object );
}
}
};
this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
var program = setProgram( camera, lights, fog, material, object );
_currentGeometryGroupHash = -1;
_this.setMaterialFaces( material );
if ( object.immediateRenderCallback ) {
object.immediateRenderCallback( program, _gl, _frustum );
} else {
object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
}
};
function unrollImmediateBufferMaterial ( globject ) {
var object = globject.object,
material = object.material;
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
};
function unrollBufferMaterial ( globject ) {
var object = globject.object;
var buffer = globject.buffer;
var geometry = object.geometry;
var material = object.material;
if ( material instanceof THREE.MeshFaceMaterial ) {
var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
material = material.materials[ materialIndex ];
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
} else {
if ( material ) {
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
}
}
};
// Objects refresh
this.initWebGLObjects = function ( scene ) {
if ( !scene.__webglObjects ) {
scene.__webglObjects = [];
scene.__webglObjectsImmediate = [];
scene.__webglSprites = [];
scene.__webglFlares = [];
}
while ( scene.__objectsAdded.length ) {
addObject( scene.__objectsAdded[ 0 ], scene );
scene.__objectsAdded.splice( 0, 1 );
}
while ( scene.__objectsRemoved.length ) {
removeObject( scene.__objectsRemoved[ 0 ], scene );
scene.__objectsRemoved.splice( 0, 1 );
}
// update must be called after objects adding / removal
for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
var object = scene.__webglObjects[ o ].object;
// TODO: Remove this hack (WebGLRenderer refactoring)
if ( object.__webglInit === undefined ) {
if ( object.__webglActive !== undefined ) {
removeObject( object, scene );
}
addObject( object, scene );
}
updateObject( object );
}
};
// Objects adding
function addObject( object, scene ) {
var g, geometry, material, geometryGroup;
if ( object.__webglInit === undefined ) {
object.__webglInit = true;
object._modelViewMatrix = new THREE.Matrix4();
object._normalMatrix = new THREE.Matrix3();
if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
object.geometry.__webglInit = true;
object.geometry.addEventListener( 'dispose', onGeometryDispose );
}
geometry = object.geometry;
if ( geometry === undefined ) {
// fail silently for now
} else if ( geometry instanceof THREE.BufferGeometry ) {
initDirectBuffers( geometry );
} else if ( object instanceof THREE.Mesh ) {
material = object.material;
if ( geometry.geometryGroups === undefined ) {
geometry.makeGroups( material instanceof THREE.MeshFaceMaterial );
}
// create separate VBOs per geometry chunk
for ( g in geometry.geometryGroups ) {
geometryGroup = geometry.geometryGroups[ g ];
// initialise VBO on the first access
if ( ! geometryGroup.__webglVertexBuffer ) {
createMeshBuffers( geometryGroup );
initMeshBuffers( geometryGroup, object );
geometry.verticesNeedUpdate = true;
geometry.morphTargetsNeedUpdate = true;
geometry.elementsNeedUpdate = true;
geometry.uvsNeedUpdate = true;
geometry.normalsNeedUpdate = true;
geometry.tangentsNeedUpdate = true;
geometry.colorsNeedUpdate = true;
}
}
} else if ( object instanceof THREE.Line ) {
if ( ! geometry.__webglVertexBuffer ) {
createLineBuffers( geometry );
initLineBuffers( geometry, object );
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
geometry.lineDistancesNeedUpdate = true;
}
} else if ( object instanceof THREE.ParticleSystem ) {
if ( ! geometry.__webglVertexBuffer ) {
createParticleBuffers( geometry );
initParticleBuffers( geometry, object );
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
}
}
}
if ( object.__webglActive === undefined ) {
if ( object instanceof THREE.Mesh ) {
geometry = object.geometry;
if ( geometry instanceof THREE.BufferGeometry ) {
addBuffer( scene.__webglObjects, geometry, object );
} else if ( geometry instanceof THREE.Geometry ) {
for ( g in geometry.geometryGroups ) {
geometryGroup = geometry.geometryGroups[ g ];
addBuffer( scene.__webglObjects, geometryGroup, object );
}
}
} else if ( object instanceof THREE.Line ||
object instanceof THREE.ParticleSystem ) {
geometry = object.geometry;
addBuffer( scene.__webglObjects, geometry, object );
} else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
addBufferImmediate( scene.__webglObjectsImmediate, object );
} else if ( object instanceof THREE.Sprite ) {
scene.__webglSprites.push( object );
} else if ( object instanceof THREE.LensFlare ) {
scene.__webglFlares.push( object );
}
object.__webglActive = true;
}
};
function addBuffer( objlist, buffer, object ) {
objlist.push(
{
id: null,
buffer: buffer,
object: object,
opaque: null,
transparent: null,
z: 0
}
);
};
function addBufferImmediate( objlist, object ) {
objlist.push(
{
id: null,
object: object,
opaque: null,
transparent: null,
z: 0
}
);
};
// Objects updates
function updateObject( object ) {
var geometry = object.geometry,
geometryGroup, customAttributesDirty, material;
if ( geometry instanceof THREE.BufferGeometry ) {
setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
} else if ( object instanceof THREE.Mesh ) {
// check all geometry groups
for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
geometryGroup = geometry.geometryGroupsList[ i ];
material = getBufferMaterial( object, geometryGroup );
if ( geometry.buffersNeedUpdate ) {
initMeshBuffers( geometryGroup, object );
}
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
}
}
geometry.verticesNeedUpdate = false;
geometry.morphTargetsNeedUpdate = false;
geometry.elementsNeedUpdate = false;
geometry.uvsNeedUpdate = false;
geometry.normalsNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.tangentsNeedUpdate = false;
geometry.buffersNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
} else if ( object instanceof THREE.Line ) {
material = getBufferMaterial( object, geometry );
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.lineDistancesNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
} else if ( object instanceof THREE.ParticleSystem ) {
material = getBufferMaterial( object, geometry );
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
}
};
// Objects updates - custom attributes check
function areCustomAttributesDirty( material ) {
for ( var a in material.attributes ) {
if ( material.attributes[ a ].needsUpdate ) return true;
}
return false;
};
function clearCustomAttributes( material ) {
for ( var a in material.attributes ) {
material.attributes[ a ].needsUpdate = false;
}
};
// Objects removal
function removeObject( object, scene ) {
if ( object instanceof THREE.Mesh ||
object instanceof THREE.ParticleSystem ||
object instanceof THREE.Line ) {
removeInstances( scene.__webglObjects, object );
} else if ( object instanceof THREE.Sprite ) {
removeInstancesDirect( scene.__webglSprites, object );
} else if ( object instanceof THREE.LensFlare ) {
removeInstancesDirect( scene.__webglFlares, object );
} else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
removeInstances( scene.__webglObjectsImmediate, object );
}
delete object.__webglActive;
};
function removeInstances( objlist, object ) {
for ( var o = objlist.length - 1; o >= 0; o -- ) {
if ( objlist[ o ].object === object ) {
objlist.splice( o, 1 );
}
}
};
function removeInstancesDirect( objlist, object ) {
for ( var o = objlist.length - 1; o >= 0; o -- ) {
if ( objlist[ o ] === object ) {
objlist.splice( o, 1 );
}
}
};
// Materials
this.initMaterial = function ( material, lights, fog, object ) {
material.addEventListener( 'dispose', onMaterialDispose );
var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
if ( material instanceof THREE.MeshDepthMaterial ) {
shaderID = 'depth';
} else if ( material instanceof THREE.MeshNormalMaterial ) {
shaderID = 'normal';
} else if ( material instanceof THREE.MeshBasicMaterial ) {
shaderID = 'basic';
} else if ( material instanceof THREE.MeshLambertMaterial ) {
shaderID = 'lambert';
} else if ( material instanceof THREE.MeshPhongMaterial ) {
shaderID = 'phong';
} else if ( material instanceof THREE.LineBasicMaterial ) {
shaderID = 'basic';
} else if ( material instanceof THREE.LineDashedMaterial ) {
shaderID = 'dashed';
} else if ( material instanceof THREE.ParticleSystemMaterial ) {
shaderID = 'particle_basic';
}
if ( shaderID ) {
setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
}
// heuristics to create shader parameters according to lights in the scene
// (not to blow over maxLights budget)
maxLightCount = allocateLights( lights );
maxShadows = allocateShadows( lights );
maxBones = allocateBones( object );
parameters = {
map: !!material.map,
envMap: !!material.envMap,
lightMap: !!material.lightMap,
bumpMap: !!material.bumpMap,
normalMap: !!material.normalMap,
specularMap: !!material.specularMap,
vertexColors: material.vertexColors,
fog: fog,
useFog: material.fog,
fogExp: fog instanceof THREE.FogExp2,
sizeAttenuation: material.sizeAttenuation,
skinning: material.skinning,
maxBones: maxBones,
useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
morphTargets: material.morphTargets,
morphNormals: material.morphNormals,
maxMorphTargets: this.maxMorphTargets,
maxMorphNormals: this.maxMorphNormals,
maxDirLights: maxLightCount.directional,
maxPointLights: maxLightCount.point,
maxSpotLights: maxLightCount.spot,
maxHemiLights: maxLightCount.hemi,
maxShadows: maxShadows,
shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
shadowMapType: this.shadowMapType,
shadowMapDebug: this.shadowMapDebug,
shadowMapCascade: this.shadowMapCascade,
alphaTest: material.alphaTest,
metal: material.metal,
wrapAround: material.wrapAround,
doubleSided: material.side === THREE.DoubleSide,
flipSided: material.side === THREE.BackSide
};
material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
var attributes = material.program.attributes;
if ( material.morphTargets ) {
material.numSupportedMorphTargets = 0;
var id, base = "morphTarget";
for ( i = 0; i < this.maxMorphTargets; i ++ ) {
id = base + i;
if ( attributes[ id ] >= 0 ) {
material.numSupportedMorphTargets ++;
}
}
}
if ( material.morphNormals ) {
material.numSupportedMorphNormals = 0;
var id, base = "morphNormal";
for ( i = 0; i < this.maxMorphNormals; i ++ ) {
id = base + i;
if ( attributes[ id ] >= 0 ) {
material.numSupportedMorphNormals ++;
}
}
}
material.uniformsList = [];
for ( u in material.uniforms ) {
material.uniformsList.push( [ material.uniforms[ u ], u ] );
}
};
function setMaterialShaders( material, shaders ) {
material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
material.vertexShader = shaders.vertexShader;
material.fragmentShader = shaders.fragmentShader;
};
function setProgram( camera, lights, fog, material, object ) {
_usedTextureUnits = 0;
if ( material.needsUpdate ) {
if ( material.program ) deallocateMaterial( material );
_this.initMaterial( material, lights, fog, object );
material.needsUpdate = false;
}
if ( material.morphTargets ) {
if ( ! object.__webglMorphTargetInfluences ) {
object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
}
}
var refreshMaterial = false;
var program = material.program,
p_uniforms = program.uniforms,
m_uniforms = material.uniforms;
if ( program !== _currentProgram ) {
_gl.useProgram( program );
_currentProgram = program;
refreshMaterial = true;
}
if ( material.id !== _currentMaterialId ) {
_currentMaterialId = material.id;
refreshMaterial = true;
}
if ( refreshMaterial || camera !== _currentCamera ) {
_gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
if ( camera !== _currentCamera ) _currentCamera = camera;
}
// skinning uniforms must be set even if material didn't change
// auto-setting of texture unit for bone texture must go before other textures
// not sure why, but otherwise weird things happen
if ( material.skinning ) {
if ( _supportsBoneTextures && object.useVertexTexture ) {
if ( p_uniforms.boneTexture !== null ) {
var textureUnit = getTextureUnit();
_gl.uniform1i( p_uniforms.boneTexture, textureUnit );
_this.setTexture( object.boneTexture, textureUnit );
}
if ( p_uniforms.boneTextureWidth !== null ) {
_gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
}
if ( p_uniforms.boneTextureHeight !== null ) {
_gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
}
} else {
if ( p_uniforms.boneGlobalMatrices !== null ) {
_gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
}
}
}
if ( refreshMaterial ) {
// refresh uniforms common to several materials
if ( fog && material.fog ) {
refreshUniformsFog( m_uniforms, fog );
}
if ( material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material.lights ) {
if ( _lightsNeedUpdate ) {
setupLights( program, lights );
_lightsNeedUpdate = false;
}
refreshUniformsLights( m_uniforms, _lights );
}
if ( material instanceof THREE.MeshBasicMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.MeshPhongMaterial ) {
refreshUniformsCommon( m_uniforms, material );
}
// refresh single material specific uniforms
if ( material instanceof THREE.LineBasicMaterial ) {
refreshUniformsLine( m_uniforms, material );
} else if ( material instanceof THREE.LineDashedMaterial ) {
refreshUniformsLine( m_uniforms, material );
refreshUniformsDash( m_uniforms, material );
} else if ( material instanceof THREE.ParticleSystemMaterial ) {
refreshUniformsParticle( m_uniforms, material );
} else if ( material instanceof THREE.MeshPhongMaterial ) {
refreshUniformsPhong( m_uniforms, material );
} else if ( material instanceof THREE.MeshLambertMaterial ) {
refreshUniformsLambert( m_uniforms, material );
} else if ( material instanceof THREE.MeshDepthMaterial ) {
m_uniforms.mNear.value = camera.near;
m_uniforms.mFar.value = camera.far;
m_uniforms.opacity.value = material.opacity;
} else if ( material instanceof THREE.MeshNormalMaterial ) {
m_uniforms.opacity.value = material.opacity;
}
if ( object.receiveShadow && ! material._shadowPass ) {
refreshUniformsShadow( m_uniforms, lights );
}
// load common uniforms
loadUniformsGeneric( program, material.uniformsList );
// load material specific uniforms
// (shader material also gets them for the sake of genericity)
if ( material instanceof THREE.ShaderMaterial ||
material instanceof THREE.MeshPhongMaterial ||
material.envMap ) {
if ( p_uniforms.cameraPosition !== null ) {
_vector3.setFromMatrixPosition( camera.matrixWorld );
_gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
}
}
if ( material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.ShaderMaterial ||
material.skinning ) {
if ( p_uniforms.viewMatrix !== null ) {
_gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
}
}
}
loadUniformsMatrices( p_uniforms, object );
if ( p_uniforms.modelMatrix !== null ) {
_gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
}
return program;
};
// Uniforms (refresh uniforms objects)
function refreshUniformsCommon ( uniforms, material ) {
uniforms.opacity.value = material.opacity;
if ( _this.gammaInput ) {
uniforms.diffuse.value.copyGammaToLinear( material.color );
} else {
uniforms.diffuse.value = material.color;
}
uniforms.map.value = material.map;
uniforms.lightMap.value = material.lightMap;
uniforms.specularMap.value = material.specularMap;
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
}
// uv repeat and offset setting priorities
// 1. color map
// 2. specular map
// 3. normal map
// 4. bump map
var uvScaleMap;
if ( material.map ) {
uvScaleMap = material.map;
} else if ( material.specularMap ) {
uvScaleMap = material.specularMap;
} else if ( material.normalMap ) {
uvScaleMap = material.normalMap;
} else if ( material.bumpMap ) {
uvScaleMap = material.bumpMap;
}
if ( uvScaleMap !== undefined ) {
var offset = uvScaleMap.offset;
var repeat = uvScaleMap.repeat;
uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
}
uniforms.envMap.value = material.envMap;
uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
if ( _this.gammaInput ) {
//uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
uniforms.reflectivity.value = material.reflectivity;
} else {
uniforms.reflectivity.value = material.reflectivity;
}
uniforms.refractionRatio.value = material.refractionRatio;
uniforms.combine.value = material.combine;
uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
};
function refreshUniformsLine ( uniforms, material ) {
uniforms.diffuse.value = material.color;
uniforms.opacity.value = material.opacity;
};
function refreshUniformsDash ( uniforms, material ) {
uniforms.dashSize.value = material.dashSize;
uniforms.totalSize.value = material.dashSize + material.gapSize;
uniforms.scale.value = material.scale;
};
function refreshUniformsParticle ( uniforms, material ) {
uniforms.psColor.value = material.color;
uniforms.opacity.value = material.opacity;
uniforms.size.value = material.size;
uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
uniforms.map.value = material.map;
};
function refreshUniformsFog ( uniforms, fog ) {
uniforms.fogColor.value = fog.color;
if ( fog instanceof THREE.Fog ) {
uniforms.fogNear.value = fog.near;
uniforms.fogFar.value = fog.far;
} else if ( fog instanceof THREE.FogExp2 ) {
uniforms.fogDensity.value = fog.density;
}
};
function refreshUniformsPhong ( uniforms, material ) {
uniforms.shininess.value = material.shininess;
if ( _this.gammaInput ) {
uniforms.ambient.value.copyGammaToLinear( material.ambient );
uniforms.emissive.value.copyGammaToLinear( material.emissive );
uniforms.specular.value.copyGammaToLinear( material.specular );
} else {
uniforms.ambient.value = material.ambient;
uniforms.emissive.value = material.emissive;
uniforms.specular.value = material.specular;
}
if ( material.wrapAround ) {
uniforms.wrapRGB.value.copy( material.wrapRGB );
}
};
function refreshUniformsLambert ( uniforms, material ) {
if ( _this.gammaInput ) {
uniforms.ambient.value.copyGammaToLinear( material.ambient );
uniforms.emissive.value.copyGammaToLinear( material.emissive );
} else {
uniforms.ambient.value = material.ambient;
uniforms.emissive.value = material.emissive;
}
if ( material.wrapAround ) {
uniforms.wrapRGB.value.copy( material.wrapRGB );
}
};
function refreshUniformsLights ( uniforms, lights ) {
uniforms.ambientLightColor.value = lights.ambient;
uniforms.directionalLightColor.value = lights.directional.colors;
uniforms.directionalLightDirection.value = lights.directional.positions;
uniforms.pointLightColor.value = lights.point.colors;
uniforms.pointLightPosition.value = lights.point.positions;
uniforms.pointLightDistance.value = lights.point.distances;
uniforms.spotLightColor.value = lights.spot.colors;
uniforms.spotLightPosition.value = lights.spot.positions;
uniforms.spotLightDistance.value = lights.spot.distances;
uniforms.spotLightDirection.value = lights.spot.directions;
uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
uniforms.spotLightExponent.value = lights.spot.exponents;
uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
uniforms.hemisphereLightDirection.value = lights.hemi.positions;
};
function refreshUniformsShadow ( uniforms, lights ) {
if ( uniforms.shadowMatrix ) {
var j = 0;
for ( var i = 0, il = lights.length; i < il; i ++ ) {
var light = lights[ i ];
if ( ! light.castShadow ) continue;
if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
uniforms.shadowMap.value[ j ] = light.shadowMap;
uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
uniforms.shadowBias.value[ j ] = light.shadowBias;
j ++;
}
}
}
};
// Uniforms (load to GPU)
function loadUniformsMatrices ( uniforms, object ) {
_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
if ( uniforms.normalMatrix ) {
_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
}
};
function getTextureUnit() {
var textureUnit = _usedTextureUnits;
if ( textureUnit >= _maxTextures ) {
console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
}
_usedTextureUnits += 1;
return textureUnit;
};
function loadUniformsGeneric ( program, uniforms ) {
var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
location = program.uniforms[ uniforms[ j ][ 1 ] ];
if ( !location ) continue;
uniform = uniforms[ j ][ 0 ];
type = uniform.type;
value = uniform.value;
if ( type === "i" ) { // single integer
_gl.uniform1i( location, value );
} else if ( type === "f" ) { // single float
_gl.uniform1f( location, value );
} else if ( type === "v2" ) { // single THREE.Vector2
_gl.uniform2f( location, value.x, value.y );
} else if ( type === "v3" ) { // single THREE.Vector3
_gl.uniform3f( location, value.x, value.y, value.z );
} else if ( type === "v4" ) { // single THREE.Vector4
_gl.uniform4f( location, value.x, value.y, value.z, value.w );
} else if ( type === "c" ) { // single THREE.Color
_gl.uniform3f( location, value.r, value.g, value.b );
} else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
_gl.uniform1iv( location, value );
} else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
_gl.uniform3iv( location, value );
} else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
_gl.uniform1fv( location, value );
} else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
_gl.uniform3fv( location, value );
} else if ( type === "v2v" ) { // array of THREE.Vector2
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 2 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 2;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
}
_gl.uniform2fv( location, uniform._array );
} else if ( type === "v3v" ) { // array of THREE.Vector3
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 3 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 3;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
uniform._array[ offset + 2 ] = value[ i ].z;
}
_gl.uniform3fv( location, uniform._array );
} else if ( type === "v4v" ) { // array of THREE.Vector4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 4 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 4;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
uniform._array[ offset + 2 ] = value[ i ].z;
uniform._array[ offset + 3 ] = value[ i ].w;
}
_gl.uniform4fv( location, uniform._array );
} else if ( type === "m4") { // single THREE.Matrix4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 16 );
}
value.flattenToArray( uniform._array );
_gl.uniformMatrix4fv( location, false, uniform._array );
} else if ( type === "m4v" ) { // array of THREE.Matrix4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 16 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
}
_gl.uniformMatrix4fv( location, false, uniform._array );
} else if ( type === "t" ) { // single THREE.Texture (2d or cube)
texture = value;
textureUnit = getTextureUnit();
_gl.uniform1i( location, textureUnit );
if ( !texture ) continue;
if ( texture.image instanceof Array && texture.image.length === 6 ) {
setCubeTexture( texture, textureUnit );
} else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
setCubeTextureDynamic( texture, textureUnit );
} else {
_this.setTexture( texture, textureUnit );
}
} else if ( type === "tv" ) { // array of THREE.Texture (2d)
if ( uniform._array === undefined ) {
uniform._array = [];
}
for( i = 0, il = uniform.value.length; i < il; i ++ ) {
uniform._array[ i ] = getTextureUnit();
}
_gl.uniform1iv( location, uniform._array );
for( i = 0, il = uniform.value.length; i < il; i ++ ) {
texture = uniform.value[ i ];
textureUnit = uniform._array[ i ];
if ( !texture ) continue;
_this.setTexture( texture, textureUnit );
}
} else {
console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
}
}
};
function setupMatrices ( object, camera ) {
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
};
//
function setColorGamma( array, offset, color, intensitySq ) {
array[ offset ] = color.r * color.r * intensitySq;
array[ offset + 1 ] = color.g * color.g * intensitySq;
array[ offset + 2 ] = color.b * color.b * intensitySq;
};
function setColorLinear( array, offset, color, intensity ) {
array[ offset ] = color.r * intensity;
array[ offset + 1 ] = color.g * intensity;
array[ offset + 2 ] = color.b * intensity;
};
function setupLights ( program, lights ) {
var l, ll, light, n,
r = 0, g = 0, b = 0,
color, skyColor, groundColor,
intensity, intensitySq,
position,
distance,
zlights = _lights,
dirColors = zlights.directional.colors,
dirPositions = zlights.directional.positions,
pointColors = zlights.point.colors,
pointPositions = zlights.point.positions,
pointDistances = zlights.point.distances,
spotColors = zlights.spot.colors,
spotPositions = zlights.spot.positions,
spotDistances = zlights.spot.distances,
spotDirections = zlights.spot.directions,
spotAnglesCos = zlights.spot.anglesCos,
spotExponents = zlights.spot.exponents,
hemiSkyColors = zlights.hemi.skyColors,
hemiGroundColors = zlights.hemi.groundColors,
hemiPositions = zlights.hemi.positions,
dirLength = 0,
pointLength = 0,
spotLength = 0,
hemiLength = 0,
dirCount = 0,
pointCount = 0,
spotCount = 0,
hemiCount = 0,
dirOffset = 0,
pointOffset = 0,
spotOffset = 0,
hemiOffset = 0;
for ( l = 0, ll = lights.length; l < ll; l ++ ) {
light = lights[ l ];
if ( light.onlyShadow ) continue;
color = light.color;
intensity = light.intensity;
distance = light.distance;
if ( light instanceof THREE.AmbientLight ) {
if ( ! light.visible ) continue;
if ( _this.gammaInput ) {
r += color.r * color.r;
g += color.g * color.g;
b += color.b * color.b;
} else {
r += color.r;
g += color.g;
b += color.b;
}
} else if ( light instanceof THREE.DirectionalLight ) {
dirCount += 1;
if ( ! light.visible ) continue;
_direction.setFromMatrixPosition( light.matrixWorld );
_vector3.setFromMatrixPosition( light.target.matrixWorld );
_direction.sub( _vector3 );
_direction.normalize();
// skip lights with undefined direction
// these create troubles in OpenGL (making pixel black)
if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
dirOffset = dirLength * 3;
dirPositions[ dirOffset ] = _direction.x;
dirPositions[ dirOffset + 1 ] = _direction.y;
dirPositions[ dirOffset + 2 ] = _direction.z;
if ( _this.gammaInput ) {
setColorGamma( dirColors, dirOffset, color, intensity * intensity );
} else {
setColorLinear( dirColors, dirOffset, color, intensity );
}
dirLength += 1;
} else if ( light instanceof THREE.PointLight ) {
pointCount += 1;
if ( ! light.visible ) continue;
pointOffset = pointLength * 3;
if ( _this.gammaInput ) {
setColorGamma( pointColors, pointOffset, color, intensity * intensity );
} else {
setColorLinear( pointColors, pointOffset, color, intensity );
}
_vector3.setFromMatrixPosition( light.matrixWorld );
pointPositions[ pointOffset ] = _vector3.x;
pointPositions[ pointOffset + 1 ] = _vector3.y;
pointPositions[ pointOffset + 2 ] = _vector3.z;
pointDistances[ pointLength ] = distance;
pointLength += 1;
} else if ( light instanceof THREE.SpotLight ) {
spotCount += 1;
if ( ! light.visible ) continue;
spotOffset = spotLength * 3;
if ( _this.gammaInput ) {
setColorGamma( spotColors, spotOffset, color, intensity * intensity );
} else {
setColorLinear( spotColors, spotOffset, color, intensity );
}
_vector3.setFromMatrixPosition( light.matrixWorld );
spotPositions[ spotOffset ] = _vector3.x;
spotPositions[ spotOffset + 1 ] = _vector3.y;
spotPositions[ spotOffset + 2 ] = _vector3.z;
spotDistances[ spotLength ] = distance;
_direction.copy( _vector3 );
_vector3.setFromMatrixPosition( light.target.matrixWorld );
_direction.sub( _vector3 );
_direction.normalize();
spotDirections[ spotOffset ] = _direction.x;
spotDirections[ spotOffset + 1 ] = _direction.y;
spotDirections[ spotOffset + 2 ] = _direction.z;
spotAnglesCos[ spotLength ] = Math.cos( light.angle );
spotExponents[ spotLength ] = light.exponent;
spotLength += 1;
} else if ( light instanceof THREE.HemisphereLight ) {
hemiCount += 1;
if ( ! light.visible ) continue;
_direction.setFromMatrixPosition( light.matrixWorld );
_direction.normalize();
// skip lights with undefined direction
// these create troubles in OpenGL (making pixel black)
if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
hemiOffset = hemiLength * 3;
hemiPositions[ hemiOffset ] = _direction.x;
hemiPositions[ hemiOffset + 1 ] = _direction.y;
hemiPositions[ hemiOffset + 2 ] = _direction.z;
skyColor = light.color;
groundColor = light.groundColor;
if ( _this.gammaInput ) {
intensitySq = intensity * intensity;
setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
} else {
setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
}
hemiLength += 1;
}
}
// null eventual remains from removed lights
// (this is to avoid if in shader)
for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
zlights.directional.length = dirLength;
zlights.point.length = pointLength;
zlights.spot.length = spotLength;
zlights.hemi.length = hemiLength;
zlights.ambient[ 0 ] = r;
zlights.ambient[ 1 ] = g;
zlights.ambient[ 2 ] = b;
};
// GL state setting
this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
if ( cullFace === THREE.CullFaceNone ) {
_gl.disable( _gl.CULL_FACE );
} else {
if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
_gl.frontFace( _gl.CW );
} else {
_gl.frontFace( _gl.CCW );
}
if ( cullFace === THREE.CullFaceBack ) {
_gl.cullFace( _gl.BACK );
} else if ( cullFace === THREE.CullFaceFront ) {
_gl.cullFace( _gl.FRONT );
} else {
_gl.cullFace( _gl.FRONT_AND_BACK );
}
_gl.enable( _gl.CULL_FACE );
}
};
this.setMaterialFaces = function ( material ) {
var doubleSided = material.side === THREE.DoubleSide;
var flipSided = material.side === THREE.BackSide;
if ( _oldDoubleSided !== doubleSided ) {
if ( doubleSided ) {
_gl.disable( _gl.CULL_FACE );
} else {
_gl.enable( _gl.CULL_FACE );
}
_oldDoubleSided = doubleSided;
}
if ( _oldFlipSided !== flipSided ) {
if ( flipSided ) {
_gl.frontFace( _gl.CW );
} else {
_gl.frontFace( _gl.CCW );
}
_oldFlipSided = flipSided;
}
};
this.setDepthTest = function ( depthTest ) {
if ( _oldDepthTest !== depthTest ) {
if ( depthTest ) {
_gl.enable( _gl.DEPTH_TEST );
} else {
_gl.disable( _gl.DEPTH_TEST );
}
_oldDepthTest = depthTest;
}
};
this.setDepthWrite = function ( depthWrite ) {
if ( _oldDepthWrite !== depthWrite ) {
_gl.depthMask( depthWrite );
_oldDepthWrite = depthWrite;
}
};
function setLineWidth ( width ) {
if ( width !== _oldLineWidth ) {
_gl.lineWidth( width );
_oldLineWidth = width;
}
};
function setPolygonOffset ( polygonoffset, factor, units ) {
if ( _oldPolygonOffset !== polygonoffset ) {
if ( polygonoffset ) {
_gl.enable( _gl.POLYGON_OFFSET_FILL );
} else {
_gl.disable( _gl.POLYGON_OFFSET_FILL );
}
_oldPolygonOffset = polygonoffset;
}
if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
_gl.polygonOffset( factor, units );
_oldPolygonOffsetFactor = factor;
_oldPolygonOffsetUnits = units;
}
};
this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
if ( blending !== _oldBlending ) {
if ( blending === THREE.NoBlending ) {
_gl.disable( _gl.BLEND );
} else if ( blending === THREE.AdditiveBlending ) {
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
} else if ( blending === THREE.SubtractiveBlending ) {
// TODO: Find blendFuncSeparate() combination
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
} else if ( blending === THREE.MultiplyBlending ) {
// TODO: Find blendFuncSeparate() combination
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
} else if ( blending === THREE.CustomBlending ) {
_gl.enable( _gl.BLEND );
} else {
_gl.enable( _gl.BLEND );
_gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
_gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
}
_oldBlending = blending;
}
if ( blending === THREE.CustomBlending ) {
if ( blendEquation !== _oldBlendEquation ) {
_gl.blendEquation( paramThreeToGL( blendEquation ) );
_oldBlendEquation = blendEquation;
}
if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
_gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
_oldBlendSrc = blendSrc;
_oldBlendDst = blendDst;
}
} else {
_oldBlendEquation = null;
_oldBlendSrc = null;
_oldBlendDst = null;
}
};
// Defines
function generateDefines ( defines ) {
var value, chunk, chunks = [];
for ( var d in defines ) {
value = defines[ d ];
if ( value === false ) continue;
chunk = "#define " + d + " " + value;
chunks.push( chunk );
}
return chunks.join( "\n" );
};
// Shaders
function buildProgram( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
var p, pl, d, program, code;
var chunks = [];
// Generate code
if ( shaderID ) {
chunks.push( shaderID );
} else {
chunks.push( fragmentShader );
chunks.push( vertexShader );
}
for ( d in defines ) {
chunks.push( d );
chunks.push( defines[ d ] );
}
for ( p in parameters ) {
chunks.push( p );
chunks.push( parameters[ p ] );
}
code = chunks.join();
// Check if code has been already compiled
for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
var programInfo = _programs[ p ];
if ( programInfo.code === code ) {
// console.log( "Code already compiled." /*: \n\n" + code*/ );
programInfo.usedTimes ++;
return programInfo.program;
}
}
var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
} else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
}
// console.log( "building new program " );
//
var customDefines = generateDefines( defines );
//
program = _gl.createProgram();
var prefix_vertex = [
"precision " + _precision + " float;",
"precision " + _precision + " int;",
customDefines,
_supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
_this.gammaInput ? "#define GAMMA_INPUT" : "",
_this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
"#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
"#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
"#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
"#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
"#define MAX_SHADOWS " + parameters.maxShadows,
"#define MAX_BONES " + parameters.maxBones,
parameters.map ? "#define USE_MAP" : "",
parameters.envMap ? "#define USE_ENVMAP" : "",
parameters.lightMap ? "#define USE_LIGHTMAP" : "",
parameters.bumpMap ? "#define USE_BUMPMAP" : "",
parameters.normalMap ? "#define USE_NORMALMAP" : "",
parameters.specularMap ? "#define USE_SPECULARMAP" : "",
parameters.vertexColors ? "#define USE_COLOR" : "",
parameters.skinning ? "#define USE_SKINNING" : "",
parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
parameters.wrapAround ? "#define WRAP_AROUND" : "",
parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
parameters.flipSided ? "#define FLIP_SIDED" : "",
parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
"uniform mat4 modelMatrix;",
"uniform mat4 modelViewMatrix;",
"uniform mat4 projectionMatrix;",
"uniform mat4 viewMatrix;",
"uniform mat3 normalMatrix;",
"uniform vec3 cameraPosition;",
"attribute vec3 position;",
"attribute vec3 normal;",
"attribute vec2 uv;",
"attribute vec2 uv2;",
"#ifdef USE_COLOR",
"attribute vec3 color;",
"#endif",
"#ifdef USE_MORPHTARGETS",
"attribute vec3 morphTarget0;",
"attribute vec3 morphTarget1;",
"attribute vec3 morphTarget2;",
"attribute vec3 morphTarget3;",
"#ifdef USE_MORPHNORMALS",
"attribute vec3 morphNormal0;",
"attribute vec3 morphNormal1;",
"attribute vec3 morphNormal2;",
"attribute vec3 morphNormal3;",
"#else",
"attribute vec3 morphTarget4;",
"attribute vec3 morphTarget5;",
"attribute vec3 morphTarget6;",
"attribute vec3 morphTarget7;",
"#endif",
"#endif",
"#ifdef USE_SKINNING",
"attribute vec4 skinIndex;",
"attribute vec4 skinWeight;",
"#endif",
""
].join("\n");
var prefix_fragment = [
"precision " + _precision + " float;",
"precision " + _precision + " int;",
( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
customDefines,
"#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
"#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
"#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
"#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
"#define MAX_SHADOWS " + parameters.maxShadows,
parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
_this.gammaInput ? "#define GAMMA_INPUT" : "",
_this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
parameters.map ? "#define USE_MAP" : "",
parameters.envMap ? "#define USE_ENVMAP" : "",
parameters.lightMap ? "#define USE_LIGHTMAP" : "",
parameters.bumpMap ? "#define USE_BUMPMAP" : "",
parameters.normalMap ? "#define USE_NORMALMAP" : "",
parameters.specularMap ? "#define USE_SPECULARMAP" : "",
parameters.vertexColors ? "#define USE_COLOR" : "",
parameters.metal ? "#define METAL" : "",
parameters.wrapAround ? "#define WRAP_AROUND" : "",
parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
parameters.flipSided ? "#define FLIP_SIDED" : "",
parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
"uniform mat4 viewMatrix;",
"uniform vec3 cameraPosition;",
""
].join("\n");
var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
_gl.attachShader( program, glVertexShader );
_gl.attachShader( program, glFragmentShader );
// Force a particular attribute to index 0.
// because potentially expensive emulation is done by browser if attribute 0 is disabled.
// And, color, for example is often automatically bound to index 0 so disabling it
if ( index0AttributeName !== undefined ) {
_gl.bindAttribLocation( program, 0, index0AttributeName );
}
_gl.linkProgram( program );
if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
console.error( 'Could not initialise shader' );
console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
console.error( 'gl.getError()', _gl.getError() );
}
if ( _gl.getProgramInfoLog( program ) !== '' ) {
console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
}
// clean up
_gl.deleteShader( glFragmentShader );
_gl.deleteShader( glVertexShader );
// console.log( prefix_fragment + fragmentShader );
// console.log( prefix_vertex + vertexShader );
program.uniforms = {};
program.attributes = {};
var identifiers, u, a, i;
// cache uniform locations
identifiers = [
'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
'morphTargetInfluences'
];
if ( parameters.useVertexTexture ) {
identifiers.push( 'boneTexture' );
identifiers.push( 'boneTextureWidth' );
identifiers.push( 'boneTextureHeight' );
} else {
identifiers.push( 'boneGlobalMatrices' );
}
for ( u in uniforms ) {
identifiers.push( u );
}
cacheUniformLocations( program, identifiers );
// cache attributes locations
identifiers = [
"position", "normal", "uv", "uv2", "tangent", "color",
"skinIndex", "skinWeight", "lineDistance"
];
for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
identifiers.push( "morphTarget" + i );
}
for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
identifiers.push( "morphNormal" + i );
}
for ( a in attributes ) {
identifiers.push( a );
}
cacheAttributeLocations( program, identifiers );
program.id = _programs_counter ++;
_programs.push( { program: program, code: code, usedTimes: 1 } );
_this.info.memory.programs = _programs.length;
return program;
};
// Shader parameters cache
function cacheUniformLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.uniforms[ id ] = _gl.getUniformLocation( program, id );
}
};
function cacheAttributeLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.attributes[ id ] = _gl.getAttribLocation( program, id );
}
};
function addLineNumbers ( string ) {
var chunks = string.split( "\n" );
for ( var i = 0, il = chunks.length; i < il; i ++ ) {
// Chrome reports shader errors on lines
// starting counting from 1
chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
}
return chunks.join( "\n" );
};
function getShader ( type, string ) {
var shader;
if ( type === "fragment" ) {
shader = _gl.createShader( _gl.FRAGMENT_SHADER );
} else if ( type === "vertex" ) {
shader = _gl.createShader( _gl.VERTEX_SHADER );
}
_gl.shaderSource( shader, string );
_gl.compileShader( shader );
if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
console.error( _gl.getShaderInfoLog( shader ) );
console.error( addLineNumbers( string ) );
return null;
}
return shader;
};
// Textures
function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
if ( isImagePowerOfTwo ) {
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
} else {
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
}
if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
_gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
texture.__oldAnisotropy = texture.anisotropy;
}
}
};
this.setTexture = function ( texture, slot ) {
if ( texture.needsUpdate ) {
if ( ! texture.__webglInit ) {
texture.__webglInit = true;
texture.addEventListener( 'dispose', onTextureDispose );
texture.__webglTexture = _gl.createTexture();
_this.info.memory.textures ++;
}
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
var image = texture.image,
isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
glFormat = paramThreeToGL( texture.format ),
glType = paramThreeToGL( texture.type );
setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
var mipmap, mipmaps = texture.mipmaps;
if ( texture instanceof THREE.DataTexture ) {
// use manually created mipmaps if available
// if there are no manual mipmaps
// set 0 level mipmap and then use GL to generate other mipmap levels
if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
_gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
texture.generateMipmaps = false;
} else {
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
}
} else if ( texture instanceof THREE.CompressedTexture ) {
for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
if ( texture.format!==THREE.RGBAFormat ) {
_gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
} else {
_gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
}
} else { // regular Texture (image, video, canvas)
// use manually created mipmaps if available
// if there are no manual mipmaps
// set 0 level mipmap and then use GL to generate other mipmap levels
if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
_gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
}
texture.generateMipmaps = false;
} else {
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
}
}
if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
texture.needsUpdate = false;
if ( texture.onUpdate ) texture.onUpdate();
} else {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
}
};
function clampToMaxSize ( image, maxSize ) {
if ( image.width <= maxSize && image.height <= maxSize ) {
return image;
}
// Warning: Scaling through the canvas will only work with images that use
// premultiplied alpha.
var maxDimension = Math.max( image.width, image.height );
var newWidth = Math.floor( image.width * maxSize / maxDimension );
var newHeight = Math.floor( image.height * maxSize / maxDimension );
var canvas = document.createElement( 'canvas' );
canvas.width = newWidth;
canvas.height = newHeight;
var ctx = canvas.getContext( "2d" );
ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
return canvas;
}
function setCubeTexture ( texture, slot ) {
if ( texture.image.length === 6 ) {
if ( texture.needsUpdate ) {
if ( ! texture.image.__webglTextureCube ) {
texture.addEventListener( 'dispose', onTextureDispose );
texture.image.__webglTextureCube = _gl.createTexture();
_this.info.memory.textures ++;
}
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
var isCompressed = texture instanceof THREE.CompressedTexture;
var cubeImage = [];
for ( var i = 0; i < 6; i ++ ) {
if ( _this.autoScaleCubemaps && ! isCompressed ) {
cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
} else {
cubeImage[ i ] = texture.image[ i ];
}
}
var image = cubeImage[ 0 ],
isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
glFormat = paramThreeToGL( texture.format ),
glType = paramThreeToGL( texture.type );
setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
for ( var i = 0; i < 6; i ++ ) {
if( !isCompressed ) {
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
} else {
var mipmap, mipmaps = cubeImage[ i ].mipmaps;
for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
mipmap = mipmaps[ j ];
if ( texture.format!==THREE.RGBAFormat ) {
_gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
} else {
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
}
}
}
if ( texture.generateMipmaps && isImagePowerOfTwo ) {
_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
}
texture.needsUpdate = false;
if ( texture.onUpdate ) texture.onUpdate();
} else {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
}
}
};
function setCubeTextureDynamic ( texture, slot ) {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
};
// Render targets
function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
};
function setupRenderBuffer ( renderbuffer, renderTarget ) {
_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
/* For some reason this is not working. Defaulting to RGBA4.
} else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
*/
} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
} else {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
}
};
this.setRenderTarget = function ( renderTarget ) {
var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
renderTarget.__webglTexture = _gl.createTexture();
_this.info.memory.textures ++;
// Setup texture, create render and frame buffers
var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
glFormat = paramThreeToGL( renderTarget.format ),
glType = paramThreeToGL( renderTarget.type );
if ( isCube ) {
renderTarget.__webglFramebuffer = [];
renderTarget.__webglRenderbuffer = [];
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
for ( var i = 0; i < 6; i ++ ) {
renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
}
if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
} else {
renderTarget.__webglFramebuffer = _gl.createFramebuffer();
if ( renderTarget.shareDepthFrom ) {
renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
} else {
renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
}
_gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
if ( renderTarget.shareDepthFrom ) {
if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
}
} else {
setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
}
if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
}
// Release everything
if ( isCube ) {
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
} else {
_gl.bindTexture( _gl.TEXTURE_2D, null );
}
_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
}
var framebuffer, width, height, vx, vy;
if ( renderTarget ) {
if ( isCube ) {
framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
} else {
framebuffer = renderTarget.__webglFramebuffer;
}
width = renderTarget.width;
height = renderTarget.height;
vx = 0;
vy = 0;
} else {
framebuffer = null;
width = _viewportWidth;
height = _viewportHeight;
vx = _viewportX;
vy = _viewportY;
}
if ( framebuffer !== _currentFramebuffer ) {
_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
_gl.viewport( vx, vy, width, height );
_currentFramebuffer = framebuffer;
}
_currentWidth = width;
_currentHeight = height;
};
function updateRenderTargetMipmap ( renderTarget ) {
if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
} else {
_gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
_gl.generateMipmap( _gl.TEXTURE_2D );
_gl.bindTexture( _gl.TEXTURE_2D, null );
}
};
// Fallback filters for non-power-of-2 textures
function filterFallback ( f ) {
if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
return _gl.NEAREST;
}
return _gl.LINEAR;
};
// Map three.js constants to WebGL constants
function paramThreeToGL ( p ) {
if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
if ( p === THREE.NearestFilter ) return _gl.NEAREST;
if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
if ( p === THREE.LinearFilter ) return _gl.LINEAR;
if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
if ( p === THREE.ByteType ) return _gl.BYTE;
if ( p === THREE.ShortType ) return _gl.SHORT;
if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
if ( p === THREE.IntType ) return _gl.INT;
if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
if ( p === THREE.FloatType ) return _gl.FLOAT;
if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
if ( p === THREE.RGBFormat ) return _gl.RGB;
if ( p === THREE.RGBAFormat ) return _gl.RGBA;
if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
if ( p === THREE.ZeroFactor ) return _gl.ZERO;
if ( p === THREE.OneFactor ) return _gl.ONE;
if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
if ( _glExtensionCompressedTextureS3TC !== undefined ) {
if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
}
return 0;
};
// Allocations
function allocateBones ( object ) {
if ( _supportsBoneTextures && object && object.useVertexTexture ) {
return 1024;
} else {
// default for when object is not specified
// ( for example when prebuilding shader
// to be used with multiple objects )
//
// - leave some extra space for other uniforms
// - limit here is ANGLE's 254 max uniform vectors
// (up to 54 should be safe)
var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
var maxBones = nVertexMatrices;
if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
maxBones = Math.min( object.bones.length, maxBones );
if ( maxBones < object.bones.length ) {
console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
}
}
return maxBones;
}
};
function allocateLights( lights ) {
var dirLights = 0;
var pointLights = 0;
var spotLights = 0;
var hemiLights = 0;
for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
var light = lights[ l ];
if ( light.onlyShadow || light.visible === false ) continue;
if ( light instanceof THREE.DirectionalLight ) dirLights ++;
if ( light instanceof THREE.PointLight ) pointLights ++;
if ( light instanceof THREE.SpotLight ) spotLights ++;
if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
}
return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
};
function allocateShadows( lights ) {
var maxShadows = 0;
for ( var l = 0, ll = lights.length; l < ll; l++ ) {
var light = lights[ l ];
if ( ! light.castShadow ) continue;
if ( light instanceof THREE.SpotLight ) maxShadows ++;
if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
}
return maxShadows;
};
// Initialization
function initGL() {
try {
var attributes = {
alpha: _alpha,
premultipliedAlpha: _premultipliedAlpha,
antialias: _antialias,
stencil: _stencil,
preserveDrawingBuffer: _preserveDrawingBuffer
};
_gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
if ( _gl === null ) {
throw 'Error creating WebGL context.';
}
} catch ( error ) {
console.error( error );
}
_glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
_glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
_glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
_glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
_glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
if ( ! _glExtensionTextureFloat ) {
console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
}
if ( ! _glExtensionStandardDerivatives ) {
console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
}
if ( ! _glExtensionTextureFilterAnisotropic ) {
console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
}
if ( ! _glExtensionCompressedTextureS3TC ) {
console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
}
if ( _gl.getShaderPrecisionFormat === undefined ) {
_gl.getShaderPrecisionFormat = function() {
return {
"rangeMin" : 1,
"rangeMax" : 1,
"precision" : 1
};
}
}
};
function setDefaultGLState () {
_gl.clearColor( 0, 0, 0, 1 );
_gl.clearDepth( 1 );
_gl.clearStencil( 0 );
_gl.enable( _gl.DEPTH_TEST );
_gl.depthFunc( _gl.LEQUAL );
_gl.frontFace( _gl.CCW );
_gl.cullFace( _gl.BACK );
_gl.enable( _gl.CULL_FACE );
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
_gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
};
// default plugins (order is important)
this.shadowMapPlugin = new THREE.ShadowMapPlugin();
this.addPrePlugin( this.shadowMapPlugin );
this.addPostPlugin( new THREE.SpritePlugin() );
this.addPostPlugin( new THREE.LensFlarePlugin() );
};
/**
* @author szimek / https://github.com/szimek/
* @author alteredq / http://alteredqualia.com/
*/
THREE.WebGLRenderTarget = function ( width, height, options ) {
this.width = width;
this.height = height;
options = options || {};
this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
this.offset = new THREE.Vector2( 0, 0 );
this.repeat = new THREE.Vector2( 1, 1 );
this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
this.generateMipmaps = true;
this.shareDepthFrom = null;
};
THREE.WebGLRenderTarget.prototype = {
constructor: THREE.WebGLRenderTarget,
clone: function () {
var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
tmp.wrapS = this.wrapS;
tmp.wrapT = this.wrapT;
tmp.magFilter = this.magFilter;
tmp.minFilter = this.minFilter;
tmp.anisotropy = this.anisotropy;
tmp.offset.copy( this.offset );
tmp.repeat.copy( this.repeat );
tmp.format = this.format;
tmp.type = this.type;
tmp.depthBuffer = this.depthBuffer;
tmp.stencilBuffer = this.stencilBuffer;
tmp.generateMipmaps = this.generateMipmaps;
tmp.shareDepthFrom = this.shareDepthFrom;
return tmp;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
};
THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
/**
* @author alteredq / http://alteredqualia.com
*/
THREE.WebGLRenderTargetCube = function ( width, height, options ) {
THREE.WebGLRenderTarget.call( this, width, height, options );
this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
};
THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableVertex = function () {
this.position = new THREE.Vector3();
this.positionWorld = new THREE.Vector3();
this.positionScreen = new THREE.Vector4();
this.visible = true;
};
THREE.RenderableVertex.prototype.copy = function ( vertex ) {
this.positionWorld.copy( vertex.positionWorld );
this.positionScreen.copy( vertex.positionScreen );
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableFace = function () {
this.id = 0;
this.v1 = new THREE.RenderableVertex();
this.v2 = new THREE.RenderableVertex();
this.v3 = new THREE.RenderableVertex();
this.centroidModel = new THREE.Vector3();
this.normalModel = new THREE.Vector3();
this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
this.vertexNormalsLength = 0;
this.color = null;
this.material = null;
this.uvs = [[]];
this.z = 0;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableObject = function () {
this.id = 0;
this.object = null;
this.z = 0;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableSprite = function () {
this.id = 0;
this.object = null;
this.x = 0;
this.y = 0;
this.z = 0;
this.rotation = 0;
this.scale = new THREE.Vector2();
this.material = null;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.RenderableLine = function () {
this.id = 0;
this.v1 = new THREE.RenderableVertex();
this.v2 = new THREE.RenderableVertex();
this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
this.material = null;
this.z = 0;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.GeometryUtils = {
// Merge two geometries or geometry and geometry from object (using object's transform)
merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
var matrix, normalMatrix,
vertexOffset = geometry1.vertices.length,
uvPosition = geometry1.faceVertexUvs[ 0 ].length,
geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
vertices1 = geometry1.vertices,
vertices2 = geometry2.vertices,
faces1 = geometry1.faces,
faces2 = geometry2.faces,
uvs1 = geometry1.faceVertexUvs[ 0 ],
uvs2 = geometry2.faceVertexUvs[ 0 ];
if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
if ( object2 instanceof THREE.Mesh ) {
object2.matrixAutoUpdate && object2.updateMatrix();
matrix = object2.matrix;
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 ) 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 ) {
faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
}
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
normal = faceVertexNormals[ j ].clone();
if ( normalMatrix ) {
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;
faceCopy.centroid.copy( face.centroid );
if ( matrix ) {
faceCopy.centroid.applyMatrix4( matrix );
}
faces1.push( faceCopy );
}
// uvs
for ( i = 0, il = uvs2.length; i < il; i ++ ) {
var uv = uvs2[ i ], uvCopy = [];
for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
}
uvs1.push( uvCopy );
}
},
// Get random point in triangle (via barycentric coordinates)
// (uniform distribution)
// http://www.cgafaq.info/wiki/Random_Point_In_Triangle
randomPointInTriangle: function () {
var vector = new THREE.Vector3();
return function ( vectorA, vectorB, vectorC ) {
var point = new THREE.Vector3();
var a = THREE.Math.random16();
var b = THREE.Math.random16();
if ( ( a + b ) > 1 ) {
a = 1 - a;
b = 1 - b;
}
var c = 1 - a - b;
point.copy( vectorA );
point.multiplyScalar( a );
vector.copy( vectorB );
vector.multiplyScalar( b );
point.add( vector );
vector.copy( vectorC );
vector.multiplyScalar( c );
point.add( vector );
return point;
};
}(),
// Get random point in face (triangle / quad)
// (uniform distribution)
randomPointInFace: function ( face, geometry, useCachedAreas ) {
var vA, vB, vC, vD;
vA = geometry.vertices[ face.a ];
vB = geometry.vertices[ face.b ];
vC = geometry.vertices[ face.c ];
return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
},
// Get uniformly distributed random points in mesh
// - create array with cumulative sums of face areas
// - pick random number from 0 to total area
// - find corresponding place in area array by binary search
// - get random point in face
randomPointsInGeometry: function ( geometry, n ) {
var face, i,
faces = geometry.faces,
vertices = geometry.vertices,
il = faces.length,
totalArea = 0,
cumulativeAreas = [],
vA, vB, vC, vD;
// precompute face areas
for ( i = 0; i < il; i ++ ) {
face = faces[ i ];
vA = vertices[ face.a ];
vB = vertices[ face.b ];
vC = vertices[ face.c ];
face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
totalArea += face._area;
cumulativeAreas[ i ] = totalArea;
}
// binary search cumulative areas array
function binarySearchIndices( value ) {
function binarySearch( start, end ) {
// return closest larger index
// if exact number is not found
if ( end < start )
return start;
var mid = start + Math.floor( ( end - start ) / 2 );
if ( cumulativeAreas[ mid ] > value ) {
return binarySearch( start, mid - 1 );
} else if ( cumulativeAreas[ mid ] < value ) {
return binarySearch( mid + 1, end );
} else {
return mid;
}
}
var result = binarySearch( 0, cumulativeAreas.length - 1 )
return result;
}
// pick random face weighted by face area
var r, index,
result = [];
var stats = {};
for ( i = 0; i < n; i ++ ) {
r = THREE.Math.random16() * totalArea;
index = binarySearchIndices( r );
result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
if ( ! stats[ index ] ) {
stats[ index ] = 1;
} else {
stats[ index ] += 1;
}
}
return result;
},
// Get triangle area (half of parallelogram)
// http://mathworld.wolfram.com/TriangleArea.html
triangleArea: function () {
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
return function ( vectorA, vectorB, vectorC ) {
vector1.subVectors( vectorB, vectorA );
vector2.subVectors( vectorC, vectorA );
vector1.cross( vector2 );
return 0.5 * vector1.length();
};
}(),
// Center geometry so that 0,0,0 is in center of bounding box
center: function ( geometry ) {
geometry.computeBoundingBox();
var bb = geometry.boundingBox;
var offset = new THREE.Vector3();
offset.addVectors( bb.min, bb.max );
offset.multiplyScalar( -0.5 );
geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
geometry.computeBoundingBox();
return offset;
},
triangulateQuads: function ( geometry ) {
var i, il, j, jl;
var faces = [];
var faceVertexUvs = [];
for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
faceVertexUvs[ i ] = [];
}
for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
var face = geometry.faces[ i ];
faces.push( face );
for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
}
}
geometry.faces = faces;
geometry.faceVertexUvs = faceVertexUvs;
geometry.computeCentroids();
geometry.computeFaceNormals();
geometry.computeVertexNormals();
if ( geometry.hasTangents ) geometry.computeTangents();
}
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
THREE.ImageUtils = {
crossOrigin: undefined,
loadTexture: function ( url, mapping, onLoad, onError ) {
var loader = new THREE.ImageLoader();
loader.crossOrigin = this.crossOrigin;
var texture = new THREE.Texture( undefined, mapping );
var image = loader.load( url, function () {
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
} );
texture.image = image;
texture.sourceFile = url;
return texture;
},
loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
var texture = new THREE.CompressedTexture();
texture.mapping = mapping;
var request = new XMLHttpRequest();
request.onload = function () {
var buffer = request.response;
var dds = THREE.ImageUtils.parseDDS( buffer, true );
texture.format = dds.format;
texture.mipmaps = dds.mipmaps;
texture.image.width = dds.width;
texture.image.height = dds.height;
// gl.generateMipmap fails for compressed textures
// mipmaps must be embedded in the DDS file
// or texture filters must not use mipmapping
texture.generateMipmaps = false;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
request.onerror = onError;
request.open( 'GET', url, true );
request.responseType = "arraybuffer";
request.send( null );
return texture;
},
loadTextureCube: function ( array, mapping, onLoad, onError ) {
var images = [];
images.loadCount = 0;
var texture = new THREE.Texture();
texture.image = images;
if ( mapping !== undefined ) texture.mapping = mapping;
// no flipping needed for cube textures
texture.flipY = false;
for ( var i = 0, il = array.length; i < il; ++ i ) {
var cubeImage = new Image();
images[ i ] = cubeImage;
cubeImage.onload = function () {
images.loadCount += 1;
if ( images.loadCount === 6 ) {
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
};
cubeImage.onerror = onError;
cubeImage.crossOrigin = this.crossOrigin;
cubeImage.src = array[ i ];
}
return texture;
},
loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
var images = [];
images.loadCount = 0;
var texture = new THREE.CompressedTexture();
texture.image = images;
if ( mapping !== undefined ) texture.mapping = mapping;
// no flipping for cube textures
// (also flipping doesn't work for compressed textures )
texture.flipY = false;
// can't generate mipmaps for compressed textures
// mips must be embedded in DDS files
texture.generateMipmaps = false;
var generateCubeFaceCallback = function ( rq, img ) {
return function () {
var buffer = rq.response;
var dds = THREE.ImageUtils.parseDDS( buffer, true );
img.format = dds.format;
img.mipmaps = dds.mipmaps;
img.width = dds.width;
img.height = dds.height;
images.loadCount += 1;
if ( images.loadCount === 6 ) {
texture.format = dds.format;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
}
}
// compressed cubemap textures as 6 separate DDS files
if ( array instanceof Array ) {
for ( var i = 0, il = array.length; i < il; ++ i ) {
var cubeImage = {};
images[ i ] = cubeImage;
var request = new XMLHttpRequest();
request.onload = generateCubeFaceCallback( request, cubeImage );
request.onerror = onError;
var url = array[ i ];
request.open( 'GET', url, true );
request.responseType = "arraybuffer";
request.send( null );
}
// compressed cubemap texture stored in a single DDS file
} else {
var url = array;
var request = new XMLHttpRequest();
request.onload = function( ) {
var buffer = request.response;
var dds = THREE.ImageUtils.parseDDS( buffer, true );
if ( dds.isCubemap ) {
var faces = dds.mipmaps.length / dds.mipmapCount;
for ( var f = 0; f < faces; f ++ ) {
images[ f ] = { mipmaps : [] };
for ( var i = 0; i < dds.mipmapCount; i ++ ) {
images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
images[ f ].format = dds.format;
images[ f ].width = dds.width;
images[ f ].height = dds.height;
}
}
texture.format = dds.format;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
}
request.onerror = onError;
request.open( 'GET', url, true );
request.responseType = "arraybuffer";
request.send( null );
}
return texture;
},
loadDDSTexture: function ( url, mapping, onLoad, onError ) {
var images = [];
images.loadCount = 0;
var texture = new THREE.CompressedTexture();
texture.image = images;
if ( mapping !== undefined ) texture.mapping = mapping;
// no flipping for cube textures
// (also flipping doesn't work for compressed textures )
texture.flipY = false;
// can't generate mipmaps for compressed textures
// mips must be embedded in DDS files
texture.generateMipmaps = false;
{
var request = new XMLHttpRequest();
request.onload = function( ) {
var buffer = request.response;
var dds = THREE.ImageUtils.parseDDS( buffer, true );
if ( dds.isCubemap ) {
var faces = dds.mipmaps.length / dds.mipmapCount;
for ( var f = 0; f < faces; f ++ ) {
images[ f ] = { mipmaps : [] };
for ( var i = 0; i < dds.mipmapCount; i ++ ) {
images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
images[ f ].format = dds.format;
images[ f ].width = dds.width;
images[ f ].height = dds.height;
}
}
} else {
texture.image.width = dds.width;
texture.image.height = dds.height;
texture.mipmaps = dds.mipmaps;
}
texture.format = dds.format;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
request.onerror = onError;
request.open( 'GET', url, true );
request.responseType = "arraybuffer";
request.send( null );
}
return texture;
},
parseDDS: function ( buffer, loadMipmaps ) {
var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
// Adapted from @toji's DDS utils
// https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
// All values and structures referenced from:
// http://msdn.microsoft.com/en-us/library/bb943991.aspx/
var DDS_MAGIC = 0x20534444;
var DDSD_CAPS = 0x1,
DDSD_HEIGHT = 0x2,
DDSD_WIDTH = 0x4,
DDSD_PITCH = 0x8,
DDSD_PIXELFORMAT = 0x1000,
DDSD_MIPMAPCOUNT = 0x20000,
DDSD_LINEARSIZE = 0x80000,
DDSD_DEPTH = 0x800000;
var DDSCAPS_COMPLEX = 0x8,
DDSCAPS_MIPMAP = 0x400000,
DDSCAPS_TEXTURE = 0x1000;
var DDSCAPS2_CUBEMAP = 0x200,
DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
DDSCAPS2_VOLUME = 0x200000;
var DDPF_ALPHAPIXELS = 0x1,
DDPF_ALPHA = 0x2,
DDPF_FOURCC = 0x4,
DDPF_RGB = 0x40,
DDPF_YUV = 0x200,
DDPF_LUMINANCE = 0x20000;
function fourCCToInt32( value ) {
return value.charCodeAt(0) +
(value.charCodeAt(1) << 8) +
(value.charCodeAt(2) << 16) +
(value.charCodeAt(3) << 24);
}
function int32ToFourCC( value ) {
return String.fromCharCode(
value & 0xff,
(value >> 8) & 0xff,
(value >> 16) & 0xff,
(value >> 24) & 0xff
);
}
function loadARGBMip( buffer, dataOffset, width, height ) {
var dataLength = width*height*4;
var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
var byteArray = new Uint8Array( dataLength );
var dst = 0;
var src = 0;
for ( var y = 0; y < height; y++ ) {
for ( var x = 0; x < width; x++ ) {
var b = srcBuffer[src]; src++;
var g = srcBuffer[src]; src++;
var r = srcBuffer[src]; src++;
var a = srcBuffer[src]; src++;
byteArray[dst] = r; dst++; //r
byteArray[dst] = g; dst++; //g
byteArray[dst] = b; dst++; //b
byteArray[dst] = a; dst++; //a
}
}
return byteArray;
}
var FOURCC_DXT1 = fourCCToInt32("DXT1");
var FOURCC_DXT3 = fourCCToInt32("DXT3");
var FOURCC_DXT5 = fourCCToInt32("DXT5");
var headerLengthInt = 31; // The header length in 32 bit ints
// Offsets into the header array
var off_magic = 0;
var off_size = 1;
var off_flags = 2;
var off_height = 3;
var off_width = 4;
var off_mipmapCount = 7;
var off_pfFlags = 20;
var off_pfFourCC = 21;
var off_RGBBitCount = 22;
var off_RBitMask = 23;
var off_GBitMask = 24;
var off_BBitMask = 25;
var off_ABitMask = 26;
var off_caps = 27;
var off_caps2 = 28;
var off_caps3 = 29;
var off_caps4 = 30;
// Parse header
var header = new Int32Array( buffer, 0, headerLengthInt );
if ( header[ off_magic ] !== DDS_MAGIC ) {
console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
return dds;
}
if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
return dds;
}
var blockBytes;
var fourCC = header[ off_pfFourCC ];
var isRGBAUncompressed = false;
switch ( fourCC ) {
case FOURCC_DXT1:
blockBytes = 8;
dds.format = THREE.RGB_S3TC_DXT1_Format;
break;
case FOURCC_DXT3:
blockBytes = 16;
dds.format = THREE.RGBA_S3TC_DXT3_Format;
break;
case FOURCC_DXT5:
blockBytes = 16;
dds.format = THREE.RGBA_S3TC_DXT5_Format;
break;
default:
if( header[off_RGBBitCount] ==32
&& header[off_RBitMask]&0xff0000
&& header[off_GBitMask]&0xff00
&& header[off_BBitMask]&0xff
&& header[off_ABitMask]&0xff000000 ) {
isRGBAUncompressed = true;
blockBytes = 64;
dds.format = THREE.RGBAFormat;
} else {
console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
return dds;
}
}
dds.mipmapCount = 1;
if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
}
//TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
dds.width = header[ off_width ];
dds.height = header[ off_height ];
var dataOffset = header[ off_size ] + 4;
// Extract mipmaps buffers
var width = dds.width;
var height = dds.height;
var faces = dds.isCubemap ? 6 : 1;
for ( var face = 0; face < faces; face ++ ) {
for ( var i = 0; i < dds.mipmapCount; i ++ ) {
if( isRGBAUncompressed ) {
var byteArray = loadARGBMip( buffer, dataOffset, width, height );
var dataLength = byteArray.length;
} else {
var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
}
var mipmap = { "data": byteArray, "width": width, "height": height };
dds.mipmaps.push( mipmap );
dataOffset += dataLength;
width = Math.max( width * 0.5, 1 );
height = Math.max( height * 0.5, 1 );
}
width = dds.width;
height = dds.height;
}
return dds;
},
getNormalMap: function ( image, depth ) {
// Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
var cross = function ( a, b ) {
return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
}
var subtract = function ( a, b ) {
return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
}
var normalize = function ( a ) {
var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
}
depth = depth | 1;
var width = image.width;
var height = image.height;
var canvas = document.createElement( 'canvas' );
canvas.width = width;
canvas.height = height;
var context = canvas.getContext( '2d' );
context.drawImage( image, 0, 0 );
var data = context.getImageData( 0, 0, width, height ).data;
var imageData = context.createImageData( width, height );
var output = imageData.data;
for ( var x = 0; x < width; x ++ ) {
for ( var y = 0; y < height; y ++ ) {
var ly = y - 1 < 0 ? 0 : y - 1;
var uy = y + 1 > height - 1 ? height - 1 : y + 1;
var lx = x - 1 < 0 ? 0 : x - 1;
var ux = x + 1 > width - 1 ? width - 1 : x + 1;
var points = [];
var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
var normals = [];
var num_points = points.length;
for ( var i = 0; i < num_points; i ++ ) {
var v1 = points[ i ];
var v2 = points[ ( i + 1 ) % num_points ];
v1 = subtract( v1, origin );
v2 = subtract( v2, origin );
normals.push( normalize( cross( v1, v2 ) ) );
}
var normal = [ 0, 0, 0 ];
for ( var i = 0; i < normals.length; i ++ ) {
normal[ 0 ] += normals[ i ][ 0 ];
normal[ 1 ] += normals[ i ][ 1 ];
normal[ 2 ] += normals[ i ][ 2 ];
}
normal[ 0 ] /= normals.length;
normal[ 1 ] /= normals.length;
normal[ 2 ] /= normals.length;
var idx = ( y * width + x ) * 4;
output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
output[ idx + 3 ] = 255;
}
}
context.putImageData( imageData, 0, 0 );
return canvas;
},
generateDataTexture: function ( width, height, color ) {
var size = width * height;
var data = new Uint8Array( 3 * size );
var r = Math.floor( color.r * 255 );
var g = Math.floor( color.g * 255 );
var b = Math.floor( color.b * 255 );
for ( var i = 0; i < size; i ++ ) {
data[ i * 3 ] = r;
data[ i * 3 + 1 ] = g;
data[ i * 3 + 2 ] = b;
}
var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
texture.needsUpdate = true;
return texture;
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.SceneUtils = {
createMultiMaterialObject: function ( geometry, materials ) {
var group = new THREE.Object3D();
for ( var i = 0, l = materials.length; i < l; i ++ ) {
group.add( new THREE.Mesh( geometry, materials[ i ] ) );
}
return group;
},
detach : function ( child, parent, scene ) {
child.applyMatrix( parent.matrixWorld );
parent.remove( child );
scene.add( child );
},
attach: function ( child, scene, parent ) {
var matrixWorldInverse = new THREE.Matrix4();
matrixWorldInverse.getInverse( parent.matrixWorld );
child.applyMatrix( matrixWorldInverse );
scene.remove( child );
parent.add( child );
}
};
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author alteredq / http://alteredqualia.com/
*
* For Text operations in three.js (See TextGeometry)
*
* It uses techniques used in:
*
* typeface.js and canvastext
* For converting fonts and rendering with javascript
* http://typeface.neocracy.org
*
* Triangulation ported from AS3
* Simple Polygon Triangulation
* http://actionsnippet.com/?p=1462
*
* A Method to triangulate shapes with holes
* http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
*
*/
THREE.FontUtils = {
faces : {},
// Just for now. face[weight][style]
face : "helvetiker",
weight: "normal",
style : "normal",
size : 150,
divisions : 10,
getFace : function() {
return this.faces[ this.face ][ this.weight ][ this.style ];
},
loadFace : function( data ) {
var family = data.familyName.toLowerCase();
var ThreeFont = this;
ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
return data;
},
drawText : function( text ) {
var characterPts = [], allPts = [];
// RenderText
var i, p,
face = this.getFace(),
scale = this.size / face.resolution,
offset = 0,
chars = String( text ).split( '' ),
length = chars.length;
var fontPaths = [];
for ( i = 0; i < length; i ++ ) {
var path = new THREE.Path();
var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
offset += ret.offset;
fontPaths.push( ret.path );
}
// get the width
var width = offset / 2;
//
// for ( p = 0; p < allPts.length; p++ ) {
//
// allPts[ p ].x -= width;
//
// }
//var extract = this.extractPoints( allPts, characterPts );
//extract.contour = allPts;
//extract.paths = fontPaths;
//extract.offset = width;
return { paths : fontPaths, offset : width };
},
extractGlyphPoints : function( c, face, scale, offset, path ) {
var pts = [];
var i, i2, divisions,
outline, action, length,
scaleX, scaleY,
x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
laste,
glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
if ( !glyph ) return;
if ( glyph.o ) {
outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
length = outline.length;
scaleX = scale;
scaleY = scale;
for ( i = 0; i < length; ) {
action = outline[ i ++ ];
//console.log( action );
switch( action ) {
case 'm':
// Move To
x = outline[ i++ ] * scaleX + offset;
y = outline[ i++ ] * scaleY;
path.moveTo( x, y );
break;
case 'l':
// Line To
x = outline[ i++ ] * scaleX + offset;
y = outline[ i++ ] * scaleY;
path.lineTo(x,y);
break;
case 'q':
// QuadraticCurveTo
cpx = outline[ i++ ] * scaleX + offset;
cpy = outline[ i++ ] * scaleY;
cpx1 = outline[ i++ ] * scaleX + offset;
cpy1 = outline[ i++ ] * scaleY;
path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
laste = pts[ pts.length - 1 ];
if ( laste ) {
cpx0 = laste.x;
cpy0 = laste.y;
for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
var t = i2 / divisions;
var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
}
}
break;
case 'b':
// Cubic Bezier Curve
cpx = outline[ i++ ] * scaleX + offset;
cpy = outline[ i++ ] * scaleY;
cpx1 = outline[ i++ ] * scaleX + offset;
cpy1 = outline[ i++ ] * -scaleY;
cpx2 = outline[ i++ ] * scaleX + offset;
cpy2 = outline[ i++ ] * -scaleY;
path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
laste = pts[ pts.length - 1 ];
if ( laste ) {
cpx0 = laste.x;
cpy0 = laste.y;
for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
var t = i2 / divisions;
var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
}
}
break;
}
}
}
return { offset: glyph.ha*scale, path:path};
}
};
THREE.FontUtils.generateShapes = function( text, parameters ) {
// Parameters
parameters = parameters || {};
var size = parameters.size !== undefined ? parameters.size : 100;
var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
var font = parameters.font !== undefined ? parameters.font : "helvetiker";
var weight = parameters.weight !== undefined ? parameters.weight : "normal";
var style = parameters.style !== undefined ? parameters.style : "normal";
THREE.FontUtils.size = size;
THREE.FontUtils.divisions = curveSegments;
THREE.FontUtils.face = font;
THREE.FontUtils.weight = weight;
THREE.FontUtils.style = style;
// Get a Font data json object
var data = THREE.FontUtils.drawText( text );
var paths = data.paths;
var shapes = [];
for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
}
return shapes;
};
/**
* This code is a quick port of code written in C++ which was submitted to
* flipcode.com by John W. Ratcliff // July 22, 2000
* See original code and more information here:
* http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
*
* ported to actionscript by Zevan Rosser
* www.actionsnippet.com
*
* ported to javascript by Joshua Koo
* http://www.lab4games.net/zz85/blog
*
*/
( function( namespace ) {
var EPSILON = 0.0000000001;
// takes in an contour array and returns
var process = function( contour, indices ) {
var n = contour.length;
if ( n < 3 ) return null;
var result = [],
verts = [],
vertIndices = [];
/* we want a counter-clockwise polygon in verts */
var u, v, w;
if ( area( contour ) > 0.0 ) {
for ( v = 0; v < n; v++ ) verts[ v ] = v;
} else {
for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
}
var nv = n;
/* remove nv - 2 vertices, creating 1 triangle every time */
var count = 2 * nv; /* error detection */
for( v = nv - 1; nv > 2; ) {
/* if we loop, it is probably a non-simple polygon */
if ( ( count-- ) <= 0 ) {
//** Triangulate: ERROR - probable bad polygon!
//throw ( "Warning, unable to triangulate polygon!" );
//return null;
// Sometimes warning is fine, especially polygons are triangulated in reverse.
console.log( "Warning, unable to triangulate polygon!" );
if ( indices ) return vertIndices;
return result;
}
/* three consecutive vertices in current polygon, <u,v,w> */
u = v; if ( nv <= u ) u = 0; /* previous */
v = u + 1; if ( nv <= v ) v = 0; /* new v */
w = v + 1; if ( nv <= w ) w = 0; /* next */
if ( snip( contour, u, v, w, nv, verts ) ) {
var a, b, c, s, t;
/* true names of the vertices */
a = verts[ u ];
b = verts[ v ];
c = verts[ w ];
/* output Triangle */
result.push( [ contour[ a ],
contour[ b ],
contour[ c ] ] );
vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
/* remove v from the remaining polygon */
for( s = v, t = v + 1; t < nv; s++, t++ ) {
verts[ s ] = verts[ t ];
}
nv--;
/* reset error detection counter */
count = 2 * nv;
}
}
if ( indices ) return vertIndices;
return result;
};
// calculate area of the contour polygon
var area = function ( contour ) {
var n = contour.length;
var a = 0.0;
for( var p = n - 1, q = 0; q < n; p = q++ ) {
a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
}
return a * 0.5;
};
var snip = function ( contour, u, v, w, n, verts ) {
var p;
var ax, ay, bx, by;
var cx, cy, px, py;
ax = contour[ verts[ u ] ].x;
ay = contour[ verts[ u ] ].y;
bx = contour[ verts[ v ] ].x;
by = contour[ verts[ v ] ].y;
cx = contour[ verts[ w ] ].x;
cy = contour[ verts[ w ] ].y;
if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
var aX, aY, bX, bY, cX, cY;
var apx, apy, bpx, bpy, cpx, cpy;
var cCROSSap, bCROSScp, aCROSSbp;
aX = cx - bx; aY = cy - by;
bX = ax - cx; bY = ay - cy;
cX = bx - ax; cY = by - ay;
for ( p = 0; p < n; p++ ) {
px = contour[ verts[ p ] ].x
py = contour[ verts[ p ] ].y
if ( ( (px === ax) && (py === ay) ) ||
( (px === bx) && (py === by) ) ||
( (px === cx) && (py === cy) ) ) continue;
apx = px - ax; apy = py - ay;
bpx = px - bx; bpy = py - by;
cpx = px - cx; cpy = py - cy;
// see if p is inside triangle abc
aCROSSbp = aX*bpy - aY*bpx;
cCROSSap = cX*apy - cY*apx;
bCROSScp = bX*cpy - bY*cpx;
if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
}
return true;
};
namespace.Triangulate = process;
namespace.Triangulate.area = area;
return namespace;
})(THREE.FontUtils);
// To use the typeface.js face files, hook up the API
self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
THREE.typeface_js = self._typeface_js;
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Extensible curve object
*
* Some common of Curve methods
* .getPoint(t), getTangent(t)
* .getPointAt(u), getTagentAt(u)
* .getPoints(), .getSpacedPoints()
* .getLength()
* .updateArcLengths()
*
* This following classes subclasses THREE.Curve:
*
* -- 2d classes --
* THREE.LineCurve
* THREE.QuadraticBezierCurve
* THREE.CubicBezierCurve
* THREE.SplineCurve
* THREE.ArcCurve
* THREE.EllipseCurve
*
* -- 3d classes --
* THREE.LineCurve3
* THREE.QuadraticBezierCurve3
* THREE.CubicBezierCurve3
* THREE.SplineCurve3
* THREE.ClosedSplineCurve3
*
* A series of curves can be represented as a THREE.CurvePath
*
**/
/**************************************************************
* Abstract Curve base class
**************************************************************/
THREE.Curve = function () {
};
// Virtual base class method to overwrite and implement in subclasses
// - t [0 .. 1]
THREE.Curve.prototype.getPoint = function ( t ) {
console.log( "Warning, getPoint() not implemented!" );
return null;
};
// Get point at relative position in curve according to arc length
// - u [0 .. 1]
THREE.Curve.prototype.getPointAt = function ( u ) {
var t = this.getUtoTmapping( u );
return this.getPoint( t );
};
// Get sequence of points using getPoint( t )
THREE.Curve.prototype.getPoints = function ( divisions ) {
if ( !divisions ) divisions = 5;
var d, pts = [];
for ( d = 0; d <= divisions; d ++ ) {
pts.push( this.getPoint( d / divisions ) );
}
return pts;
};
// Get sequence of points using getPointAt( u )
THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
if ( !divisions ) divisions = 5;
var d, pts = [];
for ( d = 0; d <= divisions; d ++ ) {
pts.push( this.getPointAt( d / divisions ) );
}
return pts;
};
// Get total curve arc length
THREE.Curve.prototype.getLength = function () {
var lengths = this.getLengths();
return lengths[ lengths.length - 1 ];
};
// Get list of cumulative segment lengths
THREE.Curve.prototype.getLengths = function ( divisions ) {
if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
if ( this.cacheArcLengths
&& ( this.cacheArcLengths.length == divisions + 1 )
&& !this.needsUpdate) {
//console.log( "cached", this.cacheArcLengths );
return this.cacheArcLengths;
}
this.needsUpdate = false;
var cache = [];
var current, last = this.getPoint( 0 );
var p, sum = 0;
cache.push( 0 );
for ( p = 1; p <= divisions; p ++ ) {
current = this.getPoint ( p / divisions );
sum += current.distanceTo( last );
cache.push( sum );
last = current;
}
this.cacheArcLengths = cache;
return cache; // { sums: cache, sum:sum }; Sum is in the last element.
};
THREE.Curve.prototype.updateArcLengths = function() {
this.needsUpdate = true;
this.getLengths();
};
// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
var arcLengths = this.getLengths();
var i = 0, il = arcLengths.length;
var targetArcLength; // The targeted u distance value to get
if ( distance ) {
targetArcLength = distance;
} else {
targetArcLength = u * arcLengths[ il - 1 ];
}
//var time = Date.now();
// binary search for the index with largest value smaller than target u distance
var low = 0, high = il - 1, comparison;
while ( low <= high ) {
i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
comparison = arcLengths[ i ] - targetArcLength;
if ( comparison < 0 ) {
low = i + 1;
continue;
} else if ( comparison > 0 ) {
high = i - 1;
continue;
} else {
high = i;
break;
// DONE
}
}
i = high;
//console.log('b' , i, low, high, Date.now()- time);
if ( arcLengths[ i ] == targetArcLength ) {
var t = i / ( il - 1 );
return t;
}
// we could get finer grain at lengths, or use simple interpolatation between two points
var lengthBefore = arcLengths[ i ];
var lengthAfter = arcLengths[ i + 1 ];
var segmentLength = lengthAfter - lengthBefore;
// determine where we are between the 'before' and 'after' points
var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
// add that fractional amount to t
var t = ( i + segmentFraction ) / ( il -1 );
return t;
};
// Returns a unit vector tangent at t
// In case any sub curve does not implement its tangent derivation,
// 2 points a small delta apart will be used to find its gradient
// which seems to give a reasonable approximation
THREE.Curve.prototype.getTangent = function( t ) {
var delta = 0.0001;
var t1 = t - delta;
var t2 = t + delta;
// Capping in case of danger
if ( t1 < 0 ) t1 = 0;
if ( t2 > 1 ) t2 = 1;
var pt1 = this.getPoint( t1 );
var pt2 = this.getPoint( t2 );
var vec = pt2.clone().sub(pt1);
return vec.normalize();
};
THREE.Curve.prototype.getTangentAt = function ( u ) {
var t = this.getUtoTmapping( u );
return this.getTangent( t );
};
/**************************************************************
* Utils
**************************************************************/
THREE.Curve.Utils = {
tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
},
// Puay Bing, thanks for helping with this derivative!
tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
return -3 * p0 * (1 - t) * (1 - t) +
3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
6 * t * p2 * (1-t) - 3 * t * t * p2 +
3 * t * t * p3;
},
tangentSpline: function ( t, p0, p1, p2, p3 ) {
// To check if my formulas are correct
var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
var h11 = 3 * t * t - 2 * t; // t3 − t2
return h00 + h10 + h01 + h11;
},
// Catmull-Rom
interpolate: function( p0, p1, p2, p3, t ) {
var v0 = ( p2 - p0 ) * 0.5;
var v1 = ( p3 - p1 ) * 0.5;
var t2 = t * t;
var t3 = t * t2;
return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
}
};
// TODO: Transformation for Curves?
/**************************************************************
* 3D Curves
**************************************************************/
// A Factory method for creating new curve subclasses
THREE.Curve.create = function ( constructor, getPointFunc ) {
constructor.prototype = Object.create( THREE.Curve.prototype );
constructor.prototype.getPoint = getPointFunc;
return constructor;
};
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*
**/
/**************************************************************
* Curved Path - a curve path is simply a array of connected
* curves, but retains the api of a curve
**************************************************************/
THREE.CurvePath = function () {
this.curves = [];
this.bends = [];
this.autoClose = false; // Automatically closes the path
};
THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
THREE.CurvePath.prototype.add = function ( curve ) {
this.curves.push( curve );
};
THREE.CurvePath.prototype.checkConnection = function() {
// TODO
// If the ending of curve is not connected to the starting
// or the next curve, then, this is not a real path
};
THREE.CurvePath.prototype.closePath = function() {
// TODO Test
// and verify for vector3 (needs to implement equals)
// Add a line curve if start and end of lines are not connected
var startPoint = this.curves[0].getPoint(0);
var endPoint = this.curves[this.curves.length-1].getPoint(1);
if (!startPoint.equals(endPoint)) {
this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
}
};
// To get accurate point with reference to
// entire path distance at time t,
// following has to be done:
// 1. Length of each sub path have to be known
// 2. Locate and identify type of curve
// 3. Get t for the curve
// 4. Return curve.getPointAt(t')
THREE.CurvePath.prototype.getPoint = function( t ) {
var d = t * this.getLength();
var curveLengths = this.getCurveLengths();
var i = 0, diff, curve;
// To think about boundaries points.
while ( i < curveLengths.length ) {
if ( curveLengths[ i ] >= d ) {
diff = curveLengths[ i ] - d;
curve = this.curves[ i ];
var u = 1 - diff / curve.getLength();
return curve.getPointAt( u );
break;
}
i ++;
}
return null;
// loop where sum != 0, sum > d , sum+1 <d
};
/*
THREE.CurvePath.prototype.getTangent = function( t ) {
};*/
// We cannot use the default THREE.Curve getPoint() with getLength() because in
// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
// getPoint() depends on getLength
THREE.CurvePath.prototype.getLength = function() {
var lens = this.getCurveLengths();
return lens[ lens.length - 1 ];
};
// Compute lengths and cache them
// We cannot overwrite getLengths() because UtoT mapping uses it.
THREE.CurvePath.prototype.getCurveLengths = function() {
// We use cache values if curves and cache array are same length
if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
return this.cacheLengths;
};
// Get length of subsurve
// Push sums into cached array
var lengths = [], sums = 0;
var i, il = this.curves.length;
for ( i = 0; i < il; i ++ ) {
sums += this.curves[ i ].getLength();
lengths.push( sums );
}
this.cacheLengths = lengths;
return lengths;
};
// Returns min and max coordinates, as well as centroid
THREE.CurvePath.prototype.getBoundingBox = function () {
var points = this.getPoints();
var maxX, maxY, maxZ;
var minX, minY, minZ;
maxX = maxY = Number.NEGATIVE_INFINITY;
minX = minY = Number.POSITIVE_INFINITY;
var p, i, il, sum;
var v3 = points[0] instanceof THREE.Vector3;
sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
for ( i = 0, il = points.length; i < il; i ++ ) {
p = points[ i ];
if ( p.x > maxX ) maxX = p.x;
else if ( p.x < minX ) minX = p.x;
if ( p.y > maxY ) maxY = p.y;
else if ( p.y < minY ) minY = p.y;
if ( v3 ) {
if ( p.z > maxZ ) maxZ = p.z;
else if ( p.z < minZ ) minZ = p.z;
}
sum.add( p );
}
var ret = {
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY,
centroid: sum.divideScalar( il )
};
if ( v3 ) {
ret.maxZ = maxZ;
ret.minZ = minZ;
}
return ret;
};
/**************************************************************
* Create Geometries Helpers
**************************************************************/
/// Generate geometry from path points (for Line or ParticleSystem objects)
THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
var pts = this.getPoints( divisions, true );
return this.createGeometry( pts );
};
// Generate geometry from equidistance sampling along the path
THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
var pts = this.getSpacedPoints( divisions, true );
return this.createGeometry( pts );
};
THREE.CurvePath.prototype.createGeometry = function( points ) {
var geometry = new THREE.Geometry();
for ( var i = 0; i < points.length; i ++ ) {
geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
}
return geometry;
};
/**************************************************************
* Bend / Wrap Helper Methods
**************************************************************/
// Wrap path / Bend modifiers?
THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
this.bends.push( bendpath );
};
THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
var i, il;
if ( !bends ) {
bends = this.bends;
}
for ( i = 0, il = bends.length; i < il; i ++ ) {
oldPts = this.getWrapPoints( oldPts, bends[ i ] );
}
return oldPts;
};
THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
var oldPts = this.getSpacedPoints( segments );
var i, il;
if ( !bends ) {
bends = this.bends;
}
for ( i = 0, il = bends.length; i < il; i ++ ) {
oldPts = this.getWrapPoints( oldPts, bends[ i ] );
}
return oldPts;
};
// This returns getPoints() bend/wrapped around the contour of a path.
// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
var bounds = this.getBoundingBox();
var i, il, p, oldX, oldY, xNorm;
for ( i = 0, il = oldPts.length; i < il; i ++ ) {
p = oldPts[ i ];
oldX = p.x;
oldY = p.y;
xNorm = oldX / bounds.maxX;
// If using actual distance, for length > path, requires line extrusions
//xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
xNorm = path.getUtoTmapping( xNorm, oldX );
// check for out of bounds?
var pathPt = path.getPoint( xNorm );
var normal = path.getTangent( xNorm );
normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
p.x = pathPt.x + normal.x;
p.y = pathPt.y + normal.y;
}
return oldPts;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Gyroscope = function () {
THREE.Object3D.call( this );
};
THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
this.matrixAutoUpdate && this.updateMatrix();
// update matrixWorld
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent ) {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
} else {
this.matrixWorld.copy( this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].updateMatrixWorld( force );
}
};
THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Creates free form 2d path using series of points, lines or curves.
*
**/
THREE.Path = function ( points ) {
THREE.CurvePath.call(this);
this.actions = [];
if ( points ) {
this.fromPoints( points );
}
};
THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
THREE.PathActions = {
MOVE_TO: 'moveTo',
LINE_TO: 'lineTo',
QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
CSPLINE_THRU: 'splineThru', // Catmull-rom spline
ARC: 'arc', // Circle
ELLIPSE: 'ellipse'
};
// TODO Clean up PATH API
// Create path using straight lines to connect all points
// - vectors: array of Vector2
THREE.Path.prototype.fromPoints = function ( vectors ) {
this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
this.lineTo( vectors[ v ].x, vectors[ v ].y );
};
};
// startPath() endPath()?
THREE.Path.prototype.moveTo = function ( x, y ) {
var args = Array.prototype.slice.call( arguments );
this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
};
THREE.Path.prototype.lineTo = function ( x, y ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
};
THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
new THREE.Vector2( aCPx, aCPy ),
new THREE.Vector2( aX, aY ) );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
};
THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
aCP2x, aCP2y,
aX, aY ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
new THREE.Vector2( aCP1x, aCP1y ),
new THREE.Vector2( aCP2x, aCP2y ),
new THREE.Vector2( aX, aY ) );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
};
THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
var args = Array.prototype.slice.call( arguments );
var lastargs = this.actions[ this.actions.length - 1 ].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
//---
var npts = [ new THREE.Vector2( x0, y0 ) ];
Array.prototype.push.apply( npts, pts );
var curve = new THREE.SplineCurve( npts );
this.curves.push( curve );
this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
};
// FUTURE: Change the API or follow canvas API?
THREE.Path.prototype.arc = function ( aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise ) {
var lastargs = this.actions[ this.actions.length - 1].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
this.absarc(aX + x0, aY + y0, aRadius,
aStartAngle, aEndAngle, aClockwise );
};
THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise ) {
this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
};
THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise ) {
var lastargs = this.actions[ this.actions.length - 1].args;
var x0 = lastargs[ lastargs.length - 2 ];
var y0 = lastargs[ lastargs.length - 1 ];
this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise );
};
THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise ) {
var args = Array.prototype.slice.call( arguments );
var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
aStartAngle, aEndAngle, aClockwise );
this.curves.push( curve );
var lastPoint = curve.getPoint(1);
args.push(lastPoint.x);
args.push(lastPoint.y);
this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
};
THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
if ( ! divisions ) divisions = 40;
var points = [];
for ( var i = 0; i < divisions; i ++ ) {
points.push( this.getPoint( i / divisions ) );
//if( !this.getPoint( i / divisions ) ) throw "DIE";
}
// if ( closedPath ) {
//
// points.push( points[ 0 ] );
//
// }
return points;
};
/* Return an array of vectors based on contour of the path */
THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
if (this.useSpacedPoints) {
console.log('tata');
return this.getSpacedPoints( divisions, closedPath );
}
divisions = divisions || 12;
var points = [];
var i, il, item, action, args;
var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
laste, j,
t, tx, ty;
for ( i = 0, il = this.actions.length; i < il; i ++ ) {
item = this.actions[ i ];
action = item.action;
args = item.args;
switch( action ) {
case THREE.PathActions.MOVE_TO:
points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
break;
case THREE.PathActions.LINE_TO:
points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
break;
case THREE.PathActions.QUADRATIC_CURVE_TO:
cpx = args[ 2 ];
cpy = args[ 3 ];
cpx1 = args[ 0 ];
cpy1 = args[ 1 ];
if ( points.length > 0 ) {
laste = points[ points.length - 1 ];
cpx0 = laste.x;
cpy0 = laste.y;
} else {
laste = this.actions[ i - 1 ].args;
cpx0 = laste[ laste.length - 2 ];
cpy0 = laste[ laste.length - 1 ];
}
for ( j = 1; j <= divisions; j ++ ) {
t = j / divisions;
tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
points.push( new THREE.Vector2( tx, ty ) );
}
break;
case THREE.PathActions.BEZIER_CURVE_TO:
cpx = args[ 4 ];
cpy = args[ 5 ];
cpx1 = args[ 0 ];
cpy1 = args[ 1 ];
cpx2 = args[ 2 ];
cpy2 = args[ 3 ];
if ( points.length > 0 ) {
laste = points[ points.length - 1 ];
cpx0 = laste.x;
cpy0 = laste.y;
} else {
laste = this.actions[ i - 1 ].args;
cpx0 = laste[ laste.length - 2 ];
cpy0 = laste[ laste.length - 1 ];
}
for ( j = 1; j <= divisions; j ++ ) {
t = j / divisions;
tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
points.push( new THREE.Vector2( tx, ty ) );
}
break;
case THREE.PathActions.CSPLINE_THRU:
laste = this.actions[ i - 1 ].args;
var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
var spts = [ last ];
var n = divisions * args[ 0 ].length;
spts = spts.concat( args[ 0 ] );
var spline = new THREE.SplineCurve( spts );
for ( j = 1; j <= n; j ++ ) {
points.push( spline.getPointAt( j / n ) ) ;
}
break;
case THREE.PathActions.ARC:
var aX = args[ 0 ], aY = args[ 1 ],
aRadius = args[ 2 ],
aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
aClockwise = !!args[ 5 ];
var deltaAngle = aEndAngle - aStartAngle;
var angle;
var tdivisions = divisions * 2;
for ( j = 1; j <= tdivisions; j ++ ) {
t = j / tdivisions;
if ( ! aClockwise ) {
t = 1 - t;
}
angle = aStartAngle + t * deltaAngle;
tx = aX + aRadius * Math.cos( angle );
ty = aY + aRadius * Math.sin( angle );
//console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
points.push( new THREE.Vector2( tx, ty ) );
}
//console.log(points);
break;
case THREE.PathActions.ELLIPSE:
var aX = args[ 0 ], aY = args[ 1 ],
xRadius = args[ 2 ],
yRadius = args[ 3 ],
aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
aClockwise = !!args[ 6 ];
var deltaAngle = aEndAngle - aStartAngle;
var angle;
var tdivisions = divisions * 2;
for ( j = 1; j <= tdivisions; j ++ ) {
t = j / tdivisions;
if ( ! aClockwise ) {
t = 1 - t;
}
angle = aStartAngle + t * deltaAngle;
tx = aX + xRadius * Math.cos( angle );
ty = aY + yRadius * Math.sin( angle );
//console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
points.push( new THREE.Vector2( tx, ty ) );
}
//console.log(points);
break;
} // end switch
}
// Normalize to remove the closing point by default.
var lastPoint = points[ points.length - 1];
var EPSILON = 0.0000000001;
if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
points.splice( points.length - 1, 1);
if ( closedPath ) {
points.push( points[ 0 ] );
}
return points;
};
// Breaks path into shapes
THREE.Path.prototype.toShapes = function( isCCW ) {
function isPointInsidePolygon( inPt, inPolygon ) {
var EPSILON = 0.0000000001;
var polyLen = inPolygon.length;
// inPt on polygon contour => immediate success or
// toggling of inside/outside at every single! intersection point of an edge
// with the horizontal line through inPt, left of inPt
// not counting lowerY endpoints of edges and whole edges on that line
var inside = false;
for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
var edgeLowPt = inPolygon[ p ];
var edgeHighPt = inPolygon[ q ];
var edgeDx = edgeHighPt.x - edgeLowPt.x;
var edgeDy = edgeHighPt.y - edgeLowPt.y;
if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
if ( edgeDy < 0 ) {
edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
}
if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
if ( inPt.y == edgeLowPt.y ) {
if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
// continue; // no intersection or edgeLowPt => doesn't count !!!
} else {
var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
if ( perpEdge == 0 ) return true; // inPt is on contour ?
if ( perpEdge < 0 ) continue;
inside = !inside; // true intersection left of inPt
}
} else { // parallel or colinear
if ( inPt.y != edgeLowPt.y ) continue; // parallel
// egde lies on the same horizontal line as inPt
if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
// continue;
}
}
return inside;
}
var i, il, item, action, args;
var subPaths = [], lastPath = new THREE.Path();
for ( i = 0, il = this.actions.length; i < il; i ++ ) {
item = this.actions[ i ];
args = item.args;
action = item.action;
if ( action == THREE.PathActions.MOVE_TO ) {
if ( lastPath.actions.length != 0 ) {
subPaths.push( lastPath );
lastPath = new THREE.Path();
}
}
lastPath[ action ].apply( lastPath, args );
}
if ( lastPath.actions.length != 0 ) {
subPaths.push( lastPath );
}
// console.log(subPaths);
if ( subPaths.length == 0 ) return [];
var solid, tmpPath, tmpShape, shapes = [];
if ( subPaths.length == 1) {
tmpPath = subPaths[0];
tmpShape = new THREE.Shape();
tmpShape.actions = tmpPath.actions;
tmpShape.curves = tmpPath.curves;
shapes.push( tmpShape );
return shapes;
}
var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
holesFirst = isCCW ? !holesFirst : holesFirst;
// console.log("Holes first", holesFirst);
var betterShapeHoles = [];
var newShapes = [];
var newShapeHoles = [];
var mainIdx = 0;
var tmpPoints;
newShapes[mainIdx] = undefined;
newShapeHoles[mainIdx] = [];
for ( i = 0, il = subPaths.length; i < il; i ++ ) {
tmpPath = subPaths[ i ];
tmpPoints = tmpPath.getPoints();
solid = THREE.Shape.Utils.isClockWise( tmpPoints );
solid = isCCW ? !solid : solid;
if ( solid ) {
if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
newShapes[mainIdx].s.actions = tmpPath.actions;
newShapes[mainIdx].s.curves = tmpPath.curves;
if ( holesFirst ) mainIdx++;
newShapeHoles[mainIdx] = [];
//console.log('cw', i);
} else {
newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
//console.log('ccw', i);
}
}
if ( newShapes.length > 1 ) {
var ambigious = false;
var toChange = [];
for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
betterShapeHoles[sIdx] = [];
}
for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
var sh = newShapes[sIdx];
var sho = newShapeHoles[sIdx];
for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
var ho = sho[hIdx];
var hole_unassigned = true;
for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
if ( hole_unassigned ) {
hole_unassigned = false;
betterShapeHoles[s2Idx].push( ho );
} else {
ambigious = true;
}
}
}
if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
}
}
// console.log("ambigious: ", ambigious);
if ( toChange.length > 0 ) {
// console.log("to change: ", toChange);
if (! ambigious) newShapeHoles = betterShapeHoles;
}
}
var tmpHoles, j, jl;
for ( i = 0, il = newShapes.length; i < il; i ++ ) {
tmpShape = newShapes[i].s;
shapes.push( tmpShape );
tmpHoles = newShapeHoles[i];
for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
tmpShape.holes.push( tmpHoles[j].h );
}
}
//console.log("shape", shapes);
return shapes;
};
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Defines a 2d shape plane using paths.
**/
// STEP 1 Create a path.
// STEP 2 Turn path into shape.
// STEP 3 ExtrudeGeometry takes in Shape/Shapes
// STEP 3a - Extract points from each shape, turn to vertices
// STEP 3b - Triangulate each shape, add faces.
THREE.Shape = function () {
THREE.Path.apply( this, arguments );
this.holes = [];
};
THREE.Shape.prototype = Object.create( THREE.Path.prototype );
// Convenience method to return ExtrudeGeometry
THREE.Shape.prototype.extrude = function ( options ) {
var extruded = new THREE.ExtrudeGeometry( this, options );
return extruded;
};
// Convenience method to return ShapeGeometry
THREE.Shape.prototype.makeGeometry = function ( options ) {
var geometry = new THREE.ShapeGeometry( this, options );
return geometry;
};
// Get points of holes
THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
var i, il = this.holes.length, holesPts = [];
for ( i = 0; i < il; i ++ ) {
holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
}
return holesPts;
};
// Get points of holes (spaced by regular distance)
THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
var i, il = this.holes.length, holesPts = [];
for ( i = 0; i < il; i ++ ) {
holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
}
return holesPts;
};
// Get points of shape and holes (keypoints based on segments parameter)
THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
return {
shape: this.getTransformedPoints( divisions ),
holes: this.getPointsHoles( divisions )
};
};
THREE.Shape.prototype.extractPoints = function ( divisions ) {
if (this.useSpacedPoints) {
return this.extractAllSpacedPoints(divisions);
}
return this.extractAllPoints(divisions);
};
//
// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
//
// return {
//
// shape: this.transform( bend, divisions ),
// holes: this.getPointsHoles( divisions, bend )
//
// };
//
// };
// Get points of shape and holes (spaced by regular distance)
THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
return {
shape: this.getTransformedSpacedPoints( divisions ),
holes: this.getSpacedPointsHoles( divisions )
};
};
/**************************************************************
* Utils
**************************************************************/
THREE.Shape.Utils = {
triangulateShape: function ( contour, holes ) {
function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
// inOtherPt needs to be colinear to the inSegment
if ( inSegPt1.x != inSegPt2.x ) {
if ( inSegPt1.x < inSegPt2.x ) {
return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
} else {
return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
}
} else {
if ( inSegPt1.y < inSegPt2.y ) {
return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
} else {
return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
}
}
}
function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
var EPSILON = 0.0000000001;
var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
var limit = seg1dy * seg2dx - seg1dx * seg2dy;
var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
if ( Math.abs(limit) > EPSILON ) { // not parallel
var perpSeg2;
if ( limit > 0 ) {
if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
} else {
if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
}
// i.e. to reduce rounding errors
// intersection at endpoint of segment#1?
if ( perpSeg2 == 0 ) {
if ( ( inExcludeAdjacentSegs ) &&
( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
return [ inSeg1Pt1 ];
}
if ( perpSeg2 == limit ) {
if ( ( inExcludeAdjacentSegs ) &&
( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
return [ inSeg1Pt2 ];
}
// intersection at endpoint of segment#2?
if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
// return real intersection point
var factorSeg1 = perpSeg2 / limit;
return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
} else { // parallel or colinear
if ( ( perpSeg1 != 0 ) ||
( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
// they are collinear or degenerate
var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
// both segments are points
if ( seg1Pt && seg2Pt ) {
if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
(inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
return [ inSeg1Pt1 ]; // they are the same point
}
// segment#1 is a single point
if ( seg1Pt ) {
if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
return [ inSeg1Pt1 ];
}
// segment#2 is a single point
if ( seg2Pt ) {
if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
return [ inSeg2Pt1 ];
}
// they are collinear segments, which might overlap
var seg1min, seg1max, seg1minVal, seg1maxVal;
var seg2min, seg2max, seg2minVal, seg2maxVal;
if (seg1dx != 0) { // the segments are NOT on a vertical line
if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
} else {
seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
}
if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
} else {
seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
}
} else { // the segments are on a vertical line
if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
} else {
seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
}
if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
} else {
seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
}
}
if ( seg1minVal <= seg2minVal ) {
if ( seg1maxVal < seg2minVal ) return [];
if ( seg1maxVal == seg2minVal ) {
if ( inExcludeAdjacentSegs ) return [];
return [ seg2min ];
}
if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
return [ seg2min, seg2max ];
} else {
if ( seg1minVal > seg2maxVal ) return [];
if ( seg1minVal == seg2maxVal ) {
if ( inExcludeAdjacentSegs ) return [];
return [ seg1min ];
}
if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
return [ seg1min, seg2max ];
}
}
}
function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
// The order of legs is important
var EPSILON = 0.0000000001;
// translation of all points, so that Vertex is at (0,0)
var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
// main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
// console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
if ( from2toAngle > 0 ) { // main angle < 180 deg.
return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
} else { // main angle > 180 deg.
return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
}
} else { // angle == 180 deg.
// console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
return ( from2otherAngle > 0 );
}
}
function removeHoles( contour, holes ) {
var shape = contour.concat(); // work on this shape
var hole;
function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
// Check if hole point lies within angle around shape point
var lastShapeIdx = shape.length - 1;
var prevShapeIdx = inShapeIdx - 1;
if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
var nextShapeIdx = inShapeIdx + 1;
if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
if (! insideAngle ) {
// console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
return false;
}
// Check if shape point lies within angle around hole point
var lastHoleIdx = hole.length - 1;
var prevHoleIdx = inHoleIdx - 1;
if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
var nextHoleIdx = inHoleIdx + 1;
if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
if (! insideAngle ) {
// console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
return false;
}
return true;
}
function intersectsShapeEdge( inShapePt, inHolePt ) {
// checks for intersections with shape edges
var sIdx, nextIdx, intersection;
for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
nextIdx = sIdx+1; nextIdx %= shape.length;
intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
if ( intersection.length > 0 ) return true;
}
return false;
}
var indepHoles = [];
function intersectsHoleEdge( inShapePt, inHolePt ) {
// checks for intersections with hole edges
var ihIdx, chkHole,
hIdx, nextIdx, intersection;
for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
chkHole = holes[indepHoles[ihIdx]];
for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
nextIdx = hIdx+1; nextIdx %= chkHole.length;
intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
if ( intersection.length > 0 ) return true;
}
}
return false;
}
var holeIndex, shapeIndex,
shapePt, holePt,
holeIdx, cutKey, failedCuts = [],
tmpShape1, tmpShape2,
tmpHole1, tmpHole2;
for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
indepHoles.push( h );
}
var counter = indepHoles.length * 2;
while ( indepHoles.length > 0 ) {
counter --;
if ( counter < 0 ) {
console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
break;
}
// search for shape-vertex and hole-vertex,
// which can be connected without intersections
for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
shapePt = shape[ shapeIndex ];
holeIndex = -1;
// search for hole which can be reached without intersections
for ( var h = 0; h < indepHoles.length; h ++ ) {
holeIdx = indepHoles[h];
// prevent multiple checks
cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
if ( failedCuts[cutKey] !== undefined ) continue;
hole = holes[holeIdx];
for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
holePt = hole[ h2 ];
if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
holeIndex = h2;
indepHoles.splice(h,1);
tmpShape1 = shape.slice( 0, shapeIndex+1 );
tmpShape2 = shape.slice( shapeIndex );
tmpHole1 = hole.slice( holeIndex );
tmpHole2 = hole.slice( 0, holeIndex+1 );
shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
// Debug only, to show the selected cuts
// glob_CutLines.push( [ shapePt, holePt ] );
break;
}
if ( holeIndex >= 0 ) break; // hole-vertex found
failedCuts[cutKey] = true; // remember failure
}
if ( holeIndex >= 0 ) break; // hole-vertex found
}
}
return shape; /* shape with no holes */
}
var i, il, f, face,
key, index,
allPointsMap = {};
// To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
var allpoints = contour.concat();
for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
Array.prototype.push.apply( allpoints, holes[h] );
}
//console.log( "allpoints",allpoints, allpoints.length );
// prepare all points map
for ( i = 0, il = allpoints.length; i < il; i ++ ) {
key = allpoints[ i ].x + ":" + allpoints[ i ].y;
if ( allPointsMap[ key ] !== undefined ) {
console.log( "Duplicate point", key );
}
allPointsMap[ key ] = i;
}
// remove holes by cutting paths to holes and adding them to the shape
var shapeWithoutHoles = removeHoles( contour, holes );
var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
//console.log( "triangles",triangles, triangles.length );
// check all face vertices against all points map
for ( i = 0, il = triangles.length; i < il; i ++ ) {
face = triangles[ i ];
for ( f = 0; f < 3; f ++ ) {
key = face[ f ].x + ":" + face[ f ].y;
index = allPointsMap[ key ];
if ( index !== undefined ) {
face[ f ] = index;
}
}
}
return triangles.concat();
},
isClockWise: function ( pts ) {
return THREE.FontUtils.Triangulate.area( pts ) < 0;
},
// Bezier Curves formulas obtained from
// http://en.wikipedia.org/wiki/B%C3%A9zier_curve
// Quad Bezier Functions
b2p0: function ( t, p ) {
var k = 1 - t;
return k * k * p;
},
b2p1: function ( t, p ) {
return 2 * ( 1 - t ) * t * p;
},
b2p2: function ( t, p ) {
return t * t * p;
},
b2: function ( t, p0, p1, p2 ) {
return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
},
// Cubic Bezier Functions
b3p0: function ( t, p ) {
var k = 1 - t;
return k * k * k * p;
},
b3p1: function ( t, p ) {
var k = 1 - t;
return 3 * k * k * t * p;
},
b3p2: function ( t, p ) {
var k = 1 - t;
return 3 * k * t * t * p;
},
b3p3: function ( t, p ) {
return t * t * t * p;
},
b3: function ( t, p0, p1, p2, p3 ) {
return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
}
};
/**************************************************************
* Line
**************************************************************/
THREE.LineCurve = function ( v1, v2 ) {
this.v1 = v1;
this.v2 = v2;
};
THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.LineCurve.prototype.getPoint = function ( t ) {
var point = this.v2.clone().sub(this.v1);
point.multiplyScalar( t ).add( this.v1 );
return point;
};
// Line curve is linear, so we can overwrite default getPointAt
THREE.LineCurve.prototype.getPointAt = function ( u ) {
return this.getPoint( u );
};
THREE.LineCurve.prototype.getTangent = function( t ) {
var tangent = this.v2.clone().sub(this.v1);
return tangent.normalize();
};
/**************************************************************
* Quadratic Bezier curve
**************************************************************/
THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
};
THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
var tx, ty;
tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
return new THREE.Vector2( tx, ty );
};
THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
var tx, ty;
tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
// returns unit vector
var tangent = new THREE.Vector2( tx, ty );
tangent.normalize();
return tangent;
};
/**************************************************************
* Cubic Bezier curve
**************************************************************/
THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
};
THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
var tx, ty;
tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
return new THREE.Vector2( tx, ty );
};
THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
var tx, ty;
tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
var tangent = new THREE.Vector2( tx, ty );
tangent.normalize();
return tangent;
};
/**************************************************************
* Spline curve
**************************************************************/
THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
this.points = (points == undefined) ? [] : points;
};
THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.SplineCurve.prototype.getPoint = function ( t ) {
var v = new THREE.Vector2();
var c = [];
var points = this.points, point, intPoint, weight;
point = ( points.length - 1 ) * t;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
return v;
};
/**************************************************************
* Ellipse curve
**************************************************************/
THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
this.aX = aX;
this.aY = aY;
this.xRadius = xRadius;
this.yRadius = yRadius;
this.aStartAngle = aStartAngle;
this.aEndAngle = aEndAngle;
this.aClockwise = aClockwise;
};
THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
THREE.EllipseCurve.prototype.getPoint = function ( t ) {
var angle;
var deltaAngle = this.aEndAngle - this.aStartAngle;
if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
if ( this.aClockwise === true ) {
angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
} else {
angle = this.aStartAngle + t * deltaAngle;
}
var tx = this.aX + this.xRadius * Math.cos( angle );
var ty = this.aY + this.yRadius * Math.sin( angle );
return new THREE.Vector2( tx, ty );
};
/**************************************************************
* Arc curve
**************************************************************/
THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
};
THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
/**************************************************************
* Line3D
**************************************************************/
THREE.LineCurve3 = THREE.Curve.create(
function ( v1, v2 ) {
this.v1 = v1;
this.v2 = v2;
},
function ( t ) {
var r = new THREE.Vector3();
r.subVectors( this.v2, this.v1 ); // diff
r.multiplyScalar( t );
r.add( this.v1 );
return r;
}
);
/**************************************************************
* Quadratic Bezier 3D curve
**************************************************************/
THREE.QuadraticBezierCurve3 = THREE.Curve.create(
function ( v0, v1, v2 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
},
function ( t ) {
var tx, ty, tz;
tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
return new THREE.Vector3( tx, ty, tz );
}
);
/**************************************************************
* Cubic Bezier 3D curve
**************************************************************/
THREE.CubicBezierCurve3 = THREE.Curve.create(
function ( v0, v1, v2, v3 ) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
},
function ( t ) {
var tx, ty, tz;
tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
return new THREE.Vector3( tx, ty, tz );
}
);
/**************************************************************
* Spline 3D curve
**************************************************************/
THREE.SplineCurve3 = THREE.Curve.create(
function ( points /* array of Vector3 */) {
this.points = (points == undefined) ? [] : points;
},
function ( t ) {
var v = new THREE.Vector3();
var c = [];
var points = this.points, point, intPoint, weight;
point = ( points.length - 1 ) * t;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
var pt0 = points[ c[0] ],
pt1 = points[ c[1] ],
pt2 = points[ c[2] ],
pt3 = points[ c[3] ];
v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
return v;
}
);
// THREE.SplineCurve3.prototype.getTangent = function(t) {
// var v = new THREE.Vector3();
// var c = [];
// var points = this.points, point, intPoint, weight;
// point = ( points.length - 1 ) * t;
// intPoint = Math.floor( point );
// weight = point - intPoint;
// c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
// c[ 1 ] = intPoint;
// c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
// c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
// var pt0 = points[ c[0] ],
// pt1 = points[ c[1] ],
// pt2 = points[ c[2] ],
// pt3 = points[ c[3] ];
// // t = weight;
// v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
// v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
// v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
// return v;
// }
/**************************************************************
* Closed Spline 3D curve
**************************************************************/
THREE.ClosedSplineCurve3 = THREE.Curve.create(
function ( points /* array of Vector3 */) {
this.points = (points == undefined) ? [] : points;
},
function ( t ) {
var v = new THREE.Vector3();
var c = [];
var points = this.points, point, intPoint, weight;
point = ( points.length - 0 ) * t;
// This needs to be from 0-length +1
intPoint = Math.floor( point );
weight = point - intPoint;
intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
c[ 0 ] = ( intPoint - 1 ) % points.length;
c[ 1 ] = ( intPoint ) % points.length;
c[ 2 ] = ( intPoint + 1 ) % points.length;
c[ 3 ] = ( intPoint + 2 ) % points.length;
v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
return v;
}
);
/**
* @author mikael emtinger / http://gomo.se/
*/
THREE.AnimationHandler = (function() {
var playing = [];
var library = {};
var that = {};
//--- update ---
that.update = function( deltaTimeMS ) {
for( var i = 0; i < playing.length; i ++ )
playing[ i ].update( deltaTimeMS );
};
//--- add ---
that.addToUpdate = function( animation ) {
if ( playing.indexOf( animation ) === -1 )
playing.push( animation );
};
//--- remove ---
that.removeFromUpdate = function( animation ) {
var index = playing.indexOf( animation );
if( index !== -1 )
playing.splice( index, 1 );
};
//--- add ---
that.add = function( data ) {
if ( library[ data.name ] !== undefined )
console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
library[ data.name ] = data;
initData( data );
};
//--- get ---
that.get = function( name ) {
if ( typeof name === "string" ) {
if ( library[ name ] ) {
return library[ name ];
} else {
console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
return null;
}
} else {
// todo: add simple tween library
}
};
//--- parse ---
that.parse = function( root ) {
// setup hierarchy
var hierarchy = [];
if ( root instanceof THREE.SkinnedMesh ) {
for( var b = 0; b < root.bones.length; b++ ) {
hierarchy.push( root.bones[ b ] );
}
} else {
parseRecurseHierarchy( root, hierarchy );
}
return hierarchy;
};
var parseRecurseHierarchy = function( root, hierarchy ) {
hierarchy.push( root );
for( var c = 0; c < root.children.length; c++ )
parseRecurseHierarchy( root.children[ c ], hierarchy );
}
//--- init data ---
var initData = function( data ) {
if( data.initialized === true )
return;
// loop through all keys
for( var h = 0; h < data.hierarchy.length; h ++ ) {
for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
// remove minus times
if( data.hierarchy[ h ].keys[ k ].time < 0 )
data.hierarchy[ h ].keys[ k ].time = 0;
// create quaternions
if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
!( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
var quat = data.hierarchy[ h ].keys[ k ].rot;
data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
}
}
// prepare morph target keys
if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
// get all used
var usedMorphTargets = {};
for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
usedMorphTargets[ morphTargetName ] = -1;
}
}
data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
// set all used on all frames
for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
var influences = {};
for ( var morphTargetName in usedMorphTargets ) {
for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
break;
}
}
if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
influences[ morphTargetName ] = 0;
}
}
data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
}
}
// remove all keys that are on the same time
for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
data.hierarchy[ h ].keys.splice( k, 1 );
k --;
}
}
// set index
for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
data.hierarchy[ h ].keys[ k ].index = k;
}
}
// done
data.initialized = true;
};
// interpolation types
that.LINEAR = 0;
that.CATMULLROM = 1;
that.CATMULLROM_FORWARD = 2;
return that;
}());
/**
* @author mikael emtinger / http://gomo.se/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Animation = function ( root, name ) {
this.root = root;
this.data = THREE.AnimationHandler.get( name );
this.hierarchy = THREE.AnimationHandler.parse( root );
this.currentTime = 0;
this.timeScale = 1;
this.isPlaying = false;
this.isPaused = true;
this.loop = true;
this.interpolationType = THREE.AnimationHandler.LINEAR;
};
THREE.Animation.prototype.play = function ( startTime ) {
this.currentTime = startTime !== undefined ? startTime : 0;
if ( this.isPlaying === false ) {
this.isPlaying = true;
this.reset();
this.update( 0 );
}
this.isPaused = false;
THREE.AnimationHandler.addToUpdate( this );
};
THREE.Animation.prototype.pause = function() {
if ( this.isPaused === true ) {
THREE.AnimationHandler.addToUpdate( this );
} else {
THREE.AnimationHandler.removeFromUpdate( this );
}
this.isPaused = !this.isPaused;
};
THREE.Animation.prototype.stop = function() {
this.isPlaying = false;
this.isPaused = false;
THREE.AnimationHandler.removeFromUpdate( this );
};
THREE.Animation.prototype.reset = function () {
for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
var object = this.hierarchy[ h ];
object.matrixAutoUpdate = true;
if ( object.animationCache === undefined ) {
object.animationCache = {};
object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
}
var prevKey = object.animationCache.prevKey;
var nextKey = object.animationCache.nextKey;
prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
}
};
THREE.Animation.prototype.update = (function(){
var points = [];
var target = new THREE.Vector3();
// Catmull-Rom spline
var interpolateCatmullRom = function ( points, scale ) {
var c = [], v3 = [],
point, intPoint, weight, w2, w3,
pa, pb, pc, pd;
point = ( points.length - 1 ) * scale;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
pa = points[ c[ 0 ] ];
pb = points[ c[ 1 ] ];
pc = points[ c[ 2 ] ];
pd = points[ c[ 3 ] ];
w2 = weight * weight;
w3 = weight * w2;
v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
return v3;
};
var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
var v0 = ( p2 - p0 ) * 0.5,
v1 = ( p3 - p1 ) * 0.5;
return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
};
return function ( delta ) {
if ( this.isPlaying === false ) return;
this.currentTime += delta * this.timeScale;
//
var vector;
var types = [ "pos", "rot", "scl" ];
var duration = this.data.length;
if ( this.loop === true && this.currentTime > duration ) {
this.currentTime %= duration;
this.reset();
} else if ( this.loop === false && this.currentTime > duration ) {
this.stop();
return;
}
this.currentTime = Math.min( this.currentTime, duration );
for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
var object = this.hierarchy[ h ];
var animationCache = object.animationCache;
// loop through pos/rot/scl
for ( var t = 0; t < 3; t ++ ) {
// get keys
var type = types[ t ];
var prevKey = animationCache.prevKey[ type ];
var nextKey = animationCache.nextKey[ type ];
if ( nextKey.time <= this.currentTime ) {
prevKey = this.data.hierarchy[ h ].keys[ 0 ];
nextKey = this.getNextKeyWith( type, h, 1 );
while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
prevKey = nextKey;
nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
}
animationCache.prevKey[ type ] = prevKey;
animationCache.nextKey[ type ] = nextKey;
}
object.matrixAutoUpdate = true;
object.matrixWorldNeedsUpdate = true;
var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
var prevXYZ = prevKey[ type ];
var nextXYZ = nextKey[ type ];
if ( scale < 0 ) scale = 0;
if ( scale > 1 ) scale = 1;
// interpolate
if ( type === "pos" ) {
vector = object.position;
if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
} else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
points[ 1 ] = prevXYZ;
points[ 2 ] = nextXYZ;
points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
scale = scale * 0.33 + 0.33;
var currentPoint = interpolateCatmullRom( points, scale );
vector.x = currentPoint[ 0 ];
vector.y = currentPoint[ 1 ];
vector.z = currentPoint[ 2 ];
if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
target.sub( vector );
target.y = 0;
target.normalize();
var angle = Math.atan2( target.x, target.z );
object.rotation.set( 0, angle, 0 );
}
}
} else if ( type === "rot" ) {
THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
} else if ( type === "scl" ) {
vector = object.scale;
vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
}
}
}
};
})();
// Get next key with
THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
key = key < keys.length - 1 ? key : keys.length - 1;
} else {
key = key % keys.length;
}
for ( ; key < keys.length; key++ ) {
if ( keys[ key ][ type ] !== undefined ) {
return keys[ key ];
}
}
return this.data.hierarchy[ h ].keys[ 0 ];
};
// Get previous key with
THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
key = key > 0 ? key : 0;
} else {
key = key >= 0 ? key : key + keys.length;
}
for ( ; key >= 0; key -- ) {
if ( keys[ key ][ type ] !== undefined ) {
return keys[ key ];
}
}
return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
};
/**
* @author mikael emtinger / http://gomo.se/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author khang duong
* @author erik kitson
*/
THREE.KeyFrameAnimation = function ( root, data ) {
this.root = root;
this.data = THREE.AnimationHandler.get( data );
this.hierarchy = THREE.AnimationHandler.parse( root );
this.currentTime = 0;
this.timeScale = 0.001;
this.isPlaying = false;
this.isPaused = true;
this.loop = true;
// initialize to first keyframes
for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
var keys = this.data.hierarchy[h].keys,
sids = this.data.hierarchy[h].sids,
obj = this.hierarchy[h];
if ( keys.length && sids ) {
for ( var s = 0; s < sids.length; s++ ) {
var sid = sids[ s ],
next = this.getNextKeyWith( sid, h, 0 );
if ( next ) {
next.apply( sid );
}
}
obj.matrixAutoUpdate = false;
this.data.hierarchy[h].node.updateMatrix();
obj.matrixWorldNeedsUpdate = true;
}
}
};
// Play
THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
this.currentTime = startTime !== undefined ? startTime : 0;
if ( this.isPlaying === false ) {
this.isPlaying = true;
// reset key cache
var h, hl = this.hierarchy.length,
object,
node;
for ( h = 0; h < hl; h++ ) {
object = this.hierarchy[ h ];
node = this.data.hierarchy[ h ];
if ( node.animationCache === undefined ) {
node.animationCache = {};
node.animationCache.prevKey = null;
node.animationCache.nextKey = null;
node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
}
var keys = this.data.hierarchy[h].keys;
if (keys.length) {
node.animationCache.prevKey = keys[ 0 ];
node.animationCache.nextKey = keys[ 1 ];
this.startTime = Math.min( keys[0].time, this.startTime );
this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
}
}
this.update( 0 );
}
this.isPaused = false;
THREE.AnimationHandler.addToUpdate( this );
};
// Pause
THREE.KeyFrameAnimation.prototype.pause = function() {
if( this.isPaused ) {
THREE.AnimationHandler.addToUpdate( this );
} else {
THREE.AnimationHandler.removeFromUpdate( this );
}
this.isPaused = !this.isPaused;
};
// Stop
THREE.KeyFrameAnimation.prototype.stop = function() {
this.isPlaying = false;
this.isPaused = false;
THREE.AnimationHandler.removeFromUpdate( this );
// reset JIT matrix and remove cache
for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
var obj = this.hierarchy[ h ];
var node = this.data.hierarchy[ h ];
if ( node.animationCache !== undefined ) {
var original = node.animationCache.originalMatrix;
if( obj instanceof THREE.Bone ) {
original.copy( obj.skinMatrix );
obj.skinMatrix = original;
} else {
original.copy( obj.matrix );
obj.matrix = original;
}
delete node.animationCache;
}
}
};
// Update
THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
if ( this.isPlaying === false ) return;
this.currentTime += delta * this.timeScale;
//
var duration = this.data.length;
if ( this.loop === true && this.currentTime > duration ) {
this.currentTime %= duration;
}
this.currentTime = Math.min( this.currentTime, duration );
for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
var object = this.hierarchy[ h ];
var node = this.data.hierarchy[ h ];
var keys = node.keys,
animationCache = node.animationCache;
if ( keys.length ) {
var prevKey = animationCache.prevKey;
var nextKey = animationCache.nextKey;
if ( nextKey.time <= this.currentTime ) {
while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
prevKey = nextKey;
nextKey = keys[ prevKey.index + 1 ];
}
animationCache.prevKey = prevKey;
animationCache.nextKey = nextKey;
}
if ( nextKey.time >= this.currentTime ) {
prevKey.interpolate( nextKey, this.currentTime );
} else {
prevKey.interpolate( nextKey, nextKey.time );
}
this.data.hierarchy[ h ].node.updateMatrix();
object.matrixWorldNeedsUpdate = true;
}
}
};
// Get next key with
THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
key = key % keys.length;
for ( ; key < keys.length; key++ ) {
if ( keys[ key ].hasTarget( sid ) ) {
return keys[ key ];
}
}
return keys[ 0 ];
};
// Get previous key with
THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
var keys = this.data.hierarchy[ h ].keys;
key = key >= 0 ? key : key + keys.length;
for ( ; key >= 0; key-- ) {
if ( keys[ key ].hasTarget( sid ) ) {
return keys[ key ];
}
}
return keys[ keys.length - 1 ];
};
/**
* @author mrdoob / http://mrdoob.com
*/
THREE.MorphAnimation = function ( mesh ) {
this.mesh = mesh;
this.frames = mesh.morphTargetInfluences.length;
this.currentTime = 0;
this.duration = 1000;
this.loop = true;
this.isPlaying = false;
};
THREE.MorphAnimation.prototype = {
play: function () {
this.isPlaying = true;
},
pause: function () {
this.isPlaying = false;
},
update: ( function () {
var lastFrame = 0;
var currentFrame = 0;
return function ( delta ) {
if ( this.isPlaying === false ) return;
this.currentTime += delta;
if ( this.loop === true && this.currentTime > this.duration ) {
this.currentTime %= this.duration;
}
this.currentTime = Math.min( this.currentTime, this.duration );
var interpolation = this.duration / this.frames;
var frame = Math.floor( this.currentTime / interpolation );
if ( frame != currentFrame ) {
this.mesh.morphTargetInfluences[ lastFrame ] = 0;
this.mesh.morphTargetInfluences[ currentFrame ] = 1;
this.mesh.morphTargetInfluences[ frame ] = 0;
lastFrame = currentFrame;
currentFrame = frame;
}
this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
}
} )()
};
/**
* Camera for rendering cube maps
* - renders scene into axis-aligned cube
*
* @author alteredq / http://alteredqualia.com/
*/
THREE.CubeCamera = function ( near, far, cubeResolution ) {
THREE.Object3D.call( this );
var fov = 90, aspect = 1;
var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraPX.up.set( 0, -1, 0 );
cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
this.add( cameraPX );
var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraNX.up.set( 0, -1, 0 );
cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
this.add( cameraNX );
var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraPY.up.set( 0, 0, 1 );
cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
this.add( cameraPY );
var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraNY.up.set( 0, 0, -1 );
cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
this.add( cameraNY );
var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraPZ.up.set( 0, -1, 0 );
cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
this.add( cameraPZ );
var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
cameraNZ.up.set( 0, -1, 0 );
cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
this.add( cameraNZ );
this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
this.updateCubeMap = function ( renderer, scene ) {
var renderTarget = this.renderTarget;
var generateMipmaps = renderTarget.generateMipmaps;
renderTarget.generateMipmaps = false;
renderTarget.activeCubeFace = 0;
renderer.render( scene, cameraPX, renderTarget );
renderTarget.activeCubeFace = 1;
renderer.render( scene, cameraNX, renderTarget );
renderTarget.activeCubeFace = 2;
renderer.render( scene, cameraPY, renderTarget );
renderTarget.activeCubeFace = 3;
renderer.render( scene, cameraNY, renderTarget );
renderTarget.activeCubeFace = 4;
renderer.render( scene, cameraPZ, renderTarget );
renderTarget.generateMipmaps = generateMipmaps;
renderTarget.activeCubeFace = 5;
renderer.render( scene, cameraNZ, renderTarget );
};
};
THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
/**
* @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
*
* A general perpose camera, for setting FOV, Lens Focal Length,
* and switching between perspective and orthographic views easily.
* Use this only if you do not wish to manage
* both a Orthographic and Perspective Camera
*
*/
THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
THREE.Camera.call( this );
this.fov = fov;
this.left = -width / 2;
this.right = width / 2
this.top = height / 2;
this.bottom = -height / 2;
// We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
this.zoom = 1;
this.toPerspective();
var aspect = width/height;
};
THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
THREE.CombinedCamera.prototype.toPerspective = function () {
// Switches to the Perspective Camera
this.near = this.cameraP.near;
this.far = this.cameraP.far;
this.cameraP.fov = this.fov / this.zoom ;
this.cameraP.updateProjectionMatrix();
this.projectionMatrix = this.cameraP.projectionMatrix;
this.inPerspectiveMode = true;
this.inOrthographicMode = false;
};
THREE.CombinedCamera.prototype.toOrthographic = function () {
// Switches to the Orthographic camera estimating viewport from Perspective
var fov = this.fov;
var aspect = this.cameraP.aspect;
var near = this.cameraP.near;
var far = this.cameraP.far;
// The size that we set is the mid plane of the viewing frustum
var hyperfocus = ( near + far ) / 2;
var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
var planeHeight = 2 * halfHeight;
var planeWidth = planeHeight * aspect;
var halfWidth = planeWidth / 2;
halfHeight /= this.zoom;
halfWidth /= this.zoom;
this.cameraO.left = -halfWidth;
this.cameraO.right = halfWidth;
this.cameraO.top = halfHeight;
this.cameraO.bottom = -halfHeight;
// this.cameraO.left = -farHalfWidth;
// this.cameraO.right = farHalfWidth;
// this.cameraO.top = farHalfHeight;
// this.cameraO.bottom = -farHalfHeight;
// this.cameraO.left = this.left / this.zoom;
// this.cameraO.right = this.right / this.zoom;
// this.cameraO.top = this.top / this.zoom;
// this.cameraO.bottom = this.bottom / this.zoom;
this.cameraO.updateProjectionMatrix();
this.near = this.cameraO.near;
this.far = this.cameraO.far;
this.projectionMatrix = this.cameraO.projectionMatrix;
this.inPerspectiveMode = false;
this.inOrthographicMode = true;
};
THREE.CombinedCamera.prototype.setSize = function( width, height ) {
this.cameraP.aspect = width / height;
this.left = -width / 2;
this.right = width / 2
this.top = height / 2;
this.bottom = -height / 2;
};
THREE.CombinedCamera.prototype.setFov = function( fov ) {
this.fov = fov;
if ( this.inPerspectiveMode ) {
this.toPerspective();
} else {
this.toOrthographic();
}
};
// For mantaining similar API with PerspectiveCamera
THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
if ( this.inPerspectiveMode ) {
this.toPerspective();
} else {
this.toPerspective();
this.toOrthographic();
}
};
/*
* Uses Focal Length (in mm) to estimate and set FOV
* 35mm (fullframe) camera is used if frame size is not specified;
* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
*/
THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
if ( frameHeight === undefined ) frameHeight = 24;
var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
this.setFov( fov );
return fov;
};
THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
this.zoom = zoom;
if ( this.inPerspectiveMode ) {
this.toPerspective();
} else {
this.toOrthographic();
}
};
THREE.CombinedCamera.prototype.toFrontView = function() {
this.rotation.x = 0;
this.rotation.y = 0;
this.rotation.z = 0;
// should we be modifing the matrix instead?
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toBackView = function() {
this.rotation.x = 0;
this.rotation.y = Math.PI;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toLeftView = function() {
this.rotation.x = 0;
this.rotation.y = - Math.PI / 2;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toRightView = function() {
this.rotation.x = 0;
this.rotation.y = Math.PI / 2;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toTopView = function() {
this.rotation.x = - Math.PI / 2;
this.rotation.y = 0;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
THREE.CombinedCamera.prototype.toBottomView = function() {
this.rotation.x = Math.PI / 2;
this.rotation.y = 0;
this.rotation.z = 0;
this.rotationAutoUpdate = false;
};
/**
* @author mrdoob / http://mrdoob.com/
* based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
*/
THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
THREE.Geometry.call( this );
var scope = this;
this.width = width;
this.height = height;
this.depth = depth;
this.widthSegments = widthSegments || 1;
this.heightSegments = heightSegments || 1;
this.depthSegments = depthSegments || 1;
var width_half = this.width / 2;
var height_half = this.height / 2;
var depth_half = this.depth / 2;
buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
var w, ix, iy,
gridX = scope.widthSegments,
gridY = scope.heightSegments,
width_half = width / 2,
height_half = height / 2,
offset = scope.vertices.length;
if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
w = 'z';
} else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
w = 'y';
gridY = scope.depthSegments;
} else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
w = 'x';
gridX = scope.depthSegments;
}
var gridX1 = gridX + 1,
gridY1 = gridY + 1,
segment_width = width / gridX,
segment_height = height / gridY,
normal = new THREE.Vector3();
normal[ w ] = depth > 0 ? 1 : - 1;
for ( iy = 0; iy < gridY1; iy ++ ) {
for ( ix = 0; ix < gridX1; ix ++ ) {
var vector = new THREE.Vector3();
vector[ u ] = ( ix * segment_width - width_half ) * udir;
vector[ v ] = ( iy * segment_height - height_half ) * vdir;
vector[ w ] = depth;
scope.vertices.push( vector );
}
}
for ( iy = 0; iy < gridY; iy++ ) {
for ( ix = 0; ix < gridX; ix++ ) {
var a = ix + gridX1 * iy;
var b = ix + gridX1 * ( iy + 1 );
var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
var d = ( ix + 1 ) + gridX1 * iy;
var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
var face = new THREE.Face3( a + offset, b + offset, d + offset );
face.normal.copy( normal );
face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
face.materialIndex = materialIndex;
scope.faces.push( face );
scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
face = new THREE.Face3( b + offset, c + offset, d + offset );
face.normal.copy( normal );
face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
face.materialIndex = materialIndex;
scope.faces.push( face );
scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
}
}
}
this.computeCentroids();
this.mergeVertices();
};
THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author hughes
*/
THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
THREE.Geometry.call( this );
this.radius = radius = radius || 50;
this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
var i, uvs = [],
center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
this.vertices.push(center);
uvs.push( centerUV );
for ( i = 0; i <= segments; i ++ ) {
var vertex = new THREE.Vector3();
var segment = thetaStart + i / segments * thetaLength;
vertex.x = radius * Math.cos( segment );
vertex.y = radius * Math.sin( segment );
this.vertices.push( vertex );
uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
}
var n = new THREE.Vector3( 0, 0, 1 );
for ( i = 1; i <= segments; i ++ ) {
var v1 = i;
var v2 = i + 1 ;
var v3 = 0;
this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
}
this.computeCentroids();
this.computeFaceNormals();
this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
};
THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
// DEPRECATED
THREE.CubeGeometry = THREE.BoxGeometry;
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
THREE.Geometry.call( this );
this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
this.height = height = height !== undefined ? height : 100;
this.radialSegments = radialSegments = radialSegments || 8;
this.heightSegments = heightSegments = heightSegments || 1;
this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
var heightHalf = height / 2;
var x, y, vertices = [], uvs = [];
for ( y = 0; y <= heightSegments; y ++ ) {
var verticesRow = [];
var uvsRow = [];
var v = y / heightSegments;
var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
for ( x = 0; x <= radialSegments; x ++ ) {
var u = x / radialSegments;
var vertex = new THREE.Vector3();
vertex.x = radius * Math.sin( u * Math.PI * 2 );
vertex.y = - v * height + heightHalf;
vertex.z = radius * Math.cos( u * Math.PI * 2 );
this.vertices.push( vertex );
verticesRow.push( this.vertices.length - 1 );
uvsRow.push( new THREE.Vector2( u, 1 - v ) );
}
vertices.push( verticesRow );
uvs.push( uvsRow );
}
var tanTheta = ( radiusBottom - radiusTop ) / height;
var na, nb;
for ( x = 0; x < radialSegments; x ++ ) {
if ( radiusTop !== 0 ) {
na = this.vertices[ vertices[ 0 ][ x ] ].clone();
nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
} else {
na = this.vertices[ vertices[ 1 ][ x ] ].clone();
nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
}
na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
for ( y = 0; y < heightSegments; y ++ ) {
var v1 = vertices[ y ][ x ];
var v2 = vertices[ y + 1 ][ x ];
var v3 = vertices[ y + 1 ][ x + 1 ];
var v4 = vertices[ y ][ x + 1 ];
var n1 = na.clone();
var n2 = na.clone();
var n3 = nb.clone();
var n4 = nb.clone();
var uv1 = uvs[ y ][ x ].clone();
var uv2 = uvs[ y + 1 ][ x ].clone();
var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
var uv4 = uvs[ y ][ x + 1 ].clone();
this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
}
}
// top cap
if ( openEnded === false && radiusTop > 0 ) {
this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
for ( x = 0; x < radialSegments; x ++ ) {
var v1 = vertices[ 0 ][ x ];
var v2 = vertices[ 0 ][ x + 1 ];
var v3 = this.vertices.length - 1;
var n1 = new THREE.Vector3( 0, 1, 0 );
var n2 = new THREE.Vector3( 0, 1, 0 );
var n3 = new THREE.Vector3( 0, 1, 0 );
var uv1 = uvs[ 0 ][ x ].clone();
var uv2 = uvs[ 0 ][ x + 1 ].clone();
var uv3 = new THREE.Vector2( uv2.x, 0 );
this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
}
}
// bottom cap
if ( openEnded === false && radiusBottom > 0 ) {
this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
for ( x = 0; x < radialSegments; x ++ ) {
var v1 = vertices[ y ][ x + 1 ];
var v2 = vertices[ y ][ x ];
var v3 = this.vertices.length - 1;
var n1 = new THREE.Vector3( 0, - 1, 0 );
var n2 = new THREE.Vector3( 0, - 1, 0 );
var n3 = new THREE.Vector3( 0, - 1, 0 );
var uv1 = uvs[ y ][ x + 1 ].clone();
var uv2 = uvs[ y ][ x ].clone();
var uv3 = new THREE.Vector2( uv2.x, 1 );
this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
}
THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*
* Creates extruded geometry from a path shape.
*
* parameters = {
*
* curveSegments: <int>, // number of points on the curves
* steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
* amount: <int>, // Depth to extrude the shape
*
* bevelEnabled: <bool>, // turn on bevel
* bevelThickness: <float>, // how deep into the original shape bevel goes
* bevelSize: <float>, // how far from shape outline is bevel
* bevelSegments: <int>, // number of bevel layers
*
* extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
* frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
*
* material: <int> // material index for front and back faces
* extrudeMaterial: <int> // material index for extrusion and beveled faces
* uvGenerator: <Object> // object that provides UV generator functions
*
* }
**/
THREE.ExtrudeGeometry = function ( shapes, options ) {
if ( typeof( shapes ) === "undefined" ) {
shapes = [];
return;
}
THREE.Geometry.call( this );
shapes = shapes instanceof Array ? shapes : [ shapes ];
this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
this.addShapeList( shapes, options );
this.computeCentroids();
this.computeFaceNormals();
// can't really use automatic vertex normals
// as then front and back sides get smoothed too
// should do separate smoothing just for sides
//this.computeVertexNormals();
//console.log( "took", ( Date.now() - startTime ) );
};
THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
var sl = shapes.length;
for ( var s = 0; s < sl; s ++ ) {
var shape = shapes[ s ];
this.addShape( shape, options );
}
};
THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
var amount = options.amount !== undefined ? options.amount : 100;
var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
var steps = options.steps !== undefined ? options.steps : 1;
var extrudePath = options.extrudePath;
var extrudePts, extrudeByPath = false;
var material = options.material;
var extrudeMaterial = options.extrudeMaterial;
// Use default WorldUVGenerator if no UV generators are specified.
var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
var shapebb = this.shapebb;
//shapebb = shape.getBoundingBox();
var splineTube, binormal, normal, position2;
if ( extrudePath ) {
extrudePts = extrudePath.getSpacedPoints( steps );
extrudeByPath = true;
bevelEnabled = false; // bevels not supported for path extrusion
// SETUP TNB variables
// Reuse TNB from TubeGeomtry for now.
// TODO1 - have a .isClosed in spline?
splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
// console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
binormal = new THREE.Vector3();
normal = new THREE.Vector3();
position2 = new THREE.Vector3();
}
// Safeguards if bevels are not enabled
if ( ! bevelEnabled ) {
bevelSegments = 0;
bevelThickness = 0;
bevelSize = 0;
}
// Variables initalization
var ahole, h, hl; // looping of holes
var scope = this;
var bevelPoints = [];
var shapesOffset = this.vertices.length;
var shapePoints = shape.extractPoints( curveSegments );
var vertices = shapePoints.shape;
var holes = shapePoints.holes;
var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
if ( reverse ) {
vertices = vertices.reverse();
// Maybe we should also check if holes are in the opposite direction, just to be safe ...
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
holes[ h ] = ahole.reverse();
}
}
reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
}
var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
/* Vertices */
var contour = vertices; // vertices has all points but contour has only points of circumference
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
vertices = vertices.concat( ahole );
}
function scalePt2 ( pt, vec, size ) {
if ( !vec ) console.log( "die" );
return vec.clone().multiplyScalar( size ).add( pt );
}
var b, bs, t, z,
vert, vlen = vertices.length,
face, flen = faces.length,
cont, clen = contour.length;
// Find directions for point movement
var RAD_TO_DEGREES = 180 / Math.PI;
function getBevelVec( inPt, inPrev, inNext ) {
var EPSILON = 0.0000000001;
var sign = THREE.Math.sign;
// computes for inPt the corresponding point inPt' on a new contour
// shiftet by 1 unit (length of normalized vector) to the left
// if we walk along contour clockwise, this new contour is outside the old one
//
// inPt' is the intersection of the two lines parallel to the two
// adjacent edges of inPt at a distance of 1 unit on the left side.
var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
// good reading for geometry algorithms (here: line-line intersection)
// http://geomalgorithms.com/a05-_intersect-1.html
var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
// check for colinear edges
var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
// length of vectors for normalizing
var v_prev_len = Math.sqrt( v_prev_lensq );
var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
// shift adjacent points by unit vectors to the left
var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
// scaling factor for v_prev to intersection point
var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
( v_prev_x * v_next_y - v_prev_y * v_next_x );
// vector from inPt to intersection point
v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
// Don't normalize!, otherwise sharp corners become ugly
// but prevent crazy spikes
var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
if ( v_trans_lensq <= 2 ) {
return new THREE.Vector2( v_trans_x, v_trans_y );
} else {
shrink_by = Math.sqrt( v_trans_lensq / 2 );
}
} else { // handle special case of colinear edges
var direction_eq = false; // assumes: opposite
if ( v_prev_x > EPSILON ) {
if ( v_next_x > EPSILON ) { direction_eq = true; }
} else {
if ( v_prev_x < -EPSILON ) {
if ( v_next_x < -EPSILON ) { direction_eq = true; }
} else {
if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
}
}
if ( direction_eq ) {
// console.log("Warning: lines are a straight sequence");
v_trans_x = -v_prev_y;
v_trans_y = v_prev_x;
shrink_by = Math.sqrt( v_prev_lensq );
} else {
// console.log("Warning: lines are a straight spike");
v_trans_x = v_prev_x;
v_trans_y = v_prev_y;
shrink_by = Math.sqrt( v_prev_lensq / 2 );
}
}
return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
}
var contourMovements = [];
for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
if ( j === il ) j = 0;
if ( k === il ) k = 0;
// (j)---(i)---(k)
// console.log('i,j,k', i, j , k)
var pt_i = contour[ i ];
var pt_j = contour[ j ];
var pt_k = contour[ k ];
contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
}
var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
oneHoleMovements = [];
for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
if ( j === il ) j = 0;
if ( k === il ) k = 0;
// (j)---(i)---(k)
oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
}
holesMovements.push( oneHoleMovements );
verticesMovements = verticesMovements.concat( oneHoleMovements );
}
// Loop bevelSegments, 1 for the front, 1 for the back
for ( b = 0; b < bevelSegments; b ++ ) {
//for ( b = bevelSegments; b > 0; b -- ) {
t = b / bevelSegments;
z = bevelThickness * ( 1 - t );
//z = bevelThickness * t;
bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
//bs = bevelSize * t ; // linear
// contract shape
for ( i = 0, il = contour.length; i < il; i ++ ) {
vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
//vert = scalePt( contour[ i ], contourCentroid, bs, false );
v( vert.x, vert.y, - z );
}
// expand holes
for ( h = 0, hl = holes.length; h < hl; h++ ) {
ahole = holes[ h ];
oneHoleMovements = holesMovements[ h ];
for ( i = 0, il = ahole.length; i < il; i++ ) {
vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
//vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
v( vert.x, vert.y, -z );
}
}
}
bs = bevelSize;
// Back facing vertices
for ( i = 0; i < vlen; i ++ ) {
vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
if ( !extrudeByPath ) {
v( vert.x, vert.y, 0 );
} else {
// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
position2.copy( extrudePts[0] ).add(normal).add(binormal);
v( position2.x, position2.y, position2.z );
}
}
// Add stepped vertices...
// Including front facing vertices
var s;
for ( s = 1; s <= steps; s ++ ) {
for ( i = 0; i < vlen; i ++ ) {
vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
if ( !extrudeByPath ) {
v( vert.x, vert.y, amount / steps * s );
} else {
// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
position2.copy( extrudePts[s] ).add( normal ).add( binormal );
v( position2.x, position2.y, position2.z );
}
}
}
// Add bevel segments planes
//for ( b = 1; b <= bevelSegments; b ++ ) {
for ( b = bevelSegments - 1; b >= 0; b -- ) {
t = b / bevelSegments;
z = bevelThickness * ( 1 - t );
//bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
// contract shape
for ( i = 0, il = contour.length; i < il; i ++ ) {
vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
v( vert.x, vert.y, amount + z );
}
// expand holes
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
oneHoleMovements = holesMovements[ h ];
for ( i = 0, il = ahole.length; i < il; i ++ ) {
vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
if ( !extrudeByPath ) {
v( vert.x, vert.y, amount + z );
} else {
v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
}
}
}
}
/* Faces */
// Top and bottom faces
buildLidFaces();
// Sides faces
buildSideFaces();
///// Internal functions
function buildLidFaces() {
if ( bevelEnabled ) {
var layer = 0 ; // steps + 1
var offset = vlen * layer;
// Bottom faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
}
layer = steps + bevelSegments * 2;
offset = vlen * layer;
// Top faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
}
} else {
// Bottom faces
for ( i = 0; i < flen; i++ ) {
face = faces[ i ];
f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
}
// Top faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
}
}
}
// Create faces for the z-sides of the shape
function buildSideFaces() {
var layeroffset = 0;
sidewalls( contour, layeroffset );
layeroffset += contour.length;
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
sidewalls( ahole, layeroffset );
//, true
layeroffset += ahole.length;
}
}
function sidewalls( contour, layeroffset ) {
var j, k;
i = contour.length;
while ( --i >= 0 ) {
j = i;
k = i - 1;
if ( k < 0 ) k = contour.length - 1;
//console.log('b', i,j, i-1, k,vertices.length);
var s = 0, sl = steps + bevelSegments * 2;
for ( s = 0; s < sl; s ++ ) {
var slen1 = vlen * s;
var slen2 = vlen * ( s + 1 );
var a = layeroffset + j + slen1,
b = layeroffset + k + slen1,
c = layeroffset + k + slen2,
d = layeroffset + j + slen2;
f4( a, b, c, d, contour, s, sl, j, k );
}
}
}
function v( x, y, z ) {
scope.vertices.push( new THREE.Vector3( x, y, z ) );
}
function f3( a, b, c, isBottom ) {
a += shapesOffset;
b += shapesOffset;
c += shapesOffset;
// normal, color, material
scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
scope.faceVertexUvs[ 0 ].push( uvs );
}
function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
a += shapesOffset;
b += shapesOffset;
c += shapesOffset;
d += shapesOffset;
scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
stepIndex, stepsLength, contourIndex1, contourIndex2 );
scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
}
};
THREE.ExtrudeGeometry.WorldUVGenerator = {
generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
var ax = geometry.vertices[ indexA ].x,
ay = geometry.vertices[ indexA ].y,
bx = geometry.vertices[ indexB ].x,
by = geometry.vertices[ indexB ].y,
cx = geometry.vertices[ indexC ].x,
cy = geometry.vertices[ indexC ].y;
return [
new THREE.Vector2( ax, ay ),
new THREE.Vector2( bx, by ),
new THREE.Vector2( cx, cy )
];
},
generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
},
generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
indexA, indexB, indexC, indexD, stepIndex, stepsLength,
contourIndex1, contourIndex2 ) {
var ax = geometry.vertices[ indexA ].x,
ay = geometry.vertices[ indexA ].y,
az = geometry.vertices[ indexA ].z,
bx = geometry.vertices[ indexB ].x,
by = geometry.vertices[ indexB ].y,
bz = geometry.vertices[ indexB ].z,
cx = geometry.vertices[ indexC ].x,
cy = geometry.vertices[ indexC ].y,
cz = geometry.vertices[ indexC ].z,
dx = geometry.vertices[ indexD ].x,
dy = geometry.vertices[ indexD ].y,
dz = geometry.vertices[ indexD ].z;
if ( Math.abs( ay - by ) < 0.01 ) {
return [
new THREE.Vector2( ax, 1 - az ),
new THREE.Vector2( bx, 1 - bz ),
new THREE.Vector2( cx, 1 - cz ),
new THREE.Vector2( dx, 1 - dz )
];
} else {
return [
new THREE.Vector2( ay, 1 - az ),
new THREE.Vector2( by, 1 - bz ),
new THREE.Vector2( cy, 1 - cz ),
new THREE.Vector2( dy, 1 - dz )
];
}
}
};
THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
/**
* @author jonobr1 / http://jonobr1.com
*
* Creates a one-sided polygonal geometry from a path shape. Similar to
* ExtrudeGeometry.
*
* parameters = {
*
* curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
*
* material: <int> // material index for front and back faces
* uvGenerator: <Object> // object that provides UV generator functions
*
* }
**/
THREE.ShapeGeometry = function ( shapes, options ) {
THREE.Geometry.call( this );
if ( shapes instanceof Array === false ) shapes = [ shapes ];
this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
this.addShapeList( shapes, options );
this.computeCentroids();
this.computeFaceNormals();
};
THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* Add an array of shapes to THREE.ShapeGeometry.
*/
THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
for ( var i = 0, l = shapes.length; i < l; i++ ) {
this.addShape( shapes[ i ], options );
}
return this;
};
/**
* Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
*/
THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
if ( options === undefined ) options = {};
var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
var material = options.material;
var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
var shapebb = this.shapebb;
//
var i, l, hole, s;
var shapesOffset = this.vertices.length;
var shapePoints = shape.extractPoints( curveSegments );
var vertices = shapePoints.shape;
var holes = shapePoints.holes;
var reverse = !THREE.Shape.Utils.isClockWise( vertices );
if ( reverse ) {
vertices = vertices.reverse();
// Maybe we should also check if holes are in the opposite direction, just to be safe...
for ( i = 0, l = holes.length; i < l; i++ ) {
hole = holes[ i ];
if ( THREE.Shape.Utils.isClockWise( hole ) ) {
holes[ i ] = hole.reverse();
}
}
reverse = false;
}
var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
// Vertices
var contour = vertices;
for ( i = 0, l = holes.length; i < l; i++ ) {
hole = holes[ i ];
vertices = vertices.concat( hole );
}
//
var vert, vlen = vertices.length;
var face, flen = faces.length;
var cont, clen = contour.length;
for ( i = 0; i < vlen; i++ ) {
vert = vertices[ i ];
this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
}
for ( i = 0; i < flen; i++ ) {
face = faces[ i ];
var a = face[ 0 ] + shapesOffset;
var b = face[ 1 ] + shapesOffset;
var c = face[ 2 ] + shapesOffset;
this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
}
};
/**
* @author astrodud / http://astrodud.isgreat.org/
* @author zz85 / https://github.com/zz85
* @author bhouston / http://exocortex.com
*/
// points - to create a closed torus, one must use a set of points
// like so: [ a, b, c, d, a ], see first is the same as last.
// segments - the number of circumference segments to create
// phiStart - the starting radian
// phiLength - the radian (0 to 2*PI) range of the lathed section
// 2*pi is a closed lathe, less than 2PI is a portion.
THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
THREE.Geometry.call( this );
segments = segments || 12;
phiStart = phiStart || 0;
phiLength = phiLength || 2 * Math.PI;
var inversePointLength = 1.0 / ( points.length - 1 );
var inverseSegments = 1.0 / segments;
for ( var i = 0, il = segments; i <= il; i ++ ) {
var phi = phiStart + i * inverseSegments * phiLength;
var c = Math.cos( phi ),
s = Math.sin( phi );
for ( var j = 0, jl = points.length; j < jl; j ++ ) {
var pt = points[ j ];
var vertex = new THREE.Vector3();
vertex.x = c * pt.x - s * pt.y;
vertex.y = s * pt.x + c * pt.y;
vertex.z = pt.z;
this.vertices.push( vertex );
}
}
var np = points.length;
for ( var i = 0, il = segments; i < il; i ++ ) {
for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
var base = j + np * i;
var a = base;
var b = base + np;
var c = base + 1 + np;
var d = base + 1;
var u0 = i * inverseSegments;
var v0 = j * inversePointLength;
var u1 = u0 + inverseSegments;
var v1 = v0 + inversePointLength;
this.faces.push( new THREE.Face3( a, b, d ) );
this.faceVertexUvs[ 0 ].push( [
new THREE.Vector2( u0, v0 ),
new THREE.Vector2( u1, v0 ),
new THREE.Vector2( u0, v1 )
] );
this.faces.push( new THREE.Face3( b, c, d ) );
this.faceVertexUvs[ 0 ].push( [
new THREE.Vector2( u1, v0 ),
new THREE.Vector2( u1, v1 ),
new THREE.Vector2( u0, v1 )
] );
}
}
this.mergeVertices();
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
};
THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author mrdoob / http://mrdoob.com/
* based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
*/
THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
THREE.Geometry.call( this );
this.width = width;
this.height = height;
this.widthSegments = widthSegments || 1;
this.heightSegments = heightSegments || 1;
var ix, iz;
var width_half = width / 2;
var height_half = height / 2;
var gridX = this.widthSegments;
var gridZ = this.heightSegments;
var gridX1 = gridX + 1;
var gridZ1 = gridZ + 1;
var segment_width = this.width / gridX;
var segment_height = this.height / gridZ;
var normal = new THREE.Vector3( 0, 0, 1 );
for ( iz = 0; iz < gridZ1; iz ++ ) {
for ( ix = 0; ix < gridX1; ix ++ ) {
var x = ix * segment_width - width_half;
var y = iz * segment_height - height_half;
this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
}
}
for ( iz = 0; iz < gridZ; iz ++ ) {
for ( ix = 0; ix < gridX; ix ++ ) {
var a = ix + gridX1 * iz;
var b = ix + gridX1 * ( iz + 1 );
var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
var d = ( ix + 1 ) + gridX1 * iz;
var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
var face = new THREE.Face3( a, b, d );
face.normal.copy( normal );
face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
this.faces.push( face );
this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
face = new THREE.Face3( b, c, d );
face.normal.copy( normal );
face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
this.faces.push( face );
this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
}
}
this.computeCentroids();
};
THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author Kaleb Murphy
*/
THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
THREE.Geometry.call( this );
innerRadius = innerRadius || 0;
outerRadius = outerRadius || 50;
thetaStart = thetaStart !== undefined ? thetaStart : 0;
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
var vertex = new THREE.Vector3();
var segment = thetaStart + o / thetaSegments * thetaLength;
vertex.x = radius * Math.cos( segment );
vertex.y = radius * Math.sin( segment );
this.vertices.push( vertex );
uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
}
radius += radiusStep;
}
var n = new THREE.Vector3( 0, 0, 1 );
for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
var thetaSegment = i * thetaSegments;
for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
var segment = o + thetaSegment;
var v1 = segment + i;
var v2 = segment + thetaSegments + i;
var v3 = segment + thetaSegments + 1 + i;
this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
v1 = segment + i;
v2 = segment + thetaSegments + 1 + i;
v3 = segment + 1 + i;
this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
}
}
this.computeCentroids();
this.computeFaceNormals();
this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
};
THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
THREE.Geometry.call( this );
this.radius = radius = radius || 50;
this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
var x, y, vertices = [], uvs = [];
for ( y = 0; y <= heightSegments; y ++ ) {
var verticesRow = [];
var uvsRow = [];
for ( x = 0; x <= widthSegments; x ++ ) {
var u = x / widthSegments;
var v = y / heightSegments;
var vertex = new THREE.Vector3();
vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
this.vertices.push( vertex );
verticesRow.push( this.vertices.length - 1 );
uvsRow.push( new THREE.Vector2( u, 1 - v ) );
}
vertices.push( verticesRow );
uvs.push( uvsRow );
}
for ( y = 0; y < this.heightSegments; y ++ ) {
for ( x = 0; x < this.widthSegments; x ++ ) {
var v1 = vertices[ y ][ x + 1 ];
var v2 = vertices[ y ][ x ];
var v3 = vertices[ y + 1 ][ x ];
var v4 = vertices[ y + 1 ][ x + 1 ];
var n1 = this.vertices[ v1 ].clone().normalize();
var n2 = this.vertices[ v2 ].clone().normalize();
var n3 = this.vertices[ v3 ].clone().normalize();
var n4 = this.vertices[ v4 ].clone().normalize();
var uv1 = uvs[ y ][ x + 1 ].clone();
var uv2 = uvs[ y ][ x ].clone();
var uv3 = uvs[ y + 1 ][ x ].clone();
var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
uv1.x = ( uv1.x + uv2.x ) / 2;
this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
} else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
uv3.x = ( uv3.x + uv4.x ) / 2;
this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
} else {
this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
}
}
}
this.computeCentroids();
this.computeFaceNormals();
this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
};
THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author alteredq / http://alteredqualia.com/
*
* For creating 3D text geometry in three.js
*
* Text = 3D Text
*
* parameters = {
* size: <float>, // size of the text
* height: <float>, // thickness to extrude text
* curveSegments: <int>, // number of points on the curves
*
* font: <string>, // font name
* weight: <string>, // font weight (normal, bold)
* style: <string>, // font style (normal, italics)
*
* bevelEnabled: <bool>, // turn on bevel
* bevelThickness: <float>, // how deep into text bevel goes
* bevelSize: <float>, // how far from text outline is bevel
* }
*
*/
/* Usage Examples
// TextGeometry wrapper
var text3d = new TextGeometry( text, options );
// Complete manner
var textShapes = THREE.FontUtils.generateShapes( text, options );
var text3d = new ExtrudeGeometry( textShapes, options );
*/
THREE.TextGeometry = function ( text, parameters ) {
parameters = parameters || {};
var textShapes = THREE.FontUtils.generateShapes( text, parameters );
// translate parameters to ExtrudeGeometry API
parameters.amount = parameters.height !== undefined ? parameters.height : 50;
// defaults
if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
THREE.ExtrudeGeometry.call( this, textShapes, parameters );
};
THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
/**
* @author oosmoxiecode
* @author mrdoob / http://mrdoob.com/
* based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
*/
THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
THREE.Geometry.call( this );
var scope = this;
this.radius = radius || 100;
this.tube = tube || 40;
this.radialSegments = radialSegments || 8;
this.tubularSegments = tubularSegments || 6;
this.arc = arc || Math.PI * 2;
var center = new THREE.Vector3(), uvs = [], normals = [];
for ( var j = 0; j <= this.radialSegments; j ++ ) {
for ( var i = 0; i <= this.tubularSegments; i ++ ) {
var u = i / this.tubularSegments * this.arc;
var v = j / this.radialSegments * Math.PI * 2;
center.x = this.radius * Math.cos( u );
center.y = this.radius * Math.sin( u );
var vertex = new THREE.Vector3();
vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
vertex.z = this.tube * Math.sin( v );
this.vertices.push( vertex );
uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
normals.push( vertex.clone().sub( center ).normalize() );
}
}
for ( var j = 1; j <= this.radialSegments; j ++ ) {
for ( var i = 1; i <= this.tubularSegments; i ++ ) {
var a = ( this.tubularSegments + 1 ) * j + i - 1;
var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
var d = ( this.tubularSegments + 1 ) * j + i;
var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
this.faces.push( face );
this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
this.faces.push( face );
this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
};
THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author oosmoxiecode
* based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
*/
THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
THREE.Geometry.call( this );
var scope = this;
this.radius = radius || 100;
this.tube = tube || 40;
this.radialSegments = radialSegments || 64;
this.tubularSegments = tubularSegments || 8;
this.p = p || 2;
this.q = q || 3;
this.heightScale = heightScale || 1;
this.grid = new Array( this.radialSegments );
var tang = new THREE.Vector3();
var n = new THREE.Vector3();
var bitan = new THREE.Vector3();
for ( var i = 0; i < this.radialSegments; ++ i ) {
this.grid[ i ] = new Array( this.tubularSegments );
var u = i / this.radialSegments * 2 * this.p * Math.PI;
var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
tang.subVectors( p2, p1 );
n.addVectors( p2, p1 );
bitan.crossVectors( tang, n );
n.crossVectors( bitan, tang );
bitan.normalize();
n.normalize();
for ( var j = 0; j < this.tubularSegments; ++ j ) {
var v = j / this.tubularSegments * 2 * Math.PI;
var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
var cy = this.tube * Math.sin( v );
var pos = new THREE.Vector3();
pos.x = p1.x + cx * n.x + cy * bitan.x;
pos.y = p1.y + cx * n.y + cy * bitan.y;
pos.z = p1.z + cx * n.z + cy * bitan.z;
this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
}
}
for ( var i = 0; i < this.radialSegments; ++ i ) {
for ( var j = 0; j < this.tubularSegments; ++ j ) {
var ip = ( i + 1 ) % this.radialSegments;
var jp = ( j + 1 ) % this.tubularSegments;
var a = this.grid[ i ][ j ];
var b = this.grid[ ip ][ j ];
var c = this.grid[ ip ][ jp ];
var d = this.grid[ i ][ jp ];
var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
this.faces.push( new THREE.Face3( a, b, d ) );
this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
this.faces.push( new THREE.Face3( b, c, d ) );
this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
function getPos( u, in_q, in_p, radius, heightScale ) {
var cu = Math.cos( u );
var su = Math.sin( u );
var quOverP = in_q / in_p * u;
var cs = Math.cos( quOverP );
var tx = radius * ( 2 + cs ) * 0.5 * cu;
var ty = radius * ( 2 + cs ) * su * 0.5;
var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
return new THREE.Vector3( tx, ty, tz );
}
};
THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author WestLangley / https://github.com/WestLangley
* @author zz85 / https://github.com/zz85
* @author miningold / https://github.com/miningold
*
* Modified from the TorusKnotGeometry by @oosmoxiecode
*
* Creates a tube which extrudes along a 3d spline
*
* Uses parallel transport frames as described in
* http://www.cs.indiana.edu/pub/techreports/TR425.pdf
*/
THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
THREE.Geometry.call( this );
this.path = path;
this.segments = segments || 64;
this.radius = radius || 1;
this.radialSegments = radialSegments || 8;
this.closed = closed || false;
this.grid = [];
var scope = this,
tangent,
normal,
binormal,
numpoints = this.segments + 1,
x, y, z,
tx, ty, tz,
u, v,
cx, cy,
pos, pos2 = new THREE.Vector3(),
i, j,
ip, jp,
a, b, c, d,
uva, uvb, uvc, uvd;
var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
tangents = frames.tangents,
normals = frames.normals,
binormals = frames.binormals;
// proxy internals
this.tangents = tangents;
this.normals = normals;
this.binormals = binormals;
function vert( x, y, z ) {
return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
}
// consruct the grid
for ( i = 0; i < numpoints; i++ ) {
this.grid[ i ] = [];
u = i / ( numpoints - 1 );
pos = path.getPointAt( u );
tangent = tangents[ i ];
normal = normals[ i ];
binormal = binormals[ i ];
for ( j = 0; j < this.radialSegments; j++ ) {
v = j / this.radialSegments * 2 * Math.PI;
cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
cy = this.radius * Math.sin( v );
pos2.copy( pos );
pos2.x += cx * normal.x + cy * binormal.x;
pos2.y += cx * normal.y + cy * binormal.y;
pos2.z += cx * normal.z + cy * binormal.z;
this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
}
}
// construct the mesh
for ( i = 0; i < this.segments; i++ ) {
for ( j = 0; j < this.radialSegments; j++ ) {
ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
jp = (j + 1) % this.radialSegments;
a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
b = this.grid[ ip ][ j ];
c = this.grid[ ip ][ jp ];
d = this.grid[ i ][ jp ];
uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
this.faces.push( new THREE.Face3( a, b, d ) );
this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
this.faces.push( new THREE.Face3( b, c, d ) );
this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
};
THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
// For computing of Frenet frames, exposing the tangents, normals and binormals the spline
THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
var tangent = new THREE.Vector3(),
normal = new THREE.Vector3(),
binormal = new THREE.Vector3(),
tangents = [],
normals = [],
binormals = [],
vec = new THREE.Vector3(),
mat = new THREE.Matrix4(),
numpoints = segments + 1,
theta,
epsilon = 0.0001,
smallest,
tx, ty, tz,
i, u, v;
// expose internals
this.tangents = tangents;
this.normals = normals;
this.binormals = binormals;
// compute the tangent vectors for each segment on the path
for ( i = 0; i < numpoints; i++ ) {
u = i / ( numpoints - 1 );
tangents[ i ] = path.getTangentAt( u );
tangents[ i ].normalize();
}
initialNormal3();
function initialNormal1(lastBinormal) {
// fixed start binormal. Has dangers of 0 vectors
normals[ 0 ] = new THREE.Vector3();
binormals[ 0 ] = new THREE.Vector3();
if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
}
function initialNormal2() {
// This uses the Frenet-Serret formula for deriving binormal
var t2 = path.getTangentAt( epsilon );
normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
}
function initialNormal3() {
// select an initial normal vector perpenicular to the first tangent vector,
// and in the direction of the smallest tangent xyz component
normals[ 0 ] = new THREE.Vector3();
binormals[ 0 ] = new THREE.Vector3();
smallest = Number.MAX_VALUE;
tx = Math.abs( tangents[ 0 ].x );
ty = Math.abs( tangents[ 0 ].y );
tz = Math.abs( tangents[ 0 ].z );
if ( tx <= smallest ) {
smallest = tx;
normal.set( 1, 0, 0 );
}
if ( ty <= smallest ) {
smallest = ty;
normal.set( 0, 1, 0 );
}
if ( tz <= smallest ) {
normal.set( 0, 0, 1 );
}
vec.crossVectors( tangents[ 0 ], normal ).normalize();
normals[ 0 ].crossVectors( tangents[ 0 ], vec );
binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
}
// compute the slowly-varying normal and binormal vectors for each segment on the path
for ( i = 1; i < numpoints; i++ ) {
normals[ i ] = normals[ i-1 ].clone();
binormals[ i ] = binormals[ i-1 ].clone();
vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
if ( vec.length() > epsilon ) {
vec.normalize();
theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
}
binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
}
// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
if ( closed ) {
theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
theta /= ( numpoints - 1 );
if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
theta = -theta;
}
for ( i = 1; i < numpoints; i++ ) {
// twist a little...
normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
}
}
};
/**
* @author clockworkgeek / https://github.com/clockworkgeek
* @author timothypratley / https://github.com/timothypratley
* @author WestLangley / http://github.com/WestLangley
*/
THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
THREE.Geometry.call( this );
radius = radius || 1;
detail = detail || 0;
var that = this;
for ( var i = 0, l = vertices.length; i < l; i ++ ) {
prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
}
var midpoints = [], p = this.vertices;
var f = [];
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var v1 = p[ faces[ i ][ 0 ] ];
var v2 = p[ faces[ i ][ 1 ] ];
var v3 = p[ faces[ i ][ 2 ] ];
f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
}
for ( var i = 0, l = f.length; i < l; i ++ ) {
subdivide(f[ i ], detail);
}
// Handle case when face straddles the seam
for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
var uvs = this.faceVertexUvs[ 0 ][ i ];
var x0 = uvs[ 0 ].x;
var x1 = uvs[ 1 ].x;
var x2 = uvs[ 2 ].x;
var max = Math.max( x0, Math.max( x1, x2 ) );
var min = Math.min( x0, Math.min( x1, x2 ) );
if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
}
}
// Apply radius
for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
this.vertices[ i ].multiplyScalar( radius );
}
// Merge vertices
this.mergeVertices();
this.computeCentroids();
this.computeFaceNormals();
this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
// Project vector onto sphere's surface
function prepare( vector ) {
var vertex = vector.normalize().clone();
vertex.index = that.vertices.push( vertex ) - 1;
// Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
var u = azimuth( vector ) / 2 / Math.PI + 0.5;
var v = inclination( vector ) / Math.PI + 0.5;
vertex.uv = new THREE.Vector2( u, 1 - v );
return vertex;
}
// Approximate a curved face with recursively sub-divided triangles.
function make( v1, v2, v3 ) {
var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
that.faces.push( face );
var azi = azimuth( face.centroid );
that.faceVertexUvs[ 0 ].push( [
correctUV( v1.uv, v1, azi ),
correctUV( v2.uv, v2, azi ),
correctUV( v3.uv, v3, azi )
] );
}
// Analytically subdivide a face to the required detail level.
function subdivide(face, detail ) {
var cols = Math.pow(2, detail);
var cells = Math.pow(4, detail);
var a = prepare( that.vertices[ face.a ] );
var b = prepare( that.vertices[ face.b ] );
var c = prepare( that.vertices[ face.c ] );
var v = [];
// Construct all of the vertices for this subdivision.
for ( var i = 0 ; i <= cols; i ++ ) {
v[ i ] = [];
var aj = prepare( a.clone().lerp( c, i / cols ) );
var bj = prepare( b.clone().lerp( c, i / cols ) );
var rows = cols - i;
for ( var j = 0; j <= rows; j ++) {
if ( j == 0 && i == cols ) {
v[ i ][ j ] = aj;
} else {
v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
}
}
}
// Construct all of the faces.
for ( var i = 0; i < cols ; i ++ ) {
for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
var k = Math.floor( j / 2 );
if ( j % 2 == 0 ) {
make(
v[ i ][ k + 1],
v[ i + 1 ][ k ],
v[ i ][ k ]
);
} else {
make(
v[ i ][ k + 1 ],
v[ i + 1][ k + 1],
v[ i + 1 ][ k ]
);
}
}
}
}
// Angle around the Y axis, counter-clockwise when looking from above.
function azimuth( vector ) {
return Math.atan2( vector.z, -vector.x );
}
// Angle above the XZ plane.
function inclination( vector ) {
return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
}
// Texture fixing helper. Spheres have some odd behaviours.
function correctUV( uv, vector, azimuth ) {
if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
return uv.clone();
}
};
THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author timothypratley / https://github.com/timothypratley
*/
THREE.IcosahedronGeometry = function ( radius, detail ) {
this.radius = radius;
this.detail = detail;
var t = ( 1 + Math.sqrt( 5 ) ) / 2;
var vertices = [
[ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
[ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
[ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
];
var faces = [
[ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
[ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
[ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
[ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
];
THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
};
THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author timothypratley / https://github.com/timothypratley
*/
THREE.OctahedronGeometry = function ( radius, detail ) {
var vertices = [
[ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
];
var faces = [
[ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
];
THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
};
THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author timothypratley / https://github.com/timothypratley
*/
THREE.TetrahedronGeometry = function ( radius, detail ) {
var vertices = [
[ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
];
var faces = [
[ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
];
THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
};
THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author zz85 / https://github.com/zz85
* Parametric Surfaces Geometry
* based on the brilliant article by @prideout http://prideout.net/blog/?p=44
*
* new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
*
*/
THREE.ParametricGeometry = function ( func, slices, stacks ) {
THREE.Geometry.call( this );
var verts = this.vertices;
var faces = this.faces;
var uvs = this.faceVertexUvs[ 0 ];
var i, il, j, p;
var u, v;
var stackCount = stacks + 1;
var sliceCount = slices + 1;
for ( i = 0; i <= stacks; i ++ ) {
v = i / stacks;
for ( j = 0; j <= slices; j ++ ) {
u = j / slices;
p = func( u, v );
verts.push( p );
}
}
var a, b, c, d;
var uva, uvb, uvc, uvd;
for ( i = 0; i < stacks; i ++ ) {
for ( j = 0; j < slices; j ++ ) {
a = i * sliceCount + j;
b = i * sliceCount + j + 1;
c = (i + 1) * sliceCount + j + 1;
d = (i + 1) * sliceCount + j;
uva = new THREE.Vector2( j / slices, i / stacks );
uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
faces.push( new THREE.Face3( a, b, d ) );
uvs.push( [ uva, uvb, uvd ] );
faces.push( new THREE.Face3( b, c, d ) );
uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
}
}
// console.log(this);
// magic bullet
// var diff = this.mergeVertices();
// console.log('removed ', diff, ' vertices by merging');
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
};
THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
* @author sroucheray / http://sroucheray.org/
* @author mrdoob / http://mrdoob.com/
*/
THREE.AxisHelper = function ( size ) {
size = size || 1;
var geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
);
geometry.colors.push(
new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
);
var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
THREE.Line.call( this, geometry, material, THREE.LinePieces );
};
THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
/**
* @author WestLangley / http://github.com/WestLangley
* @author zz85 / http://github.com/zz85
* @author bhouston / http://exocortex.com
*
* Creates an arrow for visualizing directions
*
* Parameters:
* dir - Vector3
* origin - Vector3
* length - Number
* hex - color in hex value
* headLength - Number
* headWidth - Number
*/
THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
// dir is assumed to be normalized
THREE.Object3D.call( this );
if ( hex === undefined ) hex = 0xffff00;
if ( length === undefined ) length = 1;
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
this.position = origin;
var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
this.line.matrixAutoUpdate = false;
this.add( this.line );
var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
this.cone.matrixAutoUpdate = false;
this.add( this.cone );
this.setDirection( dir );
this.setLength( length, headLength, headWidth );
};
THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
THREE.ArrowHelper.prototype.setDirection = function () {
var axis = new THREE.Vector3();
var radians;
return function ( dir ) {
// dir is assumed to be normalized
if ( dir.y > 0.99999 ) {
this.quaternion.set( 0, 0, 0, 1 );
} else if ( dir.y < - 0.99999 ) {
this.quaternion.set( 1, 0, 0, 0 );
} else {
axis.set( dir.z, 0, - dir.x ).normalize();
radians = Math.acos( dir.y );
this.quaternion.setFromAxisAngle( axis, radians );
}
};
}();
THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
this.line.scale.set( 1, length, 1 );
this.line.updateMatrix();
this.cone.scale.set( headWidth, headLength, headWidth );
this.cone.position.y = length;
this.cone.updateMatrix();
};
THREE.ArrowHelper.prototype.setColor = function ( hex ) {
this.line.material.color.setHex( hex );
this.cone.material.color.setHex( hex );
};
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.BoxHelper = function ( object ) {
// 5____4
// 1/___0/|
// | 6__|_7
// 2/___3/
var vertices = [
new THREE.Vector3( 1, 1, 1 ),
new THREE.Vector3( - 1, 1, 1 ),
new THREE.Vector3( - 1, - 1, 1 ),
new THREE.Vector3( 1, - 1, 1 ),
new THREE.Vector3( 1, 1, - 1 ),
new THREE.Vector3( - 1, 1, - 1 ),
new THREE.Vector3( - 1, - 1, - 1 ),
new THREE.Vector3( 1, - 1, - 1 )
];
this.vertices = vertices;
// TODO: Wouldn't be nice if Line had .segments?
var geometry = new THREE.Geometry();
geometry.vertices.push(
vertices[ 0 ], vertices[ 1 ],
vertices[ 1 ], vertices[ 2 ],
vertices[ 2 ], vertices[ 3 ],
vertices[ 3 ], vertices[ 0 ],
vertices[ 4 ], vertices[ 5 ],
vertices[ 5 ], vertices[ 6 ],
vertices[ 6 ], vertices[ 7 ],
vertices[ 7 ], vertices[ 4 ],
vertices[ 0 ], vertices[ 4 ],
vertices[ 1 ], vertices[ 5 ],
vertices[ 2 ], vertices[ 6 ],
vertices[ 3 ], vertices[ 7 ]
);
THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
if ( object !== undefined ) {
this.update( object );
}
};
THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
THREE.BoxHelper.prototype.update = function ( object ) {
var geometry = object.geometry;
if ( geometry.boundingBox === null ) {
geometry.computeBoundingBox();
}
var min = geometry.boundingBox.min;
var max = geometry.boundingBox.max;
var vertices = this.vertices;
vertices[ 0 ].set( max.x, max.y, max.z );
vertices[ 1 ].set( min.x, max.y, max.z );
vertices[ 2 ].set( min.x, min.y, max.z );
vertices[ 3 ].set( max.x, min.y, max.z );
vertices[ 4 ].set( max.x, max.y, min.z );
vertices[ 5 ].set( min.x, max.y, min.z );
vertices[ 6 ].set( min.x, min.y, min.z );
vertices[ 7 ].set( max.x, min.y, min.z );
this.geometry.computeBoundingSphere();
this.geometry.verticesNeedUpdate = true;
this.matrixAutoUpdate = false;
this.matrixWorld = object.matrixWorld;
};
/**
* @author WestLangley / http://github.com/WestLangley
*/
// a helper to show the world-axis-aligned bounding box for an object
THREE.BoundingBoxHelper = function ( object, hex ) {
var color = ( hex !== undefined ) ? hex : 0x888888;
this.object = object;
this.box = new THREE.Box3();
THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
};
THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
THREE.BoundingBoxHelper.prototype.update = function () {
this.box.setFromObject( this.object );
this.box.size( this.scale );
this.box.center( this.position );
};
/**
* @author alteredq / http://alteredqualia.com/
*
* - shows frustum, line of sight and up of the camera
* - suitable for fast updates
* - based on frustum visualization in lightgl.js shadowmap example
* http://evanw.github.com/lightgl.js/tests/shadowmap.html
*/
THREE.CameraHelper = function ( camera ) {
var geometry = new THREE.Geometry();
var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
var pointMap = {};
// colors
var hexFrustum = 0xffaa00;
var hexCone = 0xff0000;
var hexUp = 0x00aaff;
var hexTarget = 0xffffff;
var hexCross = 0x333333;
// near
addLine( "n1", "n2", hexFrustum );
addLine( "n2", "n4", hexFrustum );
addLine( "n4", "n3", hexFrustum );
addLine( "n3", "n1", hexFrustum );
// far
addLine( "f1", "f2", hexFrustum );
addLine( "f2", "f4", hexFrustum );
addLine( "f4", "f3", hexFrustum );
addLine( "f3", "f1", hexFrustum );
// sides
addLine( "n1", "f1", hexFrustum );
addLine( "n2", "f2", hexFrustum );
addLine( "n3", "f3", hexFrustum );
addLine( "n4", "f4", hexFrustum );
// cone
addLine( "p", "n1", hexCone );
addLine( "p", "n2", hexCone );
addLine( "p", "n3", hexCone );
addLine( "p", "n4", hexCone );
// up
addLine( "u1", "u2", hexUp );
addLine( "u2", "u3", hexUp );
addLine( "u3", "u1", hexUp );
// target
addLine( "c", "t", hexTarget );
addLine( "p", "c", hexCross );
// cross
addLine( "cn1", "cn2", hexCross );
addLine( "cn3", "cn4", hexCross );
addLine( "cf1", "cf2", hexCross );
addLine( "cf3", "cf4", hexCross );
function addLine( a, b, hex ) {
addPoint( a, hex );
addPoint( b, hex );
}
function addPoint( id, hex ) {
geometry.vertices.push( new THREE.Vector3() );
geometry.colors.push( new THREE.Color( hex ) );
if ( pointMap[ id ] === undefined ) {
pointMap[ id ] = [];
}
pointMap[ id ].push( geometry.vertices.length - 1 );
}
THREE.Line.call( this, geometry, material, THREE.LinePieces );
this.camera = camera;
this.matrixWorld = camera.matrixWorld;
this.matrixAutoUpdate = false;
this.pointMap = pointMap;
this.update();
};
THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
THREE.CameraHelper.prototype.update = function () {
var vector = new THREE.Vector3();
var camera = new THREE.Camera();
var projector = new THREE.Projector();
return function () {
var scope = this;
var w = 1, h = 1;
// we need just camera projection matrix
// world matrix must be identity
camera.projectionMatrix.copy( this.camera.projectionMatrix );
// center / target
setPoint( "c", 0, 0, -1 );
setPoint( "t", 0, 0, 1 );
// near
setPoint( "n1", -w, -h, -1 );
setPoint( "n2", w, -h, -1 );
setPoint( "n3", -w, h, -1 );
setPoint( "n4", w, h, -1 );
// far
setPoint( "f1", -w, -h, 1 );
setPoint( "f2", w, -h, 1 );
setPoint( "f3", -w, h, 1 );
setPoint( "f4", w, h, 1 );
// up
setPoint( "u1", w * 0.7, h * 1.1, -1 );
setPoint( "u2", -w * 0.7, h * 1.1, -1 );
setPoint( "u3", 0, h * 2, -1 );
// cross
setPoint( "cf1", -w, 0, 1 );
setPoint( "cf2", w, 0, 1 );
setPoint( "cf3", 0, -h, 1 );
setPoint( "cf4", 0, h, 1 );
setPoint( "cn1", -w, 0, -1 );
setPoint( "cn2", w, 0, -1 );
setPoint( "cn3", 0, -h, -1 );
setPoint( "cn4", 0, h, -1 );
function setPoint( point, x, y, z ) {
vector.set( x, y, z );
projector.unprojectVector( vector, camera );
var points = scope.pointMap[ point ];
if ( points !== undefined ) {
for ( var i = 0, il = points.length; i < il; i ++ ) {
scope.geometry.vertices[ points[ i ] ].copy( vector );
}
}
}
this.geometry.verticesNeedUpdate = true;
};
}();
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.DirectionalLightHelper = function ( light, size ) {
THREE.Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrixWorld = light.matrixWorld;
this.matrixAutoUpdate = false;
size = size || 1;
var geometry = new THREE.PlaneGeometry( size, size );
var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
this.lightPlane = new THREE.Mesh( geometry, material );
this.add( this.lightPlane );
geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3() );
geometry.vertices.push( new THREE.Vector3() );
material = new THREE.LineBasicMaterial( { fog: false } );
material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
this.targetLine = new THREE.Line( geometry, material );
this.add( this.targetLine );
this.update();
};
THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
THREE.DirectionalLightHelper.prototype.dispose = function () {
this.lightPlane.geometry.dispose();
this.lightPlane.material.dispose();
this.targetLine.geometry.dispose();
this.targetLine.material.dispose();
};
THREE.DirectionalLightHelper.prototype.update = function () {
var v1 = new THREE.Vector3();
var v2 = new THREE.Vector3();
var v3 = new THREE.Vector3();
return function () {
v1.setFromMatrixPosition( this.light.matrixWorld );
v2.setFromMatrixPosition( this.light.target.matrixWorld );
v3.subVectors( v2, v1 );
this.lightPlane.lookAt( v3 );
this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
this.targetLine.geometry.vertices[ 1 ].copy( v3 );
this.targetLine.geometry.verticesNeedUpdate = true;
this.targetLine.material.color.copy( this.lightPlane.material.color );
}
}();
/**
* @author WestLangley / http://github.com/WestLangley
*/
THREE.EdgesHelper = function ( object, hex ) {
var color = ( hex !== undefined ) ? hex : 0xffffff;
var edge = [ 0, 0 ], hash = {};
var sortFunction = function ( a, b ) { return a - b };
var keys = [ 'a', 'b', 'c' ];
var geometry = new THREE.BufferGeometry();
var geometry2 = object.geometry.clone();
geometry2.mergeVertices();
geometry2.computeFaceNormals();
var vertices = geometry2.vertices;
var faces = geometry2.faces;
var numEdges = 0;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( var j = 0; j < 3; j ++ ) {
edge[ 0 ] = face[ keys[ j ] ];
edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
edge.sort( sortFunction );
var key = edge.toString();
if ( hash[ key ] === undefined ) {
hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
numEdges ++;
} else {
hash[ key ].face2 = i;
}
}
}
geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
var coords = geometry.attributes.position.array;
var index = 0;
for ( var key in hash ) {
var h = hash[ key ];
if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
var vertex = vertices[ h.vert1 ];
coords[ index ++ ] = vertex.x;
coords[ index ++ ] = vertex.y;
coords[ index ++ ] = vertex.z;
vertex = vertices[ h.vert2 ];
coords[ index ++ ] = vertex.x;
coords[ index ++ ] = vertex.y;
coords[ index ++ ] = vertex.z;
}
}
THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
this.matrixAutoUpdate = false;
this.matrixWorld = object.matrixWorld;
};
THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
/**
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
this.object = object;
this.size = ( size !== undefined ) ? size : 1;
var color = ( hex !== undefined ) ? hex : 0xffff00;
var width = ( linewidth !== undefined ) ? linewidth : 1;
var geometry = new THREE.Geometry();
var faces = this.object.geometry.faces;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
geometry.vertices.push( new THREE.Vector3() );
geometry.vertices.push( new THREE.Vector3() );
}
THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
this.matrixAutoUpdate = false;
this.normalMatrix = new THREE.Matrix3();
this.update();
};
THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
var v1 = new THREE.Vector3();
return function ( object ) {
this.object.updateMatrixWorld( true );
this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
var vertices = this.geometry.vertices;
var faces = this.object.geometry.faces;
var worldMatrix = this.object.matrixWorld;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
var idx = 2 * i;
vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
}
this.geometry.verticesNeedUpdate = true;
return this;
}
}());
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.GridHelper = function ( size, step ) {
var geometry = new THREE.Geometry();
var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
this.color1 = new THREE.Color( 0x444444 );
this.color2 = new THREE.Color( 0x888888 );
for ( var i = - size; i <= size; i += step ) {
geometry.vertices.push(
new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
);
var color = i === 0 ? this.color1 : this.color2;
geometry.colors.push( color, color, color, color );
}
THREE.Line.call( this, geometry, material, THREE.LinePieces );
};
THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
this.color1.set( colorCenterLine );
this.color2.set( colorGrid );
this.geometry.colorsNeedUpdate = true;
}
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
THREE.Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrixWorld = light.matrixWorld;
this.matrixAutoUpdate = false;
this.colors = [ new THREE.Color(), new THREE.Color() ];
var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
for ( var i = 0, il = 8; i < il; i ++ ) {
geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
}
var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
this.lightSphere = new THREE.Mesh( geometry, material );
this.add( this.lightSphere );
this.update();
};
THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
THREE.HemisphereLightHelper.prototype.dispose = function () {
this.lightSphere.geometry.dispose();
this.lightSphere.material.dispose();
};
THREE.HemisphereLightHelper.prototype.update = function () {
var vector = new THREE.Vector3();
return function () {
this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
this.lightSphere.geometry.colorsNeedUpdate = true;
}
}();
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
THREE.PointLightHelper = function ( light, sphereSize ) {
this.light = light;
this.light.updateMatrixWorld();
var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
THREE.Mesh.call( this, geometry, material );
this.matrixWorld = this.light.matrixWorld;
this.matrixAutoUpdate = false;
/*
var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
var d = light.distance;
if ( d === 0.0 ) {
this.lightDistance.visible = false;
} else {
this.lightDistance.scale.set( d, d, d );
}
this.add( this.lightDistance );
*/
};
THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
THREE.PointLightHelper.prototype.dispose = function () {
this.geometry.dispose();
this.material.dispose();
};
THREE.PointLightHelper.prototype.update = function () {
this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
/*
var d = this.light.distance;
if ( d === 0.0 ) {
this.lightDistance.visible = false;
} else {
this.lightDistance.visible = true;
this.lightDistance.scale.set( d, d, d );
}
*/
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.SpotLightHelper = function ( light ) {
THREE.Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrixWorld = light.matrixWorld;
this.matrixAutoUpdate = false;
var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
this.cone = new THREE.Mesh( geometry, material );
this.add( this.cone );
this.update();
};
THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
THREE.SpotLightHelper.prototype.dispose = function () {
this.cone.geometry.dispose();
this.cone.material.dispose();
};
THREE.SpotLightHelper.prototype.update = function () {
var vector = new THREE.Vector3();
var vector2 = new THREE.Vector3();
return function () {
var coneLength = this.light.distance ? this.light.distance : 10000;
var coneWidth = coneLength * Math.tan( this.light.angle );
this.cone.scale.set( coneWidth, coneWidth, coneLength );
vector.setFromMatrixPosition( this.light.matrixWorld );
vector2.setFromMatrixPosition( this.light.target.matrixWorld );
this.cone.lookAt( vector2.sub( vector ) );
this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
};
}();
/**
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
this.object = object;
this.size = ( size !== undefined ) ? size : 1;
var color = ( hex !== undefined ) ? hex : 0xff0000;
var width = ( linewidth !== undefined ) ? linewidth : 1;
var geometry = new THREE.Geometry();
var vertices = object.geometry.vertices;
var faces = object.geometry.faces;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
geometry.vertices.push( new THREE.Vector3() );
geometry.vertices.push( new THREE.Vector3() );
}
}
THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
this.matrixAutoUpdate = false;
this.normalMatrix = new THREE.Matrix3();
this.update();
};
THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
var v1 = new THREE.Vector3();
return function( object ) {
var keys = [ 'a', 'b', 'c', 'd' ];
this.object.updateMatrixWorld( true );
this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
var vertices = this.geometry.vertices;
var verts = this.object.geometry.vertices;
var faces = this.object.geometry.faces;
var worldMatrix = this.object.matrixWorld;
var idx = 0;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
var vertexId = face[ keys[ j ] ];
var vertex = verts[ vertexId ];
var normal = face.vertexNormals[ j ];
vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
v1.add( vertices[ idx ] );
idx = idx + 1;
vertices[ idx ].copy( v1 );
idx = idx + 1;
}
}
this.geometry.verticesNeedUpdate = true;
return this;
}
}());
/**
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
this.object = object;
this.size = ( size !== undefined ) ? size : 1;
var color = ( hex !== undefined ) ? hex : 0x0000ff;
var width = ( linewidth !== undefined ) ? linewidth : 1;
var geometry = new THREE.Geometry();
var vertices = object.geometry.vertices;
var faces = object.geometry.faces;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
geometry.vertices.push( new THREE.Vector3() );
geometry.vertices.push( new THREE.Vector3() );
}
}
THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
this.matrixAutoUpdate = false;
this.update();
};
THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
var v1 = new THREE.Vector3();
return function( object ) {
var keys = [ 'a', 'b', 'c', 'd' ];
this.object.updateMatrixWorld( true );
var vertices = this.geometry.vertices;
var verts = this.object.geometry.vertices;
var faces = this.object.geometry.faces;
var worldMatrix = this.object.matrixWorld;
var idx = 0;
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
var vertexId = face[ keys[ j ] ];
var vertex = verts[ vertexId ];
var tangent = face.vertexTangents[ j ];
vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
v1.add( vertices[ idx ] );
idx = idx + 1;
vertices[ idx ].copy( v1 );
idx = idx + 1;
}
}
this.geometry.verticesNeedUpdate = true;
return this;
}
}());
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.WireframeHelper = function ( object, hex ) {
var color = ( hex !== undefined ) ? hex : 0xffffff;
var edge = [ 0, 0 ], hash = {};
var sortFunction = function ( a, b ) { return a - b };
var keys = [ 'a', 'b', 'c' ];
var geometry = new THREE.BufferGeometry();
if ( object.geometry instanceof THREE.Geometry ) {
var vertices = object.geometry.vertices;
var faces = object.geometry.faces;
var numEdges = 0;
// allocate maximal size
var edges = new Uint32Array( 6 * faces.length );
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( var j = 0; j < 3; j ++ ) {
edge[ 0 ] = face[ keys[ j ] ];
edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
edge.sort( sortFunction );
var key = edge.toString();
if ( hash[ key ] === undefined ) {
edges[ 2 * numEdges ] = edge[ 0 ];
edges[ 2 * numEdges + 1 ] = edge[ 1 ];
hash[ key ] = true;
numEdges ++;
}
}
}
geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
var coords = geometry.attributes.position.array;
for ( var i = 0, l = numEdges; i < l; i ++ ) {
for ( var j = 0; j < 2; j ++ ) {
var vertex = vertices[ edges [ 2 * i + j] ];
var index = 6 * i + 3 * j;
coords[ index + 0 ] = vertex.x;
coords[ index + 1 ] = vertex.y;
coords[ index + 2 ] = vertex.z;
}
}
} else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
var vertices = object.geometry.attributes.position.array;
var indices = object.geometry.attributes.index.array;
var offsets = object.geometry.offsets;
var numEdges = 0;
// allocate maximal size
var edges = new Uint32Array( 2 * indices.length );
for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
var start = offsets[ o ].start;
var count = offsets[ o ].count;
var index = offsets[ o ].index;
for ( var i = start, il = start + count; i < il; i += 3 ) {
for ( var j = 0; j < 3; j ++ ) {
edge[ 0 ] = index + indices[ i + j ];
edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
edge.sort( sortFunction );
var key = edge.toString();
if ( hash[ key ] === undefined ) {
edges[ 2 * numEdges ] = edge[ 0 ];
edges[ 2 * numEdges + 1 ] = edge[ 1 ];
hash[ key ] = true;
numEdges ++;
}
}
}
}
geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
var coords = geometry.attributes.position.array;
for ( var i = 0, l = numEdges; i < l; i ++ ) {
for ( var j = 0; j < 2; j ++ ) {
var index = 6 * i + 3 * j;
var index2 = 3 * edges[ 2 * i + j];
coords[ index + 0 ] = vertices[ index2 ];
coords[ index + 1 ] = vertices[ index2 + 1 ];
coords[ index + 2 ] = vertices[ index2 + 2 ];
}
}
} else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
var vertices = object.geometry.attributes.position.array;
var numEdges = vertices.length / 3;
var numTris = numEdges / 3;
geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
var coords = geometry.attributes.position.array;
for ( var i = 0, l = numTris; i < l; i ++ ) {
for ( var j = 0; j < 3; j ++ ) {
var index = 18 * i + 6 * j;
var index1 = 9 * i + 3 * j;
coords[ index + 0 ] = vertices[ index1 ];
coords[ index + 1 ] = vertices[ index1 + 1 ];
coords[ index + 2 ] = vertices[ index1 + 2 ];
var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
coords[ index + 3 ] = vertices[ index2 ];
coords[ index + 4 ] = vertices[ index2 + 1 ];
coords[ index + 5 ] = vertices[ index2 + 2 ];
}
}
}
THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
this.matrixAutoUpdate = false;
this.matrixWorld = object.matrixWorld;
};
THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ImmediateRenderObject = function () {
THREE.Object3D.call( this );
this.render = function ( renderCallback ) { };
};
THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.LensFlare = function ( texture, size, distance, blending, color ) {
THREE.Object3D.call( this );
this.lensFlares = [];
this.positionScreen = new THREE.Vector3();
this.customUpdateCallback = undefined;
if( texture !== undefined ) {
this.add( texture, size, distance, blending, color );
}
};
THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
/*
* Add: adds another flare
*/
THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
if( size === undefined ) size = -1;
if( distance === undefined ) distance = 0;
if( opacity === undefined ) opacity = 1;
if( color === undefined ) color = new THREE.Color( 0xffffff );
if( blending === undefined ) blending = THREE.NormalBlending;
distance = Math.min( distance, Math.max( 0, distance ) );
this.lensFlares.push( { texture: texture, // THREE.Texture
size: size, // size in pixels (-1 = use texture.width)
distance: distance, // distance (0-1) from light source (0=at light source)
x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
scale: 1, // scale
rotation: 1, // rotation
opacity: opacity, // opacity
color: color, // color
blending: blending } ); // blending
};
/*
* Update lens flares update positions on all flares based on the screen position
* Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
*/
THREE.LensFlare.prototype.updateLensFlares = function () {
var f, fl = this.lensFlares.length;
var flare;
var vecX = -this.positionScreen.x * 2;
var vecY = -this.positionScreen.y * 2;
for( f = 0; f < fl; f ++ ) {
flare = this.lensFlares[ f ];
flare.x = this.positionScreen.x + vecX * flare.distance;
flare.y = this.positionScreen.y + vecY * flare.distance;
flare.wantedRotation = flare.x * Math.PI * 0.25;
flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
}
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MorphBlendMesh = function( geometry, material ) {
THREE.Mesh.call( this, geometry, material );
this.animationsMap = {};
this.animationsList = [];
// prepare default animation
// (all frames played together in 1 second)
var numFrames = this.geometry.morphTargets.length;
var name = "__default";
var startFrame = 0;
var endFrame = numFrames - 1;
var fps = numFrames / 1;
this.createAnimation( name, startFrame, endFrame, fps );
this.setAnimationWeight( name, 1 );
};
THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
var animation = {
startFrame: start,
endFrame: end,
length: end - start + 1,
fps: fps,
duration: ( end - start ) / fps,
lastFrame: 0,
currentFrame: 0,
active: false,
time: 0,
direction: 1,
weight: 1,
directionBackwards: false,
mirroredLoop: false
};
this.animationsMap[ name ] = animation;
this.animationsList.push( animation );
};
THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
var pattern = /([a-z]+)(\d+)/;
var firstAnimation, frameRanges = {};
var geometry = this.geometry;
for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
var morph = geometry.morphTargets[ i ];
var chunks = morph.name.match( pattern );
if ( chunks && chunks.length > 1 ) {
var name = chunks[ 1 ];
var num = chunks[ 2 ];
if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
var range = frameRanges[ name ];
if ( i < range.start ) range.start = i;
if ( i > range.end ) range.end = i;
if ( ! firstAnimation ) firstAnimation = name;
}
}
for ( var name in frameRanges ) {
var range = frameRanges[ name ];
this.createAnimation( name, range.start, range.end, fps );
}
this.firstAnimation = firstAnimation;
};
THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.direction = 1;
animation.directionBackwards = false;
}
};
THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.direction = -1;
animation.directionBackwards = true;
}
};
THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.fps = fps;
animation.duration = ( animation.end - animation.start ) / animation.fps;
}
};
THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.duration = duration;
animation.fps = ( animation.end - animation.start ) / animation.duration;
}
};
THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.weight = weight;
}
};
THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.time = time;
}
};
THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
var time = 0;
var animation = this.animationsMap[ name ];
if ( animation ) {
time = animation.time;
}
return time;
};
THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
var duration = -1;
var animation = this.animationsMap[ name ];
if ( animation ) {
duration = animation.duration;
}
return duration;
};
THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.time = 0;
animation.active = true;
} else {
console.warn( "animation[" + name + "] undefined" );
}
};
THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
var animation = this.animationsMap[ name ];
if ( animation ) {
animation.active = false;
}
};
THREE.MorphBlendMesh.prototype.update = function ( delta ) {
for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
var animation = this.animationsList[ i ];
if ( ! animation.active ) continue;
var frameTime = animation.duration / animation.length;
animation.time += animation.direction * delta;
if ( animation.mirroredLoop ) {
if ( animation.time > animation.duration || animation.time < 0 ) {
animation.direction *= -1;
if ( animation.time > animation.duration ) {
animation.time = animation.duration;
animation.directionBackwards = true;
}
if ( animation.time < 0 ) {
animation.time = 0;
animation.directionBackwards = false;
}
}
} else {
animation.time = animation.time % animation.duration;
if ( animation.time < 0 ) animation.time += animation.duration;
}
var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
var weight = animation.weight;
if ( keyframe !== animation.currentFrame ) {
this.morphTargetInfluences[ animation.lastFrame ] = 0;
this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
this.morphTargetInfluences[ keyframe ] = 0;
animation.lastFrame = animation.currentFrame;
animation.currentFrame = keyframe;
}
var mix = ( animation.time % frameTime ) / frameTime;
if ( animation.directionBackwards ) mix = 1 - mix;
this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
}
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.LensFlarePlugin = function () {
var _gl, _renderer, _precision, _lensFlare = {};
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
_precision = renderer.getPrecision();
_lensFlare.vertices = new Float32Array( 8 + 8 );
_lensFlare.faces = new Uint16Array( 6 );
var i = 0;
_lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
_lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
_lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
_lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
_lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
i = 0;
_lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
_lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
// buffers
_lensFlare.vertexBuffer = _gl.createBuffer();
_lensFlare.elementBuffer = _gl.createBuffer();
_gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
// textures
_lensFlare.tempTexture = _gl.createTexture();
_lensFlare.occlusionTexture = _gl.createTexture();
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
_lensFlare.hasVertexTexture = false;
_lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
} else {
_lensFlare.hasVertexTexture = true;
_lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
}
_lensFlare.attributes = {};
_lensFlare.uniforms = {};
_lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
_lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
_lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
_lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
_lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
_lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
_lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
_lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
_lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
_lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
};
/*
* Render lens flares
* Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
* reads these back and calculates occlusion.
* Then _lensFlare.update_lensFlares() is called to re-position and
* update transparency of flares. Then they are rendered.
*
*/
this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
var flares = scene.__webglFlares,
nFlares = flares.length;
if ( ! nFlares ) return;
var tempPosition = new THREE.Vector3();
var invAspect = viewportHeight / viewportWidth,
halfViewportWidth = viewportWidth * 0.5,
halfViewportHeight = viewportHeight * 0.5;
var size = 16 / viewportHeight,
scale = new THREE.Vector2( size * invAspect, size );
var screenPosition = new THREE.Vector3( 1, 1, 0 ),
screenPositionPixels = new THREE.Vector2( 1, 1 );
var uniforms = _lensFlare.uniforms,
attributes = _lensFlare.attributes;
// set _lensFlare program and reset blending
_gl.useProgram( _lensFlare.program );
_gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
_gl.enableVertexAttribArray( _lensFlare.attributes.uv );
// loop through all lens flares to update their occlusion and positions
// setup gl and common used attribs/unforms
_gl.uniform1i( uniforms.occlusionMap, 0 );
_gl.uniform1i( uniforms.map, 1 );
_gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
_gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
_gl.disable( _gl.CULL_FACE );
_gl.depthMask( false );
var i, j, jl, flare, sprite;
for ( i = 0; i < nFlares; i ++ ) {
size = 16 / viewportHeight;
scale.set( size * invAspect, size );
// calc object screen position
flare = flares[ i ];
tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
tempPosition.applyMatrix4( camera.matrixWorldInverse );
tempPosition.applyProjection( camera.projectionMatrix );
// setup arrays for gl programs
screenPosition.copy( tempPosition )
screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
// screen cull
if ( _lensFlare.hasVertexTexture || (
screenPositionPixels.x > 0 &&
screenPositionPixels.x < viewportWidth &&
screenPositionPixels.y > 0 &&
screenPositionPixels.y < viewportHeight ) ) {
// save current RGB to temp texture
_gl.activeTexture( _gl.TEXTURE1 );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
_gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
// render pink quad
_gl.uniform1i( uniforms.renderType, 0 );
_gl.uniform2f( uniforms.scale, scale.x, scale.y );
_gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
_gl.disable( _gl.BLEND );
_gl.enable( _gl.DEPTH_TEST );
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
// copy result to occlusionMap
_gl.activeTexture( _gl.TEXTURE0 );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
_gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
// restore graphics
_gl.uniform1i( uniforms.renderType, 1 );
_gl.disable( _gl.DEPTH_TEST );
_gl.activeTexture( _gl.TEXTURE1 );
_gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
// update object positions
flare.positionScreen.copy( screenPosition )
if ( flare.customUpdateCallback ) {
flare.customUpdateCallback( flare );
} else {
flare.updateLensFlares();
}
// render flares
_gl.uniform1i( uniforms.renderType, 2 );
_gl.enable( _gl.BLEND );
for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
sprite = flare.lensFlares[ j ];
if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
screenPosition.x = sprite.x;
screenPosition.y = sprite.y;
screenPosition.z = sprite.z;
size = sprite.size * sprite.scale / viewportHeight;
scale.x = size * invAspect;
scale.y = size;
_gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
_gl.uniform2f( uniforms.scale, scale.x, scale.y );
_gl.uniform1f( uniforms.rotation, sprite.rotation );
_gl.uniform1f( uniforms.opacity, sprite.opacity );
_gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
_renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
_renderer.setTexture( sprite.texture, 1 );
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
}
}
}
}
// restore gl
_gl.enable( _gl.CULL_FACE );
_gl.enable( _gl.DEPTH_TEST );
_gl.depthMask( true );
};
function createProgram ( shader, precision ) {
var program = _gl.createProgram();
var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
var prefix = "precision " + precision + " float;\n";
_gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
_gl.shaderSource( vertexShader, prefix + shader.vertexShader );
_gl.compileShader( fragmentShader );
_gl.compileShader( vertexShader );
_gl.attachShader( program, fragmentShader );
_gl.attachShader( program, vertexShader );
_gl.linkProgram( program );
return program;
};
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ShadowMapPlugin = function () {
var _gl,
_renderer,
_depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
_frustum = new THREE.Frustum(),
_projScreenMatrix = new THREE.Matrix4(),
_min = new THREE.Vector3(),
_max = new THREE.Vector3(),
_matrixPosition = new THREE.Vector3();
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
var depthShader = THREE.ShaderLib[ "depthRGBA" ];
var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
_depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
_depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
_depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
_depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
_depthMaterial._shadowPass = true;
_depthMaterialMorph._shadowPass = true;
_depthMaterialSkin._shadowPass = true;
_depthMaterialMorphSkin._shadowPass = true;
};
this.render = function ( scene, camera ) {
if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
this.update( scene, camera );
};
this.update = function ( scene, camera ) {
var i, il, j, jl, n,
shadowMap, shadowMatrix, shadowCamera,
program, buffer, material,
webglObject, object, light,
renderList,
lights = [],
k = 0,
fog = null;
// set GL state for depth map
_gl.clearColor( 1, 1, 1, 1 );
_gl.disable( _gl.BLEND );
_gl.enable( _gl.CULL_FACE );
_gl.frontFace( _gl.CCW );
if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
_gl.cullFace( _gl.FRONT );
} else {
_gl.cullFace( _gl.BACK );
}
_renderer.setDepthTest( true );
// preprocess lights
// - skip lights that are not casting shadows
// - create virtual lights for cascaded shadow maps
for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
light = scene.__lights[ i ];
if ( ! light.castShadow ) continue;
if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
var virtualLight;
if ( ! light.shadowCascadeArray[ n ] ) {
virtualLight = createVirtualLight( light, n );
virtualLight.originalCamera = camera;
var gyro = new THREE.Gyroscope();
gyro.position = light.shadowCascadeOffset;
gyro.add( virtualLight );
gyro.add( virtualLight.target );
camera.add( gyro );
light.shadowCascadeArray[ n ] = virtualLight;
console.log( "Created virtualLight", virtualLight );
} else {
virtualLight = light.shadowCascadeArray[ n ];
}
updateVirtualLight( light, n );
lights[ k ] = virtualLight;
k ++;
}
} else {
lights[ k ] = light;
k ++;
}
}
// render depth map
for ( i = 0, il = lights.length; i < il; i ++ ) {
light = lights[ i ];
if ( ! light.shadowMap ) {
var shadowFilter = THREE.LinearFilter;
if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
shadowFilter = THREE.NearestFilter;
}
var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
light.shadowMatrix = new THREE.Matrix4();
}
if ( ! light.shadowCamera ) {
if ( light instanceof THREE.SpotLight ) {
light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
} else if ( light instanceof THREE.DirectionalLight ) {
light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
} else {
console.error( "Unsupported light type for shadow" );
continue;
}
scene.add( light.shadowCamera );
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
}
if ( light.shadowCameraVisible && ! light.cameraHelper ) {
light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
light.shadowCamera.add( light.cameraHelper );
}
if ( light.isVirtual && virtualLight.originalCamera == camera ) {
updateShadowCamera( camera, light );
}
shadowMap = light.shadowMap;
shadowMatrix = light.shadowMatrix;
shadowCamera = light.shadowCamera;
shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
_matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
shadowCamera.lookAt( _matrixPosition );
shadowCamera.updateMatrixWorld();
shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
if ( light.shadowCameraVisible ) light.cameraHelper.update();
// compute shadow matrix
shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0 );
shadowMatrix.multiply( shadowCamera.projectionMatrix );
shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
// update camera matrices and frustum
_projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// render shadow map
_renderer.setRenderTarget( shadowMap );
_renderer.clear();
// set object matrices & frustum culling
renderList = scene.__webglObjects;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
webglObject.render = false;
if ( object.visible && object.castShadow ) {
if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
webglObject.render = true;
}
}
}
// render regular objects
var objectMaterial, useMorphing, useSkinning;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
// culling is overriden globally for all objects
// while rendering depth map
// need to deal with MeshFaceMaterial somehow
// in that case just use the first of material.materials for now
// (proper solution would require to break objects by materials
// similarly to regular rendering and then set corresponding
// depth materials per each chunk instead of just once per object)
objectMaterial = getObjectMaterial( object );
useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
if ( object.customDepthMaterial ) {
material = object.customDepthMaterial;
} else if ( useSkinning ) {
material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
} else if ( useMorphing ) {
material = _depthMaterialMorph;
} else {
material = _depthMaterial;
}
if ( buffer instanceof THREE.BufferGeometry ) {
_renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
} else {
_renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
}
}
}
// set matrices and render immediate objects
renderList = scene.__webglObjectsImmediate;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
if ( object.visible && object.castShadow ) {
object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
_renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
}
}
}
// restore GL state
var clearColor = _renderer.getClearColor(),
clearAlpha = _renderer.getClearAlpha();
_gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
_gl.enable( _gl.BLEND );
if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
_gl.cullFace( _gl.BACK );
}
};
function createVirtualLight( light, cascade ) {
var virtualLight = new THREE.DirectionalLight();
virtualLight.isVirtual = true;
virtualLight.onlyShadow = true;
virtualLight.castShadow = true;
virtualLight.shadowCameraNear = light.shadowCameraNear;
virtualLight.shadowCameraFar = light.shadowCameraFar;
virtualLight.shadowCameraLeft = light.shadowCameraLeft;
virtualLight.shadowCameraRight = light.shadowCameraRight;
virtualLight.shadowCameraBottom = light.shadowCameraBottom;
virtualLight.shadowCameraTop = light.shadowCameraTop;
virtualLight.shadowCameraVisible = light.shadowCameraVisible;
virtualLight.shadowDarkness = light.shadowDarkness;
virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
virtualLight.pointsWorld = [];
virtualLight.pointsFrustum = [];
var pointsWorld = virtualLight.pointsWorld,
pointsFrustum = virtualLight.pointsFrustum;
for ( var i = 0; i < 8; i ++ ) {
pointsWorld[ i ] = new THREE.Vector3();
pointsFrustum[ i ] = new THREE.Vector3();
}
var nearZ = light.shadowCascadeNearZ[ cascade ];
var farZ = light.shadowCascadeFarZ[ cascade ];
pointsFrustum[ 0 ].set( -1, -1, nearZ );
pointsFrustum[ 1 ].set( 1, -1, nearZ );
pointsFrustum[ 2 ].set( -1, 1, nearZ );
pointsFrustum[ 3 ].set( 1, 1, nearZ );
pointsFrustum[ 4 ].set( -1, -1, farZ );
pointsFrustum[ 5 ].set( 1, -1, farZ );
pointsFrustum[ 6 ].set( -1, 1, farZ );
pointsFrustum[ 7 ].set( 1, 1, farZ );
return virtualLight;
}
// Synchronize virtual light with the original light
function updateVirtualLight( light, cascade ) {
var virtualLight = light.shadowCascadeArray[ cascade ];
virtualLight.position.copy( light.position );
virtualLight.target.position.copy( light.target.position );
virtualLight.lookAt( virtualLight.target );
virtualLight.shadowCameraVisible = light.shadowCameraVisible;
virtualLight.shadowDarkness = light.shadowDarkness;
virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
var nearZ = light.shadowCascadeNearZ[ cascade ];
var farZ = light.shadowCascadeFarZ[ cascade ];
var pointsFrustum = virtualLight.pointsFrustum;
pointsFrustum[ 0 ].z = nearZ;
pointsFrustum[ 1 ].z = nearZ;
pointsFrustum[ 2 ].z = nearZ;
pointsFrustum[ 3 ].z = nearZ;
pointsFrustum[ 4 ].z = farZ;
pointsFrustum[ 5 ].z = farZ;
pointsFrustum[ 6 ].z = farZ;
pointsFrustum[ 7 ].z = farZ;
}
// Fit shadow camera's ortho frustum to camera frustum
function updateShadowCamera( camera, light ) {
var shadowCamera = light.shadowCamera,
pointsFrustum = light.pointsFrustum,
pointsWorld = light.pointsWorld;
_min.set( Infinity, Infinity, Infinity );
_max.set( -Infinity, -Infinity, -Infinity );
for ( var i = 0; i < 8; i ++ ) {
var p = pointsWorld[ i ];
p.copy( pointsFrustum[ i ] );
THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
p.applyMatrix4( shadowCamera.matrixWorldInverse );
if ( p.x < _min.x ) _min.x = p.x;
if ( p.x > _max.x ) _max.x = p.x;
if ( p.y < _min.y ) _min.y = p.y;
if ( p.y > _max.y ) _max.y = p.y;
if ( p.z < _min.z ) _min.z = p.z;
if ( p.z > _max.z ) _max.z = p.z;
}
shadowCamera.left = _min.x;
shadowCamera.right = _max.x;
shadowCamera.top = _max.y;
shadowCamera.bottom = _min.y;
// can't really fit near/far
//shadowCamera.near = _min.z;
//shadowCamera.far = _max.z;
shadowCamera.updateProjectionMatrix();
}
// For the moment just ignore objects that have multiple materials with different animation methods
// Only the first material will be taken into account for deciding which depth material to use for shadow maps
function getObjectMaterial( object ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ 0 ]
: object.material;
};
};
THREE.ShadowMapPlugin.__projector = new THREE.Projector();
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
THREE.SpritePlugin = function () {
var _gl, _renderer, _texture;
var vertices, faces, vertexBuffer, elementBuffer;
var program, attributes, uniforms;
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
vertices = new Float32Array( [
- 0.5, - 0.5, 0, 0,
0.5, - 0.5, 1, 0,
0.5, 0.5, 1, 1,
- 0.5, 0.5, 0, 1
] );
faces = new Uint16Array( [
0, 1, 2,
0, 2, 3
] );
vertexBuffer = _gl.createBuffer();
elementBuffer = _gl.createBuffer();
_gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
program = createProgram();
attributes = {
position: _gl.getAttribLocation ( program, 'position' ),
uv: _gl.getAttribLocation ( program, 'uv' )
};
uniforms = {
uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
uvScale: _gl.getUniformLocation( program, 'uvScale' ),
rotation: _gl.getUniformLocation( program, 'rotation' ),
scale: _gl.getUniformLocation( program, 'scale' ),
color: _gl.getUniformLocation( program, 'color' ),
map: _gl.getUniformLocation( program, 'map' ),
opacity: _gl.getUniformLocation( program, 'opacity' ),
modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
fogType: _gl.getUniformLocation( program, 'fogType' ),
fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
fogNear: _gl.getUniformLocation( program, 'fogNear' ),
fogFar: _gl.getUniformLocation( program, 'fogFar' ),
fogColor: _gl.getUniformLocation( program, 'fogColor' ),
alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
};
var canvas = document.createElement( 'canvas' );
canvas.width = 8;
canvas.height = 8;
var context = canvas.getContext( '2d' );
context.fillStyle = '#ffffff';
context.fillRect( 0, 0, canvas.width, canvas.height );
_texture = new THREE.Texture( canvas );
_texture.needsUpdate = true;
};
this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
var sprites = scene.__webglSprites,
nSprites = sprites.length;
if ( ! nSprites ) return;
// setup gl
_gl.useProgram( program );
_gl.enableVertexAttribArray( attributes.position );
_gl.enableVertexAttribArray( attributes.uv );
_gl.disable( _gl.CULL_FACE );
_gl.enable( _gl.BLEND );
_gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
_gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
_gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
_gl.activeTexture( _gl.TEXTURE0 );
_gl.uniform1i( uniforms.map, 0 );
var oldFogType = 0;
var sceneFogType = 0;
var fog = scene.fog;
if ( fog ) {
_gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
if ( fog instanceof THREE.Fog ) {
_gl.uniform1f( uniforms.fogNear, fog.near );
_gl.uniform1f( uniforms.fogFar, fog.far );
_gl.uniform1i( uniforms.fogType, 1 );
oldFogType = 1;
sceneFogType = 1;
} else if ( fog instanceof THREE.FogExp2 ) {
_gl.uniform1f( uniforms.fogDensity, fog.density );
_gl.uniform1i( uniforms.fogType, 2 );
oldFogType = 2;
sceneFogType = 2;
}
} else {
_gl.uniform1i( uniforms.fogType, 0 );
oldFogType = 0;
sceneFogType = 0;
}
// update positions and sort
var i, sprite, material, fogType, scale = [];
for( i = 0; i < nSprites; i ++ ) {
sprite = sprites[ i ];
material = sprite.material;
if ( sprite.visible === false ) continue;
sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
}
sprites.sort( painterSortStable );
// render all sprites
for( i = 0; i < nSprites; i ++ ) {
sprite = sprites[ i ];
if ( sprite.visible === false ) continue;
material = sprite.material;
_gl.uniform1f( uniforms.alphaTest, material.alphaTest );
_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
scale[ 0 ] = sprite.scale.x;
scale[ 1 ] = sprite.scale.y;
if ( scene.fog && material.fog ) {
fogType = sceneFogType;
} else {
fogType = 0;
}
if ( oldFogType !== fogType ) {
_gl.uniform1i( uniforms.fogType, fogType );
oldFogType = fogType;
}
if ( material.map !== null ) {
_gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
_gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
} else {
_gl.uniform2f( uniforms.uvOffset, 0, 0 );
_gl.uniform2f( uniforms.uvScale, 1, 1 );
}
_gl.uniform1f( uniforms.opacity, material.opacity );
_gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
_gl.uniform1f( uniforms.rotation, material.rotation );
_gl.uniform2fv( uniforms.scale, scale );
_renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
_renderer.setDepthTest( material.depthTest );
_renderer.setDepthWrite( material.depthWrite );
if ( material.map && material.map.image && material.map.image.width ) {
_renderer.setTexture( material.map, 0 );
} else {
_renderer.setTexture( _texture, 0 );
}
_gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
}
// restore gl
_gl.enable( _gl.CULL_FACE );
};
function createProgram () {
var program = _gl.createProgram();
var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
_gl.shaderSource( vertexShader, [
'precision ' + _renderer.getPrecision() + ' float;',
'uniform mat4 modelViewMatrix;',
'uniform mat4 projectionMatrix;',
'uniform float rotation;',
'uniform vec2 scale;',
'uniform vec2 uvOffset;',
'uniform vec2 uvScale;',
'attribute vec2 position;',
'attribute vec2 uv;',
'varying vec2 vUV;',
'void main() {',
'vUV = uvOffset + uv * uvScale;',
'vec2 alignedPosition = position * scale;',
'vec2 rotatedPosition;',
'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
'vec4 finalPosition;',
'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
'finalPosition.xy += rotatedPosition;',
'finalPosition = projectionMatrix * finalPosition;',
'gl_Position = finalPosition;',
'}'
].join( '\n' ) );
_gl.shaderSource( fragmentShader, [
'precision ' + _renderer.getPrecision() + ' float;',
'uniform vec3 color;',
'uniform sampler2D map;',
'uniform float opacity;',
'uniform int fogType;',
'uniform vec3 fogColor;',
'uniform float fogDensity;',
'uniform float fogNear;',
'uniform float fogFar;',
'uniform float alphaTest;',
'varying vec2 vUV;',
'void main() {',
'vec4 texture = texture2D( map, vUV );',
'if ( texture.a < alphaTest ) discard;',
'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
'if ( fogType > 0 ) {',
'float depth = gl_FragCoord.z / gl_FragCoord.w;',
'float fogFactor = 0.0;',
'if ( fogType == 1 ) {',
'fogFactor = smoothstep( fogNear, fogFar, depth );',
'} else {',
'const float LOG2 = 1.442695;',
'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
'}',
'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
'}',
'}'
].join( '\n' ) );
_gl.compileShader( vertexShader );
_gl.compileShader( fragmentShader );
_gl.attachShader( program, vertexShader );
_gl.attachShader( program, fragmentShader );
_gl.linkProgram( program );
return program;
};
function painterSortStable ( a, b ) {
if ( a.z !== b.z ) {
return b.z - a.z;
} else {
return b.id - a.id;
}
};
};
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.DepthPassPlugin = function () {
this.enabled = false;
this.renderTarget = null;
var _gl,
_renderer,
_depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
_frustum = new THREE.Frustum(),
_projScreenMatrix = new THREE.Matrix4();
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
var depthShader = THREE.ShaderLib[ "depthRGBA" ];
var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
_depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
_depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
_depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
_depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
_depthMaterial._shadowPass = true;
_depthMaterialMorph._shadowPass = true;
_depthMaterialSkin._shadowPass = true;
_depthMaterialMorphSkin._shadowPass = true;
};
this.render = function ( scene, camera ) {
if ( ! this.enabled ) return;
this.update( scene, camera );
};
this.update = function ( scene, camera ) {
var i, il, j, jl, n,
program, buffer, material,
webglObject, object, light,
renderList,
fog = null;
// set GL state for depth map
_gl.clearColor( 1, 1, 1, 1 );
_gl.disable( _gl.BLEND );
_renderer.setDepthTest( true );
// update scene
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
// update camera matrices and frustum
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// render depth map
_renderer.setRenderTarget( this.renderTarget );
_renderer.clear();
// set object matrices & frustum culling
renderList = scene.__webglObjects;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
webglObject.render = false;
if ( object.visible ) {
if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
webglObject.render = true;
}
}
}
// render regular objects
var objectMaterial, useMorphing, useSkinning;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
// todo: create proper depth material for particles
if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
objectMaterial = getObjectMaterial( object );
if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
if ( object.customDepthMaterial ) {
material = object.customDepthMaterial;
} else if ( useSkinning ) {
material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
} else if ( useMorphing ) {
material = _depthMaterialMorph;
} else {
material = _depthMaterial;
}
if ( buffer instanceof THREE.BufferGeometry ) {
_renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
} else {
_renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
}
}
}
// set matrices and render immediate objects
renderList = scene.__webglObjectsImmediate;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
if ( object.visible ) {
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
_renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
}
}
// restore GL state
var clearColor = _renderer.getClearColor(),
clearAlpha = _renderer.getClearAlpha();
_gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
_gl.enable( _gl.BLEND );
};
// For the moment just ignore objects that have multiple materials with different animation methods
// Only the first material will be taken into account for deciding which depth material to use
function getObjectMaterial( object ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ 0 ]
: object.material;
};
};
/**
* @author mikael emtinger / http://gomo.se/
*/
THREE.ShaderFlares = {
'lensFlareVertexTexture': {
vertexShader: [
"uniform lowp int renderType;",
"uniform vec3 screenPosition;",
"uniform vec2 scale;",
"uniform float rotation;",
"uniform sampler2D occlusionMap;",
"attribute vec2 position;",
"attribute vec2 uv;",
"varying vec2 vUV;",
"varying float vVisibility;",
"void main() {",
"vUV = uv;",
"vec2 pos = position;",
"if( renderType == 2 ) {",
"vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
"visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
"vVisibility = visibility.r / 9.0;",
"vVisibility *= 1.0 - visibility.g / 9.0;",
"vVisibility *= visibility.b / 9.0;",
"vVisibility *= 1.0 - visibility.a / 9.0;",
"pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
"pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
"}",
"gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform lowp int renderType;",
"uniform sampler2D map;",
"uniform float opacity;",
"uniform vec3 color;",
"varying vec2 vUV;",
"varying float vVisibility;",
"void main() {",
// pink square
"if( renderType == 0 ) {",
"gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
// restore
"} else if( renderType == 1 ) {",
"gl_FragColor = texture2D( map, vUV );",
// flare
"} else {",
"vec4 texture = texture2D( map, vUV );",
"texture.a *= opacity * vVisibility;",
"gl_FragColor = texture;",
"gl_FragColor.rgb *= color;",
"}",
"}"
].join( "\n" )
},
'lensFlare': {
vertexShader: [
"uniform lowp int renderType;",
"uniform vec3 screenPosition;",
"uniform vec2 scale;",
"uniform float rotation;",
"attribute vec2 position;",
"attribute vec2 uv;",
"varying vec2 vUV;",
"void main() {",
"vUV = uv;",
"vec2 pos = position;",
"if( renderType == 2 ) {",
"pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
"pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
"}",
"gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"precision mediump float;",
"uniform lowp int renderType;",
"uniform sampler2D map;",
"uniform sampler2D occlusionMap;",
"uniform float opacity;",
"uniform vec3 color;",
"varying vec2 vUV;",
"void main() {",
// pink square
"if( renderType == 0 ) {",
"gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
// restore
"} else if( renderType == 1 ) {",
"gl_FragColor = texture2D( map, vUV );",
// flare
"} else {",
"float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
"visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
"visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
"visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
"visibility = ( 1.0 - visibility / 4.0 );",
"vec4 texture = texture2D( map, vUV );",
"texture.a *= opacity * visibility;",
"gl_FragColor = texture;",
"gl_FragColor.rgb *= color;",
"}",
"}"
].join( "\n" )
}
};
|
/**
* Copyright (c) Microsoft Corporation
* All Rights Reserved
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the 'Software'), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
* OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
var test_parameters = {
v1_params: {
tenantID: '<fill-in>',
clientID: '<fill-in>',
clientSecret: '<fill-in>=',
username: '<fill-in>',
password: '<fill-in>'
},
v2_params: {
tenantID: '<fill-in>',
clientID: '<fill-in>',
clientSecret: '<fill-in>',
username: '<fill-in>',
password: '<fill-in>'
},
b2c_params: {
tenantID: '<fill-in>',
clientID: '<fill-in>',
clientSecret: '<fill-in>',
username: '<fill-in>',
password: '<fill-in>',
scopeForBearer: ['<fill-in>'],
scopeForOIDC: ['<fill-in>']
}
};
exports.is_test_parameters_completed = false;
exports.test_parameters = test_parameters;
|
(function() {
// some API urls
var google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&callback={callback}&rsz=large&q={query}",
questions = "http://api.stackoverflow.com/1.0/questions/{id}?key={key}&body=true&jsonp={callback}",
questionsTagged = "http://api.stackoverflow.com/1.0/questions/?key={key}&tagged={tagged}&body=true&jsonp={callback}",
search = "http://api.stackoverflow.com/1.0/search/?key={key}&intitle={intitle}¬tagged={nottagged}&tagged={tagged}&body=true&jsonp={callback}",
unansweredQuestionsTagged = "http://api.stackoverflow.com/1.0/questions/unanswered/?key={key}&tagged={tagged}&body=true&jsonp={callback}",
questionsByUser = "http://api.stackoverflow.com/1.0/users/{id}/questions?key={key}&body=true&jsonp={callback}",
// prevent loading more than once
isLoaded,
// each call creates a unique jsonp callback
jsonpCount = 0,
// for matching the question id inside a stackexchange question url
regexQuestion = /\/questions\/([0-9]*)\//ig,
// those listening for the loaded event
callbacks = [];
function domLoaded() {
// based on the proven method of simulating DOMContentLoaded in IE
if (window.addEventListener) {
window.addEventListener("load", loaded, false);
}
else {
window.attachEvent("onload", loaded);
}
var check;
if (window.attachEvent) {
if ((window == window.top) && document.documentElement.doScroll) {
var timeout, er, el = document.createElement("div");
check = function() {
try {
el.doScroll("left");
}
catch (er) {
timeout = window.setTimeout(check, 0);
return;
}
el = null;
loaded();
}
check();
}
else {
document.onreadystatechange = function() {
if (/loaded|complete/.test(document.readyState)) {
loaded();
}
};
}
}
else if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", loaded, false);
}
}
function loaded() {
// called when the DOM is ready
if (!isLoaded) {
isLoaded = true;
for (var i = 0, l = callbacks.length; i < l; i++) {
callbacks[i]();
}
}
}
function jsonp(url, params, callback) {
// begin a jsonp request and foward the response
var jsonp = "_jsonp" + jsonpCount++;
url = url
.replace("{callback}", "stackunderflow." + jsonp)
.replace("{key}", su.appId);
if (params) {
for (var name in params) {
url = url.replace("{" + name + "}", params[name]);
}
}
su[jsonp] = function(data) {
delete su[jsonp];
su.loaded(function() {
callback(data);
});
};
var scr = document.createElement("script");
scr.type = "text/javascript";
scr.src = url;
// insertBefore in case this is performed inline in the head
var head = document.getElementsByTagName("head")[0];
head.insertBefore(scr, head.firstChild);
}
function getUniqueQuestions(searchResults) {
// created an array of unique question ids
// from a set of google search results
var questions = [], index = {};
for (var i = 0, l = searchResults.length; i < l; i++) {
regexQuestion.lastIndex = 0;
var url = searchResults[i].unescapedUrl,
match = regexQuestion.exec(url);
if ( match && match[1] ) {
var questionId = parseInt(match[1]);
if (!index[questionId]) {
questions.push(questionId);
index[questionId] = 1;
}
}
}
return questions;
}
function pad(num) {
var s = num+"";
return s.length === 2 ? s : ("0" + s);
}
function applyTemplate(html, obj) {
var i, l, regexTokens = new RegExp("\\{([^}]*)\\}", "g"), match, token,
tokenValues = {
site: su.site
};
do {
match = regexTokens.exec(html);
token = match ? match[1] : null;
if (token) {
var index = token.indexOf(":"),
filter = null;
if (index > -1) {
filter = token.substr(0, index);
token = token.substr(index + 1);
}
var parts = token === "=" ? [] : token.split('.'),
step = obj;
for (var i = 0, l = parts.length; i < l; i++) {
step = step[parts[i]];
if (typeof step === "undefined") break;
}
if (filter) {
var template;
if (filter.indexOf("template-") > -1) {
template = filter.substr("template-".length);
filter = "template";
}
filter = su.filters[filter];
if (filter) {
step = filter(step, template);
}
}
if (typeof step !== "undefined") {
tokenValues[match[1]] = step;
}
}
}
while (token);
for (token in tokenValues) {
html = html.replace(new RegExp("\\{" + token.replace(/([\.\:\-])/g, '\\$1') + "\\}","g"), tokenValues[token]);
}
return html;
}
function append(target, html) {
var div = document.createElement("div");
div.innerHTML = html;
while(div.firstChild) {
target.appendChild(div.firstChild);
}
}
function execQuestions(url, params, complete) {
var renderArgs,
ctx = { render: function() { renderArgs = arguments; } };
jsonp(url, params, function(questions) {
if (complete) complete(questions);
if (renderArgs) {
renderArgs = Array.prototype.slice.apply(renderArgs);
renderArgs.splice(0, 0, questions);
su.render.questions.apply(null, renderArgs);
}
});
return ctx;
}
var su = window.stackunderflow = {
appId: "oxXcnoD51kKE-crj7TadaA",
site: "http://stackoverflow.com",
loaded: function(callback) {
if (isLoaded) {
callback();
}
else {
callbacks.push(callback);
}
},
googleQuestions: function(term, complete) {
var renderArgs,
ctx = { render: function() { renderArgs = arguments; } };
var site = su.site + "/questions";
term = term || ('"' + window.location + '"');
jsonp(google, {
query: "site:" + site + " " + term
},
function(data) {
var questions = getUniqueQuestions(data.responseData.results);
if (questions.length) {
su.getQuestions(questions, function(questions) {
if (complete) complete(questions);
if (renderArgs) {
renderArgs = Array.prototype.slice.apply(renderArgs);
renderArgs.splice(0, 0, questions);
su.render.questions.apply(null, renderArgs);
}
});
}
});
return ctx;
},
getQuestions: function(questionIds, complete) {
return execQuestions(questions, { id: questionIds.join(';') }, complete);
},
searchQuestions: function(intitle, tagged, notTagged, complete) {
return execQuestions(search, { tagged: tagged, nottagged: notTagged, intitle: intitle }, complete);
},
getQuestionsWithTags: function(tags, onlyUnanswered, complete) {
return execQuestions(onlyUnanswered ? unansweredQuestionsTagged : questionsTagged,
{ tagged: tags }, complete);
},
getQuestionsByUser: function(userIds, complete) {
return execQuestions(questionsByUser, { id: userIds instanceof Array ? userIds.join(';') : userIds }, complete);
},
render: {
questions: function(questions, target, template) {
template = template || "question";
if (typeof target === "string") {
if (target.charAt(0) === "#") target = target.substr(1);
target = document.getElementById(target);
}
var html = "";
questions = questions.questions;
if (questions) {
for (var i = 0, l = questions.length; i < l; i++) {
html += applyTemplate(su.templates[template], questions[i]);
}
}
append(target, html);
}
},
templates: {
tag: '<a href="{site}/questions/tagged/{=}" class="se-post-tag" title="show questions tagged \'{=}\'" rel="tag">{=}</a> ',
question: '<div class="se-question-summary" id="question-summary-{question_id}"> \
<div onclick="window.location.href=\'{site}{question_answers_url}\'" class="se-cp se-statscontainer"> \
<div class="statsarrow"></div> \
<div class="se-stats"> \
<div class="se-vote"> \
<div class="se-votes"> \
<span class="se-mini-counts vote-count-post"><strong>{up_vote_count}</strong></span> \
<div class="viewcount">vote{pluralize:up_vote_count}</div> \
</div> \
</div> \
<div class="se-status {acceptedclass:=}"> \
<strong>{answer_count}</strong>answer{pluralize:answer_count} \
</div> \
</div> \
<div class="se-views {viewcountcolor:view_count}" title="{view_count}{viewcountk:view_count} view{pluralize:view_count}">{view_count} views</div> \
</div> \
<div class="se-summary"> \
<h3><a href="{site}{question_answers_url}" class="se-question-hyperlink" title="{title}">{title}</a></h3> \
<div class="excerpt"> {summarize:body} </div> \
<div class="se-tags"> {template-tag:tags} </div> \
<div class="se-started"> \
<div class="se-user-info"><div class="user-action-time">asked <span title="{date:last_activity_date}">{date:last_activity_date}</span></div> \
<div class="user-gravatar32"><a href="{site}/users/{owner.user_id}/{owner.display_name}"><div><img src="http://www.gravatar.com/avatar/{owner.email_hash}?s=32&d=identicon&r=PG" alt=""></div></a></div> \
<div class="se-user-details"><a style="display:{ifdef:owner}" href="{site}/users/{owner.user_id}/{owner.display_name}">{owner.display_name}</a> <br/> <span style="display:{ifdef:owner}" class="se-reputation-score" title="reputation score">{owner.reputation}</span></div> \
</div> \
</div> \
</div> \
</div> '
},
filters: {
date: function(value) {
var date = new Date(parseInt(value)*1000);
return date.getFullYear() + "-" + pad(date.getMonth()+1) + "-" + pad(date.getDate());
},
template: function(value, templateName) {
var template = su.templates[templateName],
html = "";
if (template) {
for (i = 0, l = value.length; i < l; i++) {
html += applyTemplate(template, value[i]);
}
}
return html;
},
acceptedclass: function(value) {
return value.accepted_answer_id ? "se-answered-accepted" :
(value.answer_count ? "se-answered" : "se-unanswered");
},
viewcountnumber: function(value) {
return value > 999 ? Math.round(value/1000) : value;
},
viewcountk: function(value) {
return value > 999 ? "k" : "";
},
summarize: function(value){
var max_desc = 220;
var strip_lines = /(\n|\r|<br>|<br\/>|<br \/>|<p>|<\/p>|<\/a>|<code>|<\/code>|<pre>|<\/pre>)/img;
var strip_links = /<a href="[^>]*>/img;
value = value.replace(strip_lines, " ");
value = value.replace(strip_links, " ");
if(value.length > max_desc){
return value.substr(0, max_desc);
}else{
return value;
}
},
pluralize: function(value){
return value == 1 || value == "1" ? "" : "s";
},
viewcountcolor: function(value) {
if(value >= 100000)
return "se-views-100k";
else if (value >= 10000)
return "se-views-10k";
else if (value >= 1000)
return "se-views-1k"
else
return "";
},
ifdef: function(value) {
return typeof value === "undefined" ? "none" : "";
}
}
};
domLoaded();
})();
|
require('./vector/main');
window.initGoogleMaps = require('./google/main'); |
// flow-typed signature: a49a6c96fe8a8bb3330cce2028588f4c
// flow-typed version: de5b3a01c6/redux_v4.x.x/flow_>=v0.89.x
declare module 'redux' {
/*
S = State
A = Action
D = Dispatch
*/
declare export type Action<T> = {
type: T
}
declare export type DispatchAPI<A> = (action: A) => A;
declare export type Dispatch<A: { type: * }> = DispatchAPI<A>;
declare export type MiddlewareAPI<S, A, D = Dispatch<A>> = {
dispatch: D,
getState(): S,
};
declare export type Store<S, A, D = Dispatch<A>> = {
// rewrite MiddlewareAPI members in order to get nicer error messages (intersections produce long messages)
dispatch: D,
getState(): S,
subscribe(listener: () => void): () => void,
replaceReducer(nextReducer: Reducer<S, A>): void,
};
declare export type Reducer<S, A> = (state: S | void, action: A) => S;
declare export type CombinedReducer<S, A> = (
state: ($Shape<S> & {}) | void,
action: A
) => S;
declare export type Middleware<S, A, D = Dispatch<A>> = (
api: MiddlewareAPI<S, A, D>
) => (next: D) => D;
declare export type StoreCreator<S, A, D = Dispatch<A>> = {
(reducer: Reducer<S, A>, enhancer?: StoreEnhancer<S, A, D>): Store<S, A, D>,
(
reducer: Reducer<S, A>,
preloadedState: S,
enhancer?: StoreEnhancer<S, A, D>
): Store<S, A, D>,
};
declare export type StoreEnhancer<S, A, D = Dispatch<A>> = (
next: StoreCreator<S, A, D>
) => StoreCreator<S, A, D>;
declare export function createStore<S, A, D>(
reducer: Reducer<S, A>,
enhancer?: StoreEnhancer<S, A, D>
): Store<S, A, D>;
declare export function createStore<S, A, D>(
reducer: Reducer<S, A>,
preloadedState?: S,
enhancer?: StoreEnhancer<S, A, D>
): Store<S, A, D>;
declare export function applyMiddleware<S, A, D>(
...middlewares: Array<Middleware<S, A, D>>
): StoreEnhancer<S, A, D>;
declare export type ActionCreator<A, B> = (...args: Array<B>) => A;
declare export type ActionCreators<K, A> = {
[key: K]: ActionCreator<A, any>,
};
declare export function bindActionCreators<
A,
C: ActionCreator<A, any>,
D: DispatchAPI<A>
>(
actionCreator: C,
dispatch: D
): C;
declare export function bindActionCreators<
A,
K,
C: ActionCreators<K, A>,
D: DispatchAPI<A>
>(
actionCreators: C,
dispatch: D
): C;
declare export function combineReducers<O: {}, A>(
reducers: O
): CombinedReducer<$ObjMap<O, <S>(r: Reducer<S, any>) => S>, A>;
declare export var compose: $Compose;
}
|
exports.names = ['settings', 'set'];
exports.hidden = true;
exports.enabled = true;
exports.cdAll = 10;
exports.cdUser = 10;
exports.cdStaff = 5;
exports.minRole = PERMISSIONS.BOUNCER_PLUS;
exports.handler = function (data) {
var input = data.message.split(' ');
var logMessage = '';
var chatMessage = '';
var result;
var translation = [
{ configName: 'djIdleAfterMins', chatName: 'djidle', english: 'DJ Idle Seconds', notify: true },
{
configName: 'djIdleMinQueueLengthToEnforce',
chatName: 'minidlequeue',
english: 'Min Idle Queue',
notify: false
},
{ configName: 'djCycleMaxQueueLength', chatName: 'maxcyclequeue', english: 'Max Cycle Queue', notify: false },
{ configName: 'maxSongLengthSecs', chatName: 'maxsonglength', english: 'Max Song Seconds', notify: true },
{ configName: 'minSongReleaseDate', chatName: 'minreleasedate', english: 'Min Release Date ', notify: true },
{ configName: 'maxSongReleaseDate', chatName: 'maxreleasedate', english: 'Max Release Date', notify: true },
{ configName: 'prohibitDownvoteInQueue', chatName: 'nomehsinqueue', english: 'No Mehs in Queue', notify: false },
{ configName: 'quietMode', chatName: 'quietmode', english: 'Quiet Mode', notify: false },
{ configName: 'verboseLogging', chatName: 'verboselogging', english: 'Verbose Logging', notify: false }
];
if (input.length < 3) {
for (var key in config.queue) {
result = _.findWhere(translation, { configName: key });
if (config.queue.hasOwnProperty(key) && result) {
chatMessage += result.chatName + ': ' + config.queue[key] + ', ';
}
}
for (var key in config) {
result = _.findWhere(translation, { configName: key });
if (config.hasOwnProperty(key) && result) {
chatMessage += result.chatName + ': ' + config[key] + ', ';
}
}
if (chatMessage != '') {
bot.sendChat('Settings: ' + trimCommas(chatMessage));
}
}
else {
var setting = input[1];
var newValue = _.rest(input, 2).join(' ').trim();
result = _.findWhere(translation, { chatName: setting });
if (result !== undefined) {
if (newValue === 'false') {
newValue = new Boolean(false);
} else if (newValue === 'true') {
newValue = new Boolean(true);
} else if (newValue.match(/^\d+$/)) {
newValue = parseInt(newValue);
}
if (config.queue.hasOwnProperty(result.configName)) {
config.queue[result.configName] = newValue;
}
if (config.hasOwnProperty(result.configName)) {
config[result.configName] = newValue;
}
if (result.notify) {
bot.sendChat(result.english + ' now set to: ' + newValue + ' @djs');
}
logMessage = '[CONFIG] ' + data.from.username + ' set `' + result.configName + '` to `' + newValue + '`';
console.log(logMessage);
sendToWebhooks(logMessage);
}
else {
bot.sendChat('unknown setting: ' + setting);
}
// @TODO - need to merge down configState and settings{}
settings.maxsonglength = parseInt(config.queue.maxSongLengthSecs);
settings.maxdjidletime = parseInt(config.queue.djIdleAfterMins) * 60;
settings.djidleminqueue = parseInt(config.queue.djIdleMinQueueLengthToEnforce);
settings.djcyclemaxqueue = parseInt(config.queue.djCycleMaxQueueLength);
writeConfigState();
}
};
|
import { expect } from 'chai';
import typeMapper from '../src/typeMapper';
import {
BOOLEAN,
ENUM,
FLOAT,
INTEGER,
STRING
} from 'sequelize';
import {
GraphQLString,
GraphQLInt,
GraphQLBoolean,
GraphQLFloat,
GraphQLEnumType,
GraphQLList
} from 'graphql';
describe('typeMapper', () => {
// TODO write tests for typeMapper
})
|
var fs = require('fs');
var path = require('path');
var Sequelize = require('Sequelize');
var _ = require('lodash');
var config = require('./config');
var db = {};
var sequelize = new Sequelize(config.db.dbName, config.db.username, config.db.password, {
dialect: config.db.dialect,
port: config.db.port,
logging : false
});
sequelize.authenticate().complete(function(err) {
if (!!err) {
logger.error('Unable to connect to the database:', err)
} else {
logger.info('Database connection has been established successfully.')
}
});
// loop through all files in models directory ignoring hidden files and this file
fs.readdirSync(config.modelsDir)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file !== 'session.server.model.js');
})
// import model files and save model names
.forEach(function(file) {
logger.debug('Loading model file ' + file);
var model = sequelize.import(path.join(config.modelsDir, file));
db[model.name] = model;
})
// invoke associations on each of the models
Object.keys(db).forEach(function(modelName) {
if (db[modelName].options.hasOwnProperty('associate')) {
db[modelName].options.associate(db)
}
});
// Synchronizing any model changes with database.
// WARNING: this will DROP your database everytime you re-run your application
sequelize
.sync({force: false})
.complete(function(err){
if(err) logger.error("An error occured %j",err);
else logger.info("Database synchronized");
});
// assign the sequelize variables to the db object and returning the db.
module.exports = _.extend({
sequelize: sequelize,
Sequelize: Sequelize
}, db);
|
const Audio = {
play() {},
};
export default Audio;
|
export * from './class'; |
import React from 'react';
import ReactDOM from 'react-dom';
module.exports = React.createClass({
displayName: 'Portal',
portalElement: null,
componentDidMount () {
let el = document.createElement('div');
document.body.appendChild(el);
this.portalElement = el;
this.componentDidUpdate();
},
componentWillUnmount () {
document.body.removeChild(this.portalElement);
},
componentDidUpdate () {
ReactDOM.render(<div {...this.props}>{this.props.children}</div>, this.portalElement);
},
getPortalDOMNode () {
return this.portalElement;
},
render () {
return null;
},
});
|
'use strict';
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var ohm = require('..');
var test = require('tape-catch');
// --------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------
function toGrammar(recipeString) {
return ohm.makeRecipe(eval(recipeString)); // eslint-disable-line no-eval
}
// --------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------
test('simple recipes', function(t) {
var g = ohm.grammar('G{}');
t.ok(toGrammar(g.toRecipe()).match('', 'end'), 'grammar with no rules');
g = ohm.grammar('G { start = end }');
t.ok(toGrammar(g.toRecipe()).match('', 'start'), 'grammar with one rule');
g = ohm.grammar('MyGrammar { start = x\n x = "a" }');
t.ok(toGrammar(g.toRecipe()).match('a', 'start'), 'grammar with multiple rules');
t.end();
});
test('recipes with supergrammars', function(t) {
var ns = ohm.createNamespace();
ns.G = ohm.grammar('G { start = end }');
ns.G2 = ohm.grammar('G2 <: G { start := "a" }', ns);
t.ok(toGrammar(ns.G2.toRecipe()).match('a', 'start'), 'one level of inheritance');
ns.G3 = ohm.grammar('G3 <: G2 { begin = a b\n a = "a"\n b = "b" }', ns);
t.ok(toGrammar(ns.G3.toRecipe()).match('ab', 'begin'), 'two levels of inheritance');
t.end();
});
|
//! ScriptApp.Test.debug.js
//
(function() {
function executeScript() {
////////////////////////////////////////////////////////////////////////////////
// IBase
window.IBase = function() {
};
IBase.prototype = {
print : null
}
IBase.registerInterface('IBase');
}
ss.loader.registerScript('ScriptApp.Test', [], executeScript);
})();
//! This script was generated using Script# v0.6.3.0
|
/**
* Geometry functions simplifier.
*
* @type {{normalizeAngle: Function, angleDifference: Function}}
*/
var Geometry = {
normalizeAngle: function(angle) {
return (angle + Math.PI*2) % (2*Math.PI);
},
angleDifference: function(sourceAngle, destinationAngle) {
return Math.atan2(Math.sin(destinationAngle-sourceAngle),
Math.cos(destinationAngle-sourceAngle));
}
};
/**
* @type {string[]}
*/
var THEMES = [
"classic",
"sketch",
"sunrise"
];
/**
* GlobalsDB Admin module.
* @author ZitRo
*/
var app = new function() {
var DOM_ELEMENTS = {
VIEWPORT: null,
FIELD: null,
TREE_PATH: null
},
USE_HARDWARE_ACCELERATION = false,
DATA_ADAPTER = dataAdaptor,
TREE_ROOT = null,
manipulator,
CLIENT_VERSION = "1.3.0",
// enables handling action by application
ACTION_HANDLERS_ON = true,
// confirm deleting nodes
NODE_DELETION_CONFIRM = true,
CSS_CLASS_NAME_NODE = "node",
CSS_CLASS_NAME_LINK = "link",
CSS_CLASS_NAME_SELECT = "selected",
CSS_CLASS_NAME_DELETE = "deleting",
CSS_CLASS_NAME_COPY = "copying",
CSS_CLASS_NAME_EDIT = "editing",
CSS_EMPTY_CLASS_NAME = "",
NODE_STATE_ACTION_SELECT = 0,
NODE_STATE_ACTION_EDIT = 1,
NODE_STATE_ACTION_COPY = 2,
NODE_STATE_ACTION_DELETE = 3,
NODE_STATE_ACTIONS = 4,
NODE_MAX_VISUAL_ELEMENTS = 15,
MIN_NODES_DISTANCE = 110, // minimal distance between nodes
BASE_NODE_RADIUS = 140,
TREE_NODE_RADIUS = 80,
VIEW_UPDATES_PER_STEP = 0,
COPY_NODE_PATH_DESTINATION = null,
COPY_NODE_PATH_TARGET = null,
TRIGGER_ADD = 0,
TRIGGER_JUMP = 1,
TRIGGER_PASTE = 2;
/**
* Block DOM event.
*
* @param e
*/
var blockEvent = function(e) {
e.preventDefault();
e.cancelBubble = true;
if (e.preventDefault) {
e.preventDefault();
e.stopPropagation();
}
};
var setElements = function() {
DOM_ELEMENTS.VIEWPORT = document.getElementById("fieldViewport");
DOM_ELEMENTS.FIELD = document.getElementById("field");
DOM_ELEMENTS.TREE_PATH = document.getElementById("treePath");
};
var transformsSupport = function() {
var el = document.createElement('p'),
has3d,
transforms = {
'webkitTransform':'-webkit-transform',
'OTransform':'-o-transform',
'msTransform':'-ms-transform',
'MozTransform':'-moz-transform',
'transform':'transform'
};
document.body.insertBefore(el, null);
for (var t in transforms) {
if (!transforms.hasOwnProperty(t)) continue;
if (el.style[t] !== undefined) {
el.style[t] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el, null).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
};
/**
* Handles all user events and adapts them to the controller. Also manipulates viewport.
*/
var Manipulator = function() {
var _this = this,
VIEWPORT_WIDTH = window.innerWidth,
VIEWPORT_HEIGHT = window.innerHeight,
VIEW_X = 0,
VIEW_Y = 0,
VISUAL_VIEW_X = 0,
VISUAL_VIEW_Y = 0,
VIEW_CENTER_X = 0,
VIEW_CENTER_Y = 0,
VIEWPORT_SCALE = 1,
WORLD_WIDTH = 100000,
WORLD_HEIGHT = 100000,
MIN_SCALE = 0.3,
MAX_SCALE = 3,
viewportUpdateInterval = 0,
touchObject = {
ox: 0,
oy: 0,
x: 0,
y: 0,
target: null,
event: null,
pressed: false
};
this.getRelativeCenter = function() {
return {
x: WORLD_WIDTH/2,
y: WORLD_HEIGHT/2
}
};
this.getViewX = function() { return VIEW_X - WORLD_WIDTH/2; };
this.getViewY = function() { return VIEW_Y - WORLD_HEIGHT/2; };
/**
* Performs relative scale for viewport.
*/
this.scaleView = function(delta) {
var element = DOM_ELEMENTS.FIELD;
VIEWPORT_SCALE += delta;
VIEWPORT_SCALE = Math.max(MIN_SCALE, Math.min(MAX_SCALE, VIEWPORT_SCALE));
_this.setViewCenter(VIEW_CENTER_X, VIEW_CENTER_Y);
forceViewUpdate();
element.style["transform"] = element.style["-ms-transform"] = element.style["-o-transform"] =
element.style["-moz-transform"] = element.style["-webkit-transform"] =
"scale(" + VIEWPORT_SCALE + ")";
};
/**
* Centers the viewport on a (x, y) coordinates.
*
* @param x
* @param y
*/
this.setViewCenter = function(x, y) {
VIEW_CENTER_X = x;
VIEW_CENTER_Y = y;
VIEW_X = WORLD_WIDTH/2 + x*VIEWPORT_SCALE - VIEWPORT_WIDTH/2;
VIEW_Y = WORLD_HEIGHT/2 + y*VIEWPORT_SCALE - VIEWPORT_HEIGHT/2;
if (!viewportUpdateInterval) viewportUpdateInterval = setInterval(viewportUpdater, 25);
};
var viewportUpdater = function() {
var deltaX, deltaY;
VISUAL_VIEW_X += deltaX = (VIEW_X - VISUAL_VIEW_X)/2;
VISUAL_VIEW_Y += deltaY = (VIEW_Y - VISUAL_VIEW_Y)/2;
if (Math.abs(deltaX) + Math.abs(deltaY) < 0.001) {
clearInterval(viewportUpdateInterval);
viewportUpdateInterval = 0;
VISUAL_VIEW_X = VIEW_X;
VISUAL_VIEW_Y = VIEW_Y;
}
DOM_ELEMENTS.VIEWPORT.scrollLeft = Math.round(VISUAL_VIEW_X);
DOM_ELEMENTS.VIEWPORT.scrollTop = Math.round(VISUAL_VIEW_Y);
};
var forceViewUpdate = function() {
VISUAL_VIEW_X = VIEW_X;
VISUAL_VIEW_Y = VIEW_Y;
viewportUpdater();
};
var pointerEvents = new function() {
var updateInterval = 0,
newEvent;
var step = function() {
var e = newEvent;
if (e.scrolling) { // if there's a node to scroll
var node = e.scrolling.parentNode,
angle = -Math.atan2(e.x - e.ox, e.oy - e.y) + Math.PI/2;
var deltaAngle = Geometry.angleDifference(angle, e.scrolling.angle);
node.childController.updateSelectedIndex(-deltaAngle);
e.scrolling.angle = angle;
if (Math.abs(deltaAngle) < 0.001) {
stopUpdate();
}
return;
}
if (!e.event.changedTouches || e.event.changedTouches.length < 2) {
} else {
var d = Math.sqrt(
Math.pow(
e.event.changedTouches[0].pageX - e.event.changedTouches[1].pageX,
2
) +
Math.pow(
e.event.changedTouches[0].pageY - e.event.changedTouches[1].pageY,
2
)
);
if (e.ld) {
e.i++;
_this.scaleView((d - e.ld)/100);
}
e.ld = d;
}
_this.setViewCenter(e.ovx + (e.ox - e.x)/VIEWPORT_SCALE,
e.ovy + (e.oy - e.y)/VIEWPORT_SCALE);
};
var startUpdate = function() {
if (updateInterval) return;
clearInterval(updateInterval);
updateInterval = setInterval(step, 30);
};
var stopUpdate = function() {
clearInterval(updateInterval);
updateInterval = 0;
};
this.started = function(e) {
e.ox = e.x;
e.oy = e.y;
e.i = 0;
e.ld = undefined;
e.ovx = (_this.getViewX() + VIEWPORT_WIDTH/2)/VIEWPORT_SCALE;
e.ovy = (_this.getViewY() + VIEWPORT_HEIGHT/2)/VIEWPORT_SCALE;
e.scrolling = null;
var t = e.target;
do {
if (t.NODE_OBJECT) {
var node;
try {
node = t.NODE_OBJECT.getParent();
} catch(e) { node = null; }
if (node && !node.childController.isFreeAligned()) {
e.scrolling = {
currentNode: t.NODE_OBJECT,
parentNode: node,
angle: 0
};
var dir = //Geometry.normalizeAngle(
-Math.atan2(t.NODE_OBJECT.getX() - node.getX(),
node.getY() - t.NODE_OBJECT.getY()) + Math.PI/2
/*)*/,
len = Math.sqrt(Math.pow(t.NODE_OBJECT.getX() - node.getX(), 2) +
Math.pow(t.NODE_OBJECT.getY() - node.getY(), 2));
e.scrolling.angle = dir;
e.ox = e.ox - Math.cos(dir)*len*VIEWPORT_SCALE;
e.oy = e.oy + Math.sin(dir)*len*VIEWPORT_SCALE;
}
}
t = t.parentNode;
} while (t);
};
this.moved = function(e) { // limited while pressed
blockEvent(e.event);
newEvent = e;
startUpdate();
};
this.ended = function(e) {
blockEvent(e.event);
stopUpdate();
};
};
var keyboardEvents = new function() {
var keyStat = {},
KEY_PRESSED = 1,
KEY_RELEASED = 0;
this.keyPress = function(keyCode, event) {
keyStat[keyCode] = KEY_PRESSED;
var scrolling = function(delta) {
if (TREE_ROOT) TREE_ROOT.scrollEvent(delta);
};
switch (keyCode) {
case 8: { // BACKSPACE
if (TREE_ROOT) TREE_ROOT.backEvent();
blockEvent(event);
} break;
case 13: { // ENTER
if (TREE_ROOT) TREE_ROOT.triggerEvent();
} break;
case 37: { // LEFT
if (TREE_ROOT) TREE_ROOT.changeStateAction(-1);
} break;
case 38: { // UP
scrolling(-1);
} break;
case 39: { // RIGHT
if (TREE_ROOT) TREE_ROOT.changeStateAction(1);
} break;
case 40: { // DOWN
scrolling(1);
} break;
case 107: { // PLUS
_this.scaleView(0.1);
} break;
case 109: { // MINUS
_this.scaleView(-0.1);
}
}
};
this.keyRelease = function(keyCode, event) {
keyStat[keyCode] = KEY_RELEASED;
};
};
/**
* Handles viewport update.
*/
this.viewportUpdated = function() {
VIEWPORT_WIDTH = window.innerWidth;
VIEWPORT_HEIGHT = window.innerHeight;
};
/**
* Returns viewport to original position.
*/
this.resetViewport = function() {
DOM_ELEMENTS.FIELD.style.width = WORLD_WIDTH + "px";
DOM_ELEMENTS.FIELD.style.height = WORLD_HEIGHT + "px";
_this.setViewCenter(0, 0);
VISUAL_VIEW_X = VIEW_X;
VISUAL_VIEW_Y = VIEW_Y;
};
this.initialize = function() {
manipulator.viewportUpdated();
_this.resetViewport();
var setupTouchEvent = function(event) {
var t = (event.touches || event.changedTouches || [event])[0];
if (!t) return;
touchObject.x = t.pageX;
touchObject.y = t.pageY;
touchObject.event = event;
touchObject.target = event.target || event.srcElement;
};
DOM_ELEMENTS.VIEWPORT.ontouchstart = function(e) {
if (!ACTION_HANDLERS_ON) return;
touchObject.pressed = true;
setupTouchEvent(e);
pointerEvents.started(touchObject);
};
DOM_ELEMENTS.VIEWPORT.ontouchmove = function(e) {
if (!ACTION_HANDLERS_ON) return;
setupTouchEvent(e);
pointerEvents.moved(touchObject);
};
DOM_ELEMENTS.VIEWPORT.ontouchend = function(e) {
if (!ACTION_HANDLERS_ON) return;
touchObject.pressed = false;
setupTouchEvent(e);
pointerEvents.ended(touchObject);
};
DOM_ELEMENTS.VIEWPORT.onmousedown = function(e) {
if (!ACTION_HANDLERS_ON) return;
touchObject.pressed = true;
setupTouchEvent(e);
pointerEvents.started(touchObject);
};
DOM_ELEMENTS.VIEWPORT.onmousemove = function(e) {
if (!ACTION_HANDLERS_ON) return;
if (!touchObject.pressed) return;
setupTouchEvent(e);
pointerEvents.moved(touchObject);
};
DOM_ELEMENTS.VIEWPORT.onmouseup = function(e) {
if (!ACTION_HANDLERS_ON) return;
touchObject.pressed = false;
setupTouchEvent(e);
pointerEvents.ended(touchObject);
};
DOM_ELEMENTS.VIEWPORT.onmousewheel = function(e) {
if (!ACTION_HANDLERS_ON) return;
_this.scaleView(-(e.deltaY || e.wheelDelta)/2000);
};
document.body.onkeydown = function(e) {
if (!ACTION_HANDLERS_ON) return;
keyboardEvents.keyPress(e.keyCode, e);
};
document.body.onkeyup = function(e) {
if (!ACTION_HANDLERS_ON) return;
keyboardEvents.keyRelease(e.keyCode, e);
};
};
};
/**
* Node element.
*
* @param parentNode {Node} Parent node
* @param initialIndex {Array|string} Node index. In case of string, node will try require data in data adaptor with it's path.
* In case of object, node will get new properties.
* @param baseAngle
* @param {Number=} startX
* @param {Number=} startY
* @constructor
*/
var Node = function(parentNode, initialIndex, baseAngle, startX, startY) {
var _this = this,
PARENT_NODE = (parentNode instanceof Node)?parentNode:null,
CHILD_NODES = [],
INDEX = "",
visualNodeProps = {
x: 0,
y: 0,
r: 0,
relativeX: manipulator.getRelativeCenter().x,
relativeY: manipulator.getRelativeCenter().y,
baseAngle: baseAngle // angle to parent element
},
value = "",
element = null,
currentStateAction = NODE_STATE_ACTION_SELECT;
this.setPosition = function(x, y) {
visualNodeProps.x = x;
visualNodeProps.y = y;
updateView();
};
this.setRadius = function(r) {
visualNodeProps.r = r;
updateView();
};
this.setChild = function(node) {
if (!(node instanceof Node)) return;
for (var i in CHILD_NODES) {
if (!CHILD_NODES.hasOwnProperty(i)) continue;
if (CHILD_NODES[i] === node) return;
}
CHILD_NODES.push(node);
};
this.setValue = function(text) {
value = text;
try {
element.childNodes[0].childNodes[0].innerHTML = value;
} catch (e) {
console.error("Unable to set value to node DOM element", e);
}
};
this.setIndex = function(index) { // @improve (value method)
INDEX = index;
_this.updateValue();
};
this.setZIndex = function(z) {
if (element) element.style.zIndex = z;
};
this.setBaseAngle = function(angle) {
visualNodeProps.baseAngle = angle;
};
this.changeStateAction = function(delta) {
currentStateAction =
Math.round(currentStateAction + NODE_STATE_ACTIONS + delta) % NODE_STATE_ACTIONS;
_this.childController.updateView();
};
this.getX = function() { return visualNodeProps.x; };
this.getY = function() { return visualNodeProps.y; };
this.getR = function() { return visualNodeProps.r; };
this.getParent = function() { return PARENT_NODE; };
this.getIndex = function() { return INDEX; };
this.getBaseAngle = function() { return baseAngle; };
this.getStateAction = function() { return currentStateAction; };
this.getPath = function() {
var path = [INDEX],
parentNode = PARENT_NODE;
while (parentNode) {
path.unshift(parentNode.getIndex());
parentNode = parentNode.getParent();
}
return path;
};
this.getChildNode = function(nodeIndex) {
return _this.childController.getChildNodeByIndex(nodeIndex);
};
this.childController = new function() {
var __this = this,
node = _this,
child = [], // full child node data [string]
beams = {
// index: { index: Number, beam: Beam }
},
ADDITIONAL_CHILD = 0,
MAX_VISUAL_ELEMENTS = NODE_MAX_VISUAL_ELEMENTS,
INITIAL_ELEMENT_NUMBER = 30,
SELECTED_INDEX = 0,
VISUAL_SELECTED_INDEX = 0, // for animation
updateViewInterval = 0,
PASTE_CONTROL = false, // additional variable to define if paste control was added
NODES_FREE_ALIGN = true; // shows if place nodes free (not to fix them with selector)
/**
* Function updates extra child control according to current NODES_FREE_ALIGN constant.
*/
var resetExtraChild = function() {
child[-1] = undefined;
child[-2] = undefined;
child[-3] = undefined;
var search = {
name: "jump",
value: "<img src=\"img/jumpIcon.png\" class=\"jumpIcon\"/>",
trigger: TRIGGER_JUMP
},
add = {
name: "add",
value: "<img src=\"img/addIcon.png\" class=\"addIcon\"/>",
trigger: TRIGGER_ADD
},
paste = {
name: "paste",
value: "<img src=\"img/copyIcon.png\" class=\"copyIcon\">",
trigger: TRIGGER_PASTE
};
if (NODES_FREE_ALIGN) {
ADDITIONAL_CHILD = 1;
child[-1] = add;
child[-2] = paste;
} else {
ADDITIONAL_CHILD = 2;
child[-1] = add;
child[-2] = search;
child[-3] = paste;
}
if (COPY_NODE_PATH_TARGET) {
ADDITIONAL_CHILD++;
}
if (COPY_NODE_PATH_TARGET && !PASTE_CONTROL) {
PASTE_CONTROL = true;
alignSubNodes();
}
};
/**
* Return child node with given name = index.
*
* @param index
*/
this.getChildNodeByIndex = function(index) {
var node;
for (var b in beams) {
if (!beams.hasOwnProperty(b)) continue;
node = beams[b].beam.getNode();
if (node.getIndex() === index) {
return node;
}
}
return null;
};
this.isFreeAligned = function() {
return NODES_FREE_ALIGN;
};
/**
* Returns currently selected node.
*
* @returns {Node | null}
*/
this.getCurrentNode = function() {
return __this.getChildNodeByIndex(child[Math.round(SELECTED_INDEX)]);
};
/**
* Enters to selected node.
*/
this.triggerEvent = function() { // @update SELECTED_INDEX => argument
if (!beams[Math.round(SELECTED_INDEX)]) return;
if (SELECTED_INDEX < 0 || (NODES_FREE_ALIGN && child.length <= SELECTED_INDEX)) {
currentStateAction = NODE_STATE_ACTION_SELECT;
}
switch (currentStateAction) {
case NODE_STATE_ACTION_SELECT: {
VISUAL_SELECTED_INDEX = SELECTED_INDEX;
__this.handleSelect();
} break;
case NODE_STATE_ACTION_EDIT: {
__this.handleEdit();
} break;
case NODE_STATE_ACTION_COPY: {
__this.handleCopy();
resetExtraChild();
} break;
case NODE_STATE_ACTION_DELETE: {
__this.handleDelete();
} break;
default: console.log("Unhandled action: " + currentStateAction);
}
__this.forceViewUpdate();
};
/**
* Handles trigger of selected node.
*
* @param trigger
*/
var handleSelectedNodeTrigger = function(trigger) {
switch (trigger) {
case TRIGGER_ADD: TREE_ROOT.handler.addNode(); break;
case TRIGGER_JUMP: TREE_ROOT.handler.jumpNode(); break;
case TRIGGER_PASTE: TREE_ROOT.handler.pasteNode(_this.getPath()); break;
default: console.log("Unrecognised trigger");
}
};
this.handleSelect = function() {
var beam = beams[Math.round(SELECTED_INDEX)].beam,
node = beam.getNode(),
nodeIndex = node.getIndex();
if (typeof nodeIndex === "object" && typeof nodeIndex.trigger !== "undefined") {
handleSelectedNodeTrigger(nodeIndex.trigger);
return;
}
beam.setRadius(beam.getInitialRadius()*2.5); // @split to function
node.initChild();
TREE_ROOT.setTriggeringNode(node);
};
this.handleEdit = function() {
var node = __this.getCurrentNode();
if (!node) return;
TREE_ROOT.handler.editNode(node.getPath());
};
this.handleCopy = function() {
var node = __this.getCurrentNode();
if (!node) return;
TREE_ROOT.handler.copyNode(node.getPath());
};
this.handleDelete = function() {
var node = __this.getCurrentNode();
if (!node) return;
if (NODE_DELETION_CONFIRM) {
if (confirm("Are you sure to delete " + node.getIndex() + "?")) {
TREE_ROOT.handler.deleteNode(node.getPath());
}
} else {
TREE_ROOT.handler.deleteNode(node.getPath());
}
};
this.updateSelectedIndex = function(indexDelta) {
var last = SELECTED_INDEX;
if (NODES_FREE_ALIGN) {
SELECTED_INDEX = (SELECTED_INDEX + indexDelta + child.length + ADDITIONAL_CHILD)
% (child.length + ADDITIONAL_CHILD);
} else {
SELECTED_INDEX = Math.max(-ADDITIONAL_CHILD, Math.min(child.length - 1, SELECTED_INDEX + indexDelta));
if (last !== SELECTED_INDEX) {
try {
beams[Math.round(last)].beam.setRadius(
beams[Math.round(last)].beam.getInitialRadius());
beams[Math.round(last)].beam.getNode().childController.removeBeams();
} catch (e) { /* deleted beam */ }
}
}
if (SELECTED_INDEX + MAX_VISUAL_ELEMENTS/2 > child.length) {
updateFromModel();
}
if (last !== SELECTED_INDEX) {
if (NODES_FREE_ALIGN) {
__this.updateView();
} else {
alignSubNodes();
}
}
};
this.targetSelectionToSubPath = function(subPathName) {
for (var b in beams) {
if (!beams.hasOwnProperty(b)) continue;
if (beams[b].beam.getSubPath() === subPathName) {
__this.updateSelectedIndex(beams[b].index - SELECTED_INDEX);
return beams[b].index;
}
}
return 0;
};
this.removeBeams = function() {
for (var i in beams) {
if (!beams.hasOwnProperty(i)) continue;
beams[i].beam.remove();
delete beams[i];
}
};
/**
* Server data update chain handler. Function forces to make requests to dataAdaptor again.
*/
this.update = function() {
var length = child.length;
updateFromModel();
//if (child.length !== length) {
alignSubNodes();
//}
__this.updateSelectedIndex(0);
};
/**
* Request data.
*/
var updateFromModel = function() {
var fromIndex = SELECTED_INDEX - Math.ceil(MAX_VISUAL_ELEMENTS/2),
level = DATA_ADAPTER.getLevel(
node.getPath(),
INITIAL_ELEMENT_NUMBER,
(fromIndex <= 0)?"":child[fromIndex]
);
if (fromIndex < 0) fromIndex = 0;
for (var i = 0; i < level.length; i++) {
child[fromIndex + i] = level[i];
}
child.splice(fromIndex + i, child.length - fromIndex - i);
if (NODES_FREE_ALIGN
&& (level.length + fromIndex - 1 > MAX_VISUAL_ELEMENTS/(PARENT_NODE?2:1))) {
NODES_FREE_ALIGN = false;
for (var b in beams) {
if (!beams.hasOwnProperty(b)) continue;
beams[b].beam.setRadius(0);
beams[b].beam.resetInitialRadius();
}
alignSubNodes();
}
resetExtraChild();
};
var alignSubNodes = function() {
var getBeamsNumber = function() {
var bm = 0;
for (var i in beams) {
if (!beams.hasOwnProperty(i)) continue;
bm++;
}
return bm;
};
if (NODES_FREE_ALIGN) {
var cleanBeams = function() {
for (var b in beams) {
if (!beams.hasOwnProperty(b)) continue;
beams[b].beam.setRadius(beams[b].beam.getInitialRadius());
beams[b].beam.resetInitialRadius();
var n = beams[b].beam.getNode();
if (n) {
n.childController.removeBeams();
}
}
};
var clean;
for (var b in beams) {
if (!beams.hasOwnProperty(b)
|| beams[b].beam.getSubPath() == child[beams[b].index]) continue;
beams[b].beam.remove();
clean = true;
delete beams[b];
}
for (var u = 0;
u < child.length + ADDITIONAL_CHILD;
u++) {
if (beams[u]) continue;
clean = true;
beams[u] = {
index: u,
beam: new Beam(node, (u<child.length)?child[u]:child[child.length-u-1], 0, 0)
};
}
if (clean) cleanBeams();
} else {
var fromIndex = Math.max(
Math.ceil(SELECTED_INDEX - MAX_VISUAL_ELEMENTS/2),
-ADDITIONAL_CHILD
),
toIndex = Math.min(
Math.floor(SELECTED_INDEX + MAX_VISUAL_ELEMENTS/2),
child.length
),
deprecatedBeams = [ /* { index, beam } */ ],
i, tempBeam;
for (i in beams) {
if (!beams.hasOwnProperty(i)) continue;
if (i < fromIndex || i >= toIndex) {
deprecatedBeams.push(beams[i]);
delete beams[i];
}
}
for (i = fromIndex; i < toIndex; i++) {
if (beams.hasOwnProperty(i.toString())) { // update
if (typeof beams[i].beam.getSubPath() === "object") { // override trigger
beams[i].beam.remove();
} else {
// if model updated
if (beams[i].beam.getSubPath() !== child[beams[i].index]
&& child[beams[i].index]) {
beams[i].beam.setSubPathName(child[beams[i].index]);
}
continue; // skip iteration (else-branch)
}
}
if (deprecatedBeams.length) { // reset
tempBeam = deprecatedBeams.pop();
tempBeam.beam.setSubPathName(child[i]);
tempBeam.index = i;
beams[i] = tempBeam;
} else { // create
beams[i] = { index: i, beam: new Beam(node, child[i], 0, 0)};
}
}
for (i = 0; i < deprecatedBeams.length; i++) { // delete
deprecatedBeams[i].beam.remove();
}
}
__this.forceViewUpdate();
__this.updateView();
};
this.updateView = function () {
if (NODES_FREE_ALIGN) {
viewFreeUpdater();
updateViewInterval = 0;
return;
}
if (!updateViewInterval) {
updateViewInterval = setInterval(viewScrollUpdater, 25);
}
};
this.forceViewUpdate = function() {
if (NODES_FREE_ALIGN) {
viewFreeUpdater();
updateViewInterval = 0;
return;
}
clearInterval(updateViewInterval);
updateViewInterval = 0;
viewScrollUpdater();
};
var getAppropriateStateActionClassName = function() {
switch (currentStateAction) {
case NODE_STATE_ACTION_SELECT: return CSS_CLASS_NAME_SELECT; break;
case NODE_STATE_ACTION_EDIT: return CSS_CLASS_NAME_EDIT; break;
case NODE_STATE_ACTION_COPY: return CSS_CLASS_NAME_COPY; break;
case NODE_STATE_ACTION_DELETE: return CSS_CLASS_NAME_DELETE; break;
default: return CSS_EMPTY_CLASS_NAME;
}
};
var viewFreeUpdater = function() {
var i = 0,
mi = child.length + ADDITIONAL_CHILD,
angle, dAngle, aAngle, bAngle,
baseAngleDefined = (visualNodeProps.baseAngle !== undefined)?1:0;
// @weirdMath
for (var b in beams) {
if (!beams.hasOwnProperty(b)) continue;
// beams[b].beam.highlight(
// (Math.round(SELECTED_INDEX) === beams[b].index)?
// getAppropriateStateActionClassName():CSS_EMPTY_CLASS_NAME
// ); // @improve
if (baseAngleDefined) {
bAngle = 0;
aAngle = Math.PI;
aAngle = Math.min(aAngle, Math.PI/6*mi);
dAngle = aAngle/(mi || 1);
} else {
bAngle = (1/mi)*2*Math.PI/2;
aAngle = 2*Math.PI - (1/mi)*2*Math.PI;
dAngle = aAngle/(mi || 1);
}
angle = Geometry.normalizeAngle(
(visualNodeProps.baseAngle || 0) + Math.PI
- ((mi > 1)?aAngle/2:0) + (i/(mi - 1 || 1))*aAngle - bAngle
) || 0;
var r;
if (!beams[b].beam.getInitialRadius()) {
r = Math.max(
beams[b].beam.getNode().getR()/Math.tan(dAngle/2),
beams[b].beam.getNode().getR() + node.getR() + MIN_NODES_DISTANCE
);
if (r === Infinity) {
r = beams[b].beam.getNode().getR() + node.getR() + MIN_NODES_DISTANCE;
}
// beams[b].beam.setRadius(r);
}
// beams[b].beam.setAngle(angle);
beams[b].beam.updateGeometry(angle, r || beams[b].beam.getRadius(),
undefined, (Math.round(SELECTED_INDEX) === beams[b].index)?
getAppropriateStateActionClassName():CSS_EMPTY_CLASS_NAME);
i++;
}
};
var viewScrollUpdater = function(k) { // work with indexes: display child array
var delta, d;
if (!k) k = 2.5;
VISUAL_SELECTED_INDEX += delta = (SELECTED_INDEX - VISUAL_SELECTED_INDEX)/k;
if (Math.abs(delta) < 0.001) {
VISUAL_SELECTED_INDEX = SELECTED_INDEX;
clearInterval(updateViewInterval);
updateViewInterval = 0;
}
for (var b in beams) {
if (!beams.hasOwnProperty(b)) continue;
d = beams[b].index - VISUAL_SELECTED_INDEX;
beams[b].beam.updateGeometry(Math.atan(Math.PI/1.4*d*2/MAX_VISUAL_ELEMENTS * 2)*2
+ ((typeof visualNodeProps.baseAngle === "number")?
visualNodeProps.baseAngle:Math.PI) + Math.PI,
Math.max(
beams[b].beam.getRadius(),
beams[b].beam.getNode().getR()/Math.tan(Math.PI*2/MAX_VISUAL_ELEMENTS),
beams[b].beam.getNode().getR() + node.getR() + MIN_NODES_DISTANCE
),
-Math.round(d*d) + 200, (Math.round(SELECTED_INDEX) === beams[b].index)?
getAppropriateStateActionClassName():CSS_EMPTY_CLASS_NAME);
}
};
__this.init = function() {
updateFromModel();
alignSubNodes();
};
};
/**
* Handle clicking on node.
*/
var handleClick = function() {
var node = _this.getParent();
if (node) {
node.childController.targetSelectionToSubPath(_this.getIndex());
node.childController.triggerEvent();
}
};
/**
* Joins node to the parent node.
*/
var joinParent = function(parentNode) {
if (!(parentNode instanceof Node)) return;
parentNode.setChild(_this);
};
var createNodeElement = function() {
var el = document.createElement("DIV");
el.className = CSS_CLASS_NAME_NODE;
el.NODE_OBJECT = _this;
el.innerHTML = "<div><span>" + value + "</span></div>";
el.onclick = handleClick;
DOM_ELEMENTS.FIELD.appendChild(el);
return el;
};
var updateView = function() {
// @optimize: -r to set* methods
var x = Math.round(visualNodeProps.relativeX + visualNodeProps.x - visualNodeProps.r),
y = Math.round(visualNodeProps.relativeY + visualNodeProps.y - visualNodeProps.r);
if (USE_HARDWARE_ACCELERATION) {
element.style["transform"] = element.style["-ms-transform"] = element.style["-o-transform"] =
element.style["-moz-transform"] = element.style["-webkit-transform"] = "translate3d(" +
x + "px, " +
y + "px, 0)";
} else {
element.style.left = x + "px";
element.style.top = y + "px";
}
element.style.width = element.style.height = visualNodeProps.r*2 + "px";
VIEW_UPDATES_PER_STEP += 1;
};
this.initChild = function() {
_this.childController.init();
};
/**
* Gives control to parent node.
*/
this.back = function() {
var parent = _this.getParent();
if (!parent) return;
TREE_ROOT.setTriggeringNode(parent);
};
this.remove = function() {
if (element) element.parentNode.removeChild(element);
_this.childController.removeBeams();
};
this.updateValue = function() {
if (typeof INDEX === "object") {
_this.setValue(INDEX.value);
} else {
_this.setValue(DATA_ADAPTER.getValue(_this.getPath()));
}
};
/**
* Make node glow (highlight node).
*
* @param CSSClassName {Boolean}
*/
this.highlight = function(CSSClassName) {
element.className = CSS_CLASS_NAME_NODE + " " + CSSClassName;
};
_this.handle = {
updateChild: function() {
_this.childController.update();
}
};
var init = function() {
joinParent(PARENT_NODE);
element = createNodeElement();
_this.setPosition(startX, startY);
_this.setRadius((parentNode != null)?TREE_NODE_RADIUS:BASE_NODE_RADIUS);
_this.setIndex(initialIndex);
updateView();
};
init();
};
/**
* Connects parentNode and node with position controlling under node.
*
* @param parentNode
* @param subPath
* @param {number=} initialAngle
* @param {number=} initialRadius
*
* @constructor
*/
var Beam = function(parentNode, subPath, initialAngle, initialRadius) {
var visualBeamProps = {
angle: Geometry.normalizeAngle(initialAngle || 0),
r: initialRadius || 100,
relativeX: manipulator.getRelativeCenter().x,
relativeY: manipulator.getRelativeCenter().y,
initialRadius: initialRadius,
WIDTH_EXPAND: 2,
HALF_HEIGHT: 3 // @override
},
_this = this,
node = new Node(
parentNode,
subPath,
Geometry.normalizeAngle(visualBeamProps.angle + Math.PI),
0,
0
),
element = null;
var handleClick = function() {
if (parentNode) {
parentNode.childController.targetSelectionToSubPath(_this.getSubPath());
parentNode.changeStateAction(1);
}
};
var createBeamElement = function() {
var el = document.createElement("DIV");
el.className = CSS_CLASS_NAME_LINK;
el.innerHTML = "<div><div><div><span>" +
((typeof subPath !== "object")?subPath:subPath.name)
+ "</span></div></div></div>"; // @structured
el.onclick = handleClick;
DOM_ELEMENTS.FIELD.appendChild(el);
visualBeamProps.HALF_HEIGHT = parseFloat(el.clientHeight)/2 || 3;
return el;
};
/**
* @param direction
*/
this.setAngle = function(direction) {
visualBeamProps.angle = Geometry.normalizeAngle(direction);
node.setBaseAngle(Geometry.normalizeAngle(visualBeamProps.angle + Math.PI));
updateView();
};
/**
* @param radius
*/
this.setRadius = function(radius) {
if (!visualBeamProps.initialRadius) visualBeamProps.initialRadius = radius;
visualBeamProps.r = radius;
updateView();
};
/**
* @deprecated
* @param z
*/
this.setZIndex = function(z) {
if (element) element.style.zIndex = 11 + z;
if (node) node.setZIndex(12 + z);
};
/**
* Completely updates beam.
* @param angle
* @param radius
* @param {Number|undefined} zIndex
* @param CSSClassName
*/
this.updateGeometry = function(angle, radius, zIndex, CSSClassName) {
visualBeamProps.angle = Geometry.normalizeAngle(angle);
node.setBaseAngle(Geometry.normalizeAngle(visualBeamProps.angle + Math.PI));
if (!visualBeamProps.initialRadius) visualBeamProps.initialRadius = radius;
visualBeamProps.r = radius;
if (zIndex && element) element.style.zIndex = 11 + zIndex;
if (zIndex && node) node.setZIndex(12 + zIndex);
if (CSSClassName && typeof node.getIndex() === "object" // limit to allow only
&& typeof node.getIndex() !== "undefined") // selection for trigger nodes
CSSClassName = CSS_CLASS_NAME_SELECT;
element.className = CSS_CLASS_NAME_LINK + " " + CSSClassName;
if (node) node.highlight(CSSClassName);
updateView();
};
this.remove = function() {
if (element) element.parentNode.removeChild(element);
if (node) node.remove();
};
this.setSubPathName = function(index) {
subPath = index;
try {
element.childNodes[0].childNodes[0].childNodes[0].childNodes[0].innerHTML =
(typeof subPath !== "object")?subPath:subPath.name;
} catch (e) {
console.error("Unable to set value to beam DOM element", e);
}
node.setIndex(index);
};
/**
* Make link glow (highlight link).
*
* @deprecated
* @see this.updateGeometry
* @param CSSClassName {String} Empty string or class name
*/
this.highlight = function(CSSClassName) {
if (CSSClassName && typeof node.getIndex() === "object" // limit to allow only
&& typeof node.getIndex() !== "undefined") // selection for trigger nodes
CSSClassName = CSS_CLASS_NAME_SELECT;
element.className = CSS_CLASS_NAME_LINK + " " + CSSClassName;
if (node) node.highlight(CSSClassName);
};
this.resetInitialRadius = function() { visualBeamProps.initialRadius = 0; };
this.getNode = function() { return node; };
this.getSubPath = function() { return subPath; };
this.getParentNode = function() { return parentNode; };
this.getAngle = function() { return visualBeamProps.angle; };
this.getRadius = function() { return visualBeamProps.r; };
this.getInitialRadius = function() { return visualBeamProps.initialRadius; };
var updateElementPosition = function() {
if (!parentNode || !node) return;
/*
* The transformations here based on relative y-shift within angle (for line height/2) pixels and rotation
* around the left top corner of "link" box for given angle. Note that constants WIDTH_EXPAND and HALF_HEIGHT
* are dependent from CSS.
**/
var x1 = parentNode.getX() - visualBeamProps.HALF_HEIGHT*Math.cos(visualBeamProps.angle + Math.PI/2),
y1 = parentNode.getY() - visualBeamProps.HALF_HEIGHT*Math.sin(visualBeamProps.angle + Math.PI/2),
r = parentNode.getR() - visualBeamProps.WIDTH_EXPAND,
w = Math.sqrt(Math.pow(node.getX() - parentNode.getX(), 2) +
Math.pow(node.getY() - parentNode.getY(), 2)) - r - node.getR() + visualBeamProps.WIDTH_EXPAND*2,
boxElement = element.childNodes[0].childNodes[0];
if (w > visualBeamProps.WIDTH_EXPAND) {
if (w < 60) {
boxElement.style.display = "none";
} else {
boxElement.style.display = "block";
}
element.style.display = "block";
element.style.width = Math.round(w) + "px";
} else {
element.style.display = "none";
return;
}
if (USE_HARDWARE_ACCELERATION) {
element.style["transform"] = element.style["-ms-transform"] = element.style["-o-transform"] =
element.style["-moz-transform"] = element.style["-webkit-transform"] = "translate3d(" +
(visualBeamProps.relativeX + x1 + r*Math.cos(visualBeamProps.angle)) + "px, " +
(visualBeamProps.relativeY + y1 + r*Math.sin(visualBeamProps.angle)) + "px, 0) rotate(" +
visualBeamProps.angle + "rad)";
boxElement.style["transform"] = boxElement.style["-ms-transform"] = boxElement.style["-o-transform"] =
boxElement.style["-moz-transform"] = boxElement.style["-webkit-transform"] = "rotate(" +
((visualBeamProps.angle < Math.PI/2 || visualBeamProps.angle > Math.PI + Math.PI/2)?0:180) + "deg)";
} else {
element.style.visibility = "hidden"; // @improve: svg
}
VIEW_UPDATES_PER_STEP += 1;
};
var updateView = function() {
node.setPosition(
parentNode.getX() + visualBeamProps.r*Math.cos(visualBeamProps.angle),
parentNode.getY() + visualBeamProps.r*Math.sin(visualBeamProps.angle)
);
updateElementPosition();
};
var init = function() {
element = createBeamElement();
updateView();
};
init();
};
/**
* Tree root has basic tree control capabilities.
*
* @param {string="ROOT"} baseName
*/
var TreeRoot = function(baseName) {
var _this = this,
rootNode = null,
triggeringNode = null;
var init = function() {
baseName = baseName || "ROOT";
rootNode = new Node(null, "root", undefined, 0, 0);
triggeringNode = rootNode;
rootNode.initChild();
updateTreePathView();
};
var updateTreePathView = function() {
var arr = _this.getCurrentPath(),
viewArr = arr.slice(),
el;
viewArr[0] = baseName;
DOM_ELEMENTS.TREE_PATH.innerHTML =
"<li onclick=\"uiController.switchInfoPanel();\"><div><div>i</div></div></li>";
var setHandler = function(element, node) {
element.onclick = function(e) {
if (node) {
_this.setTriggeringNode(node);
blockEvent(e);
}
};
};
for (var i = 0; i < arr.length; i++) {
el = document.createElement("li");
el.innerHTML = viewArr[i];
var ci = arr.slice(1, i + 1),
node = getNodeByPath(ci);
setHandler(el, node);
DOM_ELEMENTS.TREE_PATH.appendChild(el);
}
};
var getNodeByPath = function(path) {
var node = rootNode;
for (var i = 0; i < path.length; i++) {
if (!node) break;
node = node.getChildNode(path[i]);
}
return node || null;
};
this.getNodeByPath = getNodeByPath;
/**
* @override
* @param path
*/
dataAdaptor.childUpdated = function(path) {
var node = getNodeByPath(path);
if (node != triggeringNode) return;
if (node) node.handle.updateChild();
};
/**
* @override
* @param path
*/
dataAdaptor.nodeValueUpdated = function(path) {
var node = getNodeByPath(path);
if (node) node.updateValue();
};
/**
* Scroll nodes for delta. Delta = 1 will scroll to 1 next node.
*
* @param delta
*/
this.scrollEvent = function(delta) {
if (triggeringNode) triggeringNode.childController.updateSelectedIndex(delta);
};
this.triggerEvent = function() {
if (triggeringNode) triggeringNode.childController.triggerEvent();
};
this.backEvent = function() {
if (triggeringNode) triggeringNode.back();
};
this.getCurrentPath = function() {
if (!triggeringNode) return [];
return triggeringNode.getPath();
};
this.setTriggeringNode = function(node) {
if (!(node instanceof Node)) return;
triggeringNode = node;
manipulator.setViewCenter(node.getX(), node.getY());
updateTreePathView();
};
this.handler = {
addNode: function() {
uiController.switchAddNodeForm();
},
editNode: function(path) {
uiController.switchEditNodeForm(path[path.length - 1], dataAdaptor.getValue(path));
},
copyNode: function(path) {
COPY_NODE_PATH_TARGET = path;
uiController.hint("Copied [" + path.join(" -> ") + "]");
},
pasteNode: function(path) {
if (!COPY_NODE_PATH_TARGET) return;
COPY_NODE_PATH_DESTINATION = path;
uiController.switchCopyNodeForm(
COPY_NODE_PATH_TARGET.join(" -> "),
path.join(" -> ") + " -> "
);
},
deleteNode: function(path) {
var dp = path.slice(); // because something in dataAdaptor.deleteNode changes array
dataAdaptor.deleteNode(path, function(success) {
if (success) uiController.hint("Node [" + dp.join(" -> ")
+ "] has been deleted.");
});
},
jumpNode: function() {
uiController.switchJumpNodeForm();
}
};
/**
* Removes the tree.
*/
this.remove = function() {
if (rootNode) rootNode.remove();
triggeringNode = null;
rootNode = null;
};
/**
* Changes type of action which will be performed on selected subnodes.
*/
this.changeStateAction = function(delta) {
if (triggeringNode) {
triggeringNode.changeStateAction(delta);
}
};
init();
};
/**
* Switches control to application (enables handlers)
*/
this.switchControl = function(enabled) {
ACTION_HANDLERS_ON = enabled?true:false;
};
/**
* Update the viewport.
*/
this.updateViewport = function() {
if (manipulator) manipulator.viewportUpdated();
};
/**
* Set of handlers.
*/
this.handle = {
connectionClose: function(data) {
// do nothing
uiController.showMessage("Connection broken.", "Client was disconnected from server.");
uiController.switchConnectForm();
},
/**
* Add node to current path.
*
* @param name
* @param value
*/
addNode: function(name, value) {
if (!TREE_ROOT) return;
var path = TREE_ROOT.getCurrentPath();
if (!path.length) return;
dataAdaptor.setNode(path, name, value, function(success) {
if (!success) {
uiController.showMessage("Failed to set node",
"Unable to set node [" + name + "] with value [" + value + "]");
} else {
uiController.hint("Node [" + name + "] created.");
}
});
},
/**
* Edit node within current path and selected node.
*
* @param name
* @param value
*/
editNode: function(name, value) {
if (!TREE_ROOT) return;
var path = TREE_ROOT.getCurrentPath();
if (!path.length) return;
var node = TREE_ROOT.getNodeByPath(path.slice(1));
if (!node) return;
node = node.childController.getCurrentNode();
if (!node) return;
if (node.getIndex() !== name) return;
dataAdaptor.setNode(path, name, value, function(success) {
if (!success) {
uiController.showMessage("Failed to set node",
"Unable to set node [" + name + "] with value [" + value + "]");
} else {
uiController.hint("Node [" + name + "] changed.");
}
});
},
copyNode: function(destinationNodeName) {
COPY_NODE_PATH_DESTINATION.push(destinationNodeName);
dataAdaptor.copyNode(COPY_NODE_PATH_TARGET, COPY_NODE_PATH_DESTINATION, function(ok) {
if (!ok) {
uiController.showMessage("Failed to copy node",
"Unable to copy node [" + COPY_NODE_PATH_TARGET.join(" -> ")
+ "] to [" + COPY_NODE_PATH_DESTINATION.join(" -> ") + "]");
} else {
dataAdaptor.forceClear(COPY_NODE_PATH_DESTINATION);
uiController.hint("Pasted: [" + COPY_NODE_PATH_TARGET.join(" -> ") + "] to ["
+ COPY_NODE_PATH_DESTINATION.join(" -> ") + "]");
}
});
},
/**
* Jump to node (limit node by name)
*/
jumpNode: function(name) {
dataAdaptor.setJumper(TREE_ROOT.getCurrentPath(), name);
uiController.hint("Jumper set to [" + name + "]");
}
};
/**
* Resets tree root for new or existing adaptor. Adapter will be reset too.
*
* @param adapter {object=}
* @param baseName {string=}
* @param username {string=}
*/
this.resetTreeRoot = function(adapter, baseName, username) {
if (TREE_ROOT) {
TREE_ROOT.remove();
}
if (adapter) {
DATA_ADAPTER = adapter;
}
DATA_ADAPTER.reset(username + ": " + baseName);
TREE_ROOT = new TreeRoot(baseName);
};
/**
* This callback is displayed as part of the Requester class. Callback called twice: immediately
* after function call and after server data load.
* @callback app~addDescriptionCallBack
* @param {string} text - Text to output.
*/
/**
* Returns app description.
* @param {app~addDescriptionCallBack} callback
*/
this.getDescription = function(callback) {
callback("<h1>About</h1><hr/><h3>" +
"<a target=\"_blank\" href=\"http://zitros.github.io/globalsDB-Admin-NodeJS\">" +
"GlobalsDB Admin client</a></h3><div>VERSION: " + CLIENT_VERSION + "</div>");
server.send({
request: "about"
}, function(data) {
if (data && data.result && !data.error) {
callback(data.result.result);
}
});
server.send({
request: "getManifest"
}, function(data) {
var s = "<h3>GlobalsDB Admin NodeJS Server adaptor</h3>" +
"<div style=\"display: inline-block; margin: 0 auto; text-align: left;\">";
data = data.manifest || {};
for (var p in data) {
if (!data.hasOwnProperty(p)) continue;
s += "<div>" + p + ": " + data[p] + "</div>";
}
s += "</div>";
callback(s);
});
};
/**
* Initialize application.
*/
this.init = function() {
uiController.init();
USE_HARDWARE_ACCELERATION = transformsSupport();
setElements(); // variables setup
manipulator = new Manipulator();
manipulator.initialize();
TREE_ROOT = new TreeRoot();
uiController.switchConnectForm();
}
}; |
import Mingus from 'mingus';
import {
chunk,
classNames,
debounce,
getClassName,
noop,
request
} from '../utils';
Mingus.createTestCase('ChunkTest', {
testChunkIterableWithItems() {
const xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = chunk(xs, 3);
this.assertDeepEqual(result, [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10]
]);
},
testChunkTooLarge() {
const xs = [1, 2, 3, 4];
const result = chunk(xs, 10);
this.assertDeepEqual(result, [[1, 2, 3, 4]]);
}
});
Mingus.createTestCase('ClassNamesTest', {
testEmptyClassNamesArgs() {
this.assertEqual(classNames(), '');
},
testEmptyClassNamesConfig() {
this.assertEqual(classNames({}), '');
},
testClassNamesArgs() {
this.assertEqual(classNames('a', 'b', 'c'), 'a b c');
},
testClassNamesConfig() {
this.assertEqual(classNames({
'awesome-stuff': true,
'bad-stuff': false,
'cool-stuff': true
}), 'awesome-stuff cool-stuff');
}
});
Mingus.createTestCase('DebounceTest', {
testCallDebouncedFunction() {
const mock = {callCount: 0};
const fn = debounce(() => (mock.callCount += 1), 325);
this.stub(global, 'setTimeout', (cb) => cb());
this.stub(global, 'clearTimeout');
fn('a', 'b', 'c');
this.assertEqual(global.setTimeout.callCount, 1);
this.assertEqual(mock.callCount, 1);
this.assertTypeOf(global.setTimeout.firstCall.args[0], 'function');
this.assertEqual(global.setTimeout.firstCall.args[1], 325);
}
});
Mingus.createTestCase('GetClassNameTest', {
testGetClassName() {
this.assertEqual(
getClassName('react-ui-ajax-form', 'custom-form'),
'react-ui-ajax-form custom-form'
);
}
});
Mingus.createTestCase('NoopTest', {
testNoop() {
this.assertUndefined(noop());
}
});
Mingus.createTestCase('RequestTest', {
before() {
const me = this;
class MockXMLHttpRequest {
constructor() {
me.request = this;
}
open() {
}
send() {
me.spy(this, 'onload');
me.spy(this, 'onerror');
this.status = 200;
this.onload();
this.status = 404;
this.onload();
this.onerror();
}
}
this.XMLHttpRequest = global.XMLHttpRequest;
global.XMLHttpRequest = MockXMLHttpRequest;
},
beforeEach() {
this.spy(global.XMLHttpRequest.prototype, 'open');
this.spy(global.XMLHttpRequest.prototype, 'send');
},
after() {
global.XMLHttpRequest = this.XMLHttpRequest;
},
testPostRequest() {
const onResponse = this.stub();
request.post('/api/neato/', 'mock data', onResponse);
this.assertEqual(this.request.open.callCount, 1);
this.assertEqual(this.request.send.callCount, 1);
this.assertEqual(this.request.onload.callCount, 2);
this.assertEqual(this.request.onerror.callCount, 1);
this.assertEqual(onResponse.callCount, 3);
this.assertTrue(this.request.open.calledWith(
'POST',
'/api/neato/',
true
));
this.assertTrue(this.request.send.calledWith('mock data'));
this.assertTrue(onResponse.calledWith(
new Error('POST: Network Error'),
this.request
));
this.assertTrue(onResponse.calledWith(
new Error('POST: Status Error'),
this.request
));
this.assertTrue(onResponse.calledWith(
undefined,
this.request
));
},
testGetRequest() {
const onResponse = this.stub();
request.get('/api/neato/', onResponse);
this.assertEqual(this.request.open.callCount, 1);
this.assertEqual(this.request.send.callCount, 1);
this.assertEqual(this.request.onload.callCount, 2);
this.assertEqual(this.request.onerror.callCount, 1);
this.assertEqual(onResponse.callCount, 3);
this.assertTrue(this.request.open.calledWith(
'GET',
'/api/neato/',
true
));
this.assertTrue(this.request.send.calledWith());
this.assertTrue(onResponse.calledWith(
new Error('GET: Network Error'),
this.request
));
this.assertTrue(onResponse.calledWith(
new Error('GET: Status Error'),
this.request
));
this.assertTrue(onResponse.calledWith(
undefined,
this.request
));
}
});
|
/**
* MongooseError constructor
*
* @param {String} msg Error message
* @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
*/
function MongooseError (msg) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.message = msg;
this.name = 'MongooseError';
};
/*!
* Inherits from Error.
*/
MongooseError.prototype.__proto__ = Error.prototype;
/*!
* Module exports.
*/
module.exports = exports = MongooseError;
/*!
* Expose subclasses
*/
MongooseError.CastError = require('./errors/cast');
MongooseError.DocumentError = require('./errors/document');
MongooseError.ValidationError = require('./errors/validation')
MongooseError.ValidatorError = require('./errors/validator')
MongooseError.VersionError =require('./errors/version')
MongooseError.OverwriteModelError = require('./errors/overwriteModel')
MongooseError.MissingSchemaError = require('./errors/missingSchema')
MongooseError.DivergentArrayError = require('./errors/divergentArray')
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Boundary = mongoose.model('Boundary');
/**
* Globals
*/
var user, boundary;
/**
* Unit tests
*/
describe('Boundary Model Unit Tests:', function () {
beforeEach(function (done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'M3@n.jsI$Aw3$0m3'
});
user.save(function () {
boundary = new Boundary({
properties: {
MANAME: 'Test management',
OWNER:'Test owner',
MGRINST: 'Test institution',
MANAGER: 'Test Manager',
MGRCITY: 'Test city',
MGRPHONE: 'Test phone',
COMMENTS1: 'Test comment1',
COMMENTS2: 'Test comment2',
MA_WEBSITE: 'Test website'
},
geometry: {
type: 'Point',
coordinates: [ -82.22820807639421, 29.59590886748321 ]
}
});
done();
});
});
describe('Method Save', function () {
it('should be able to save without problems', function (done) {
this.timeout(10000);
return boundary.save(function (err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without any geometry', function (done) {
boundary.geometry = null;
return boundary.save(function (err) {
should.exist(err);
done();
});
});
});
afterEach(function (done) {
Boundary.remove().exec(function () {
User.remove().exec(done);
});
});
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" />
, 'MoreVertRounded');
|
'use strict';
var fs = require('fs');
module.exports = function( dest,
target,
grunt ){
// Create the file withe the column headers
if( !grunt.file.exists( dest ) ){
grunt.file.write( dest, 'name,date,error,count,cycles,hz\n' );
}
// Append a line with the test results
var line = [
'"' + target.name + '"',
'"' + target.timestamp + '"',
target.error,
target.count,
target.cycles,
target.hz
].join( ',' ) + '\n';
fs.appendFileSync( dest, line );
}; |
/* eslint-env mocha */
import Vue from 'vue-test'; // eslint-disable-line
import Vuex from 'vuex';
import sinon from 'sinon';
import { expect } from 'chai';
import { mount } from '@vue/test-utils';
import AssignmentCopyModal from '../../src/views/assignments/AssignmentCopyModal';
const defaultProps = {
modalTitle: '',
copyExplanation: '',
assignmentQuestion: '',
classId: 'class_2',
classList: [{ id: 'class_1', name: 'Class One' }, { id: 'class_2', name: 'Class Two' }],
};
// prettier-ignore
function makeWrapper(options) {
const wrapper = mount(AssignmentCopyModal, options)
const els = {
selectClassroomForm: () => wrapper.find('form#select-classroom'),
selectLearnerGroupForm: () => wrapper.find('form#select-learnergroup'),
submitButton: () => wrapper.find('button[type="submit"]')
};
return { wrapper, els }
}
describe('AssignmentCopyModal', () => {
let store;
beforeEach(() => {
store = new Vuex.Store();
});
it('starts on the Select Classroom form', () => {
const { els } = makeWrapper({
propsData: { ...defaultProps },
store,
});
expect(els.selectClassroomForm().exists()).to.be.true;
expect(els.selectLearnerGroupForm().exists()).to.be.false;
});
it('shows one radio button for each classroom', () => {
const { els } = makeWrapper({
propsData: { ...defaultProps },
store,
});
const classroomRadios = els.selectClassroomForm().findAll({ name: 'kRadioButton' });
expect(classroomRadios.length).to.equal(2);
});
it('first classroom radio button is the current class and has special label', () => {
const { els } = makeWrapper({
propsData: { ...defaultProps },
store,
});
const currentClassroomRadio = els
.selectClassroomForm()
.findAll({ name: 'kRadioButton' })
.at(0);
expect(currentClassroomRadio.props().label).to.equal('Class Two (current class)');
});
it('clicking continue on Select Classroom form goes to Select Learner Group form', () => {
const groups = [{ name: 'group 1', id: 'group_1' }];
const { wrapper, els } = makeWrapper({
propsData: { ...defaultProps },
store,
});
sinon.stub(wrapper.vm, 'getLearnerGroupsForClassroom').returns(Promise.resolve(groups));
return wrapper.vm.goToAvailableGroups().then(() => {
expect(els.selectLearnerGroupForm().exists()).to.be.true;
// Explanations should reflect the selection of Class Two (current class)
// prettier-ignore
const explanation = wrapper.find('p').text();
expect(explanation).to.equal(`Will be copied to 'Class Two'`);
// Recipient selector gets all of the groups
const recipientSelector = els.selectLearnerGroupForm().find({ name: 'recipientSelector' });
expect(recipientSelector.props().groups).to.deep.equal(groups);
});
});
it('clicking submit on Select Learner Group form causes modal to emit a "copy" event', () => {
const { wrapper, els } = makeWrapper({
propsData: { ...defaultProps },
store,
});
sinon.stub(wrapper.vm, 'getLearnerGroupsForClassroom').returns(Promise.resolve([]));
return wrapper.vm.goToAvailableGroups().then(() => {
els.selectLearnerGroupForm().trigger('submit');
// By default, this will copy the Assignment to the same class, and the entire class
expect(wrapper.emitted().copy[0]).to.deep.equal(['class_2', ['class_2']]);
});
});
// not tested:
// clicking cancel
// error handling
});
|
window.addEvent('domready', function() {
prettyPrint()
document.getElements('[data-example]').each(function(el) {
el.addClass('simulated-example');
Moobile.Simulator.create('iPhone', el.get('data-example'), { container: el });
});
document.getElements('[data-simulator-app]').each(function(el) {
el.addClass('simulator-wrapper');
var simulator = new Moobile.Simulator({container: el});
simulator.setDevice(el.get('data-device') || 'iPhone5');
simulator.setDeviceOrientation(el.get('data-orientation') || 'portrait');
simulator.setApplication(el.get('data-simulator-app'));
});
document.getElements('.sidebar a').each(function(el) {
var href = el.get('href').replace('../../', '');
if (window.location.pathname.contains(href)) {
el.addClass('current');
}
});
document.getElements('.table-of-contents a').each(function(el) {
el.addEvent('click', function(e) {
e.stop();
document.location.hash = this.href.split('#')[1];
});
});
}); |
var ExtendError = require('../error').ExtendError,
types = require('swig/lib/lexer').types;
/**
* This class is used to manage all tag plugins in Hexo.
*
* @class Tag
* @constructor
* @namespace Extend
* @module hexo
*/
var Tag = module.exports = function(){
/**
* @property store
* @type Object
*/
this.store = [];
};
/**
* Returns a list of tag plugins.
*
* @method list
* @return {Object}
*/
Tag.prototype.list = function(){
return this.store;
};
/**
* Registers a tag plugin.
*
* @method register
* @param {String} name
* @param {Function} fn
* @param {Boolean} [ends=false]
*/
Tag.prototype.register = function(name, fn, ends){
if (typeof fn !== 'function'){
throw new ExtendError('Tag function is not defined');
}
var tag = {
name: name,
ends: ends
};
tag.parse = function(str, line, parser, types, options){
// Hack: Don't let Swig parse tokens
parser.on('*', function(token){
switch (token.type){
case types.WHITESPACE:
this.out.push(' ');
break;
case types.DOTKEY:
this.out.push('.');
break;
case types.FILTER:
case types.FILTEREMPTY:
this.out.push('|');
break;
}
token.type = types.STRING;
return true;
});
return true;
};
tag.compile = function(compiler, args, content, parents, options, blockName){
var tokens = content.join(''),
match = tokens.match(/^\n(\t*)/),
indent = match ? match[1].length : 0,
raw = [];
tokens.replace(/^\n*/, '').replace(/\n*$/, '').split('\n').forEach(function(line){
if (indent){
raw.push(line.replace(new RegExp('^\\t{' + indent + '}'), ''));
} else {
raw.push(line);
}
});
var result = fn(args.join('').split(' '), raw.join('\n'));
if (!result) return '';
result = result
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/"/g, '\\"');
var out = [
'(function(){',
'_output += "<escape indent=\'' + indent + '\'>' + result + '</escape>";',
'return _output;',
'})();'
].join('\n');
return out;
};
this.store.push(tag);
}; |
import _curry3 from './internal/_curry3';
/**
* Takes a function and two values, and returns whichever value produces the
* larger result when passed to the provided function.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Relation
* @sig Ord b => (a -> b) -> a -> a -> a
* @param {Function} f
* @param {*} a
* @param {*} b
* @return {*}
* @see R.max, R.minBy
* @example
*
* // square :: Number -> Number
* var square = n => n * n;
*
* R.maxBy(square, -3, 2); //=> -3
*
* R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5
* R.reduce(R.maxBy(square), 0, []); //=> 0
*/
var maxBy = _curry3(function maxBy(f, a, b) {
return f(b) > f(a) ? b : a;
});
export default maxBy;
|
import Component from '@ember/component';
import template from './template';
import { tagName, layout } from '@ember-decorators/component';
@tagName('')
@layout(template)
class PaperSelectSearchMessage extends Component {
}
export default PaperSelectSearchMessage;
|
const expect = require('chai').expect;
const React = require('react');
import { mount } from 'enzyme';
import { Provider } from 'react-redux';
import RecipeEntry from '../../client/components/RecipeEntry.js';
import fakeStore from './fakeStore';
const recipe = { title: 'Recipe Title' };
describe('<RecipeEntry />', () => {
let wrapper;
beforeEach('render Profile', () => {
wrapper = mount(
<Provider store={fakeStore}>
<RecipeEntry recipe={recipe} />
</Provider>);
});
it('should render without problems', () => {
expect(wrapper.find(RecipeEntry)).to.have.length(1);
});
it('should display the recipe name', () => {
expect(wrapper.find('.recipe-entry-title').text()).to.equal(recipe.title);
});
});
|
const path = require('path');
const Promise = require('bluebird');
const {i18n} = require('../../lib/common');
const errors = require('@tryghost/errors');
const dbBackup = require('../../data/db/backup');
const models = require('../../models');
const permissionsService = require('../../services/permissions');
const ALLOWED_INCLUDES = ['count.posts', 'permissions', 'roles', 'roles.permissions'];
const UNSAFE_ATTRS = ['status', 'roles'];
module.exports = {
docName: 'users',
browse: {
options: [
'include',
'filter',
'fields',
'limit',
'order',
'page',
'debug'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
}
}
},
permissions: true,
query(frame) {
return models.User.findPage(frame.options);
}
},
read: {
options: [
'include',
'filter',
'fields',
'debug'
],
data: [
'id',
'slug',
'email',
'role'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
}
}
},
permissions: true,
query(frame) {
return models.User.findOne(frame.data, frame.options)
.then((model) => {
if (!model) {
return Promise.reject(new errors.NotFoundError({
message: i18n.t('errors.api.users.userNotFound')
}));
}
return model;
});
}
},
edit: {
headers: {},
options: [
'id',
'include'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
},
id: {
required: true
}
}
},
permissions: {
unsafeAttrs: UNSAFE_ATTRS
},
query(frame) {
return models.User.edit(frame.data.users[0], frame.options)
.then((model) => {
if (!model) {
return Promise.reject(new errors.NotFoundError({
message: i18n.t('errors.api.users.userNotFound')
}));
}
if (model.wasChanged()) {
this.headers.cacheInvalidate = true;
} else {
this.headers.cacheInvalidate = false;
}
return model;
});
}
},
destroy: {
headers: {
cacheInvalidate: true
},
options: [
'id'
],
validation: {
options: {
id: {
required: true
}
}
},
permissions: true,
async query(frame) {
const backupPath = await dbBackup.backup();
const parsedFileName = path.parse(backupPath);
const filename = `${parsedFileName.name}${parsedFileName.ext}`;
return models.Base.transaction((t) => {
frame.options.transacting = t;
return models.Post.destroyByAuthor(frame.options)
.then(() => {
return models.User.destroy(Object.assign({status: 'all'}, frame.options));
})
.then(() => filename);
}).catch((err) => {
return Promise.reject(new errors.NoPermissionError({
err: err
}));
});
}
},
changePassword: {
validation: {
docName: 'password',
data: {
newPassword: {required: true},
ne2Password: {required: true},
user_id: {required: true}
}
},
permissions: {
docName: 'user',
method: 'edit',
identifier(frame) {
return frame.data.password[0].user_id;
}
},
query(frame) {
frame.options.skipSessionID = frame.original.session.id;
return models.User.changePassword(frame.data.password[0], frame.options);
}
},
transferOwnership: {
permissions(frame) {
return models.Role.findOne({name: 'Owner'})
.then((ownerRole) => {
return permissionsService.canThis(frame.options.context).assign.role(ownerRole);
});
},
query(frame) {
return models.User.transferOwnership(frame.data.owner[0], frame.options);
}
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:57011f078c3553835f2c4853a065baf60bc6c66a5221870a5d571087aaa3a47b
size 2280
|
'use strict';
var assign = require('object-assign');
var XMLNode = require('./xml');
function SVG() {
this.width = 100;
this.height = 100;
this.svg = new XMLNode('svg');
this.context = []; // Track nested nodes
this.setAttributes(this.svg, {
xmlns: 'http://www.w3.org/2000/svg',
width: this.width,
height: this.height
});
return this;
}
module.exports = SVG;
// This is a hack so groups work.
SVG.prototype.currentContext = function () {
return this.context[this.context.length - 1] || this.svg;
};
// This is a hack so groups work.
SVG.prototype.end = function () {
this.context.pop();
return this;
};
SVG.prototype.currentNode = function () {
var context = this.currentContext();
return context.lastChild || context;
};
SVG.prototype.transform = function (transformations) {
this.currentNode().setAttribute('transform',
Object.keys(transformations).map(function (transformation) {
return transformation + '(' + transformations[transformation].join(',') + ')';
}).join(' ')
);
return this;
};
SVG.prototype.setAttributes = function (el, attrs) {
Object.keys(attrs).forEach(function (attr) {
el.setAttribute(attr, attrs[attr]);
});
};
SVG.prototype.setWidth = function (width) {
this.svg.setAttribute('width', Math.floor(width));
};
SVG.prototype.setHeight = function (height) {
this.svg.setAttribute('height', Math.floor(height));
};
SVG.prototype.toString = function () {
return this.svg.toString();
};
SVG.prototype.rect = function (x, y, width, height, args) {
// Accept array first argument
var self = this;
if (Array.isArray(x)) {
x.forEach(function (a) {
self.rect.apply(self, a.concat(args));
});
return this;
}
var rect = new XMLNode('rect');
this.currentContext().appendChild(rect);
this.setAttributes(rect, assign({
x: x,
y: y,
width: width,
height: height
}, args));
return this;
};
SVG.prototype.circle = function (cx, cy, r, args) {
var circle = new XMLNode('circle');
this.currentContext().appendChild(circle);
this.setAttributes(circle, assign({
cx: cx,
cy: cy,
r: r
}, args));
return this;
};
SVG.prototype.path = function (str, args) {
var path = new XMLNode('path');
this.currentContext().appendChild(path);
this.setAttributes(path, assign({
d: str
}, args));
return this;
};
SVG.prototype.polyline = function (str, args) {
// Accept array first argument
var self = this;
if (Array.isArray(str)) {
str.forEach(function (s) {
self.polyline(s, args);
});
return this;
}
var polyline = new XMLNode('polyline');
this.currentContext().appendChild(polyline);
this.setAttributes(polyline, assign({
points: str
}, args));
return this;
};
// group and context are hacks
SVG.prototype.group = function (args) {
var group = new XMLNode('g');
this.currentContext().appendChild(group);
this.context.push(group);
this.setAttributes(group, assign({}, args));
return this;
};
|
var Swarm = require('swarm');
var Spec = Swarm.Spec;
var TodoList = require('./model/TodoList');
var TodoItem = require('./model/TodoItem');
var TodoApp = require('./TodoApp');
module.exports = window.TodoApp = (function(superclass){
var defaultModels = [];
// TODO: default english version
defaultModels.push({text:'распределенное приложение как локальное', completed: location.hash !== "#focused"});
defaultModels.push({text:'всё очень быстро', completed: true});
defaultModels.push({text:'теперь доступно каждому!', completed: true});
var prototype = extend$((import$(S, superclass), S), superclass).prototype, constructor = S;
function S(ssnid, itemId){
this.path = [];
this.ssnid = ssnid;
this.moving = false;
this.initSwarm();
this.installListeners();
this.parseUri();
if (location.hash === '#focused') {
this.selectItem(0);
}
}
prototype.initSwarm = function () {
this.storage = new Swarm.SharedWebStorage();
this.storage.authoritative = true;
this.host = Swarm.env.localhost =
new Swarm.Host(this.ssnid,'',this.storage);
};
prototype.installListeners = function () {
var self = this;
document.addEventListener('keydown', function (ev) {
switch (ev.keyCode) {
// case 9: self.forward();break; // tab
// case 27: self.back(); break; // esc
case 40: self.down(); break; // down arrow
case 38: self.up(); break; // up arrow
case 45: self.toggle(); break; // insert
case 13: self.create(); break; // enter
//case 46: self.delete(); break; // delete
default: return true;
}
ev.preventDefault();
return false;
});
};
prototype.parseUri = function () {
var hash = window.localStorage.getItem(".itemId");
var path = window.localStorage.getItem(".listId");
var idre = Spec.reQTokExt;
idre.lastIndex = 0;
var ml = idre.exec(path), listId = ml&&ml[2];
idre.lastIndex = 0;
var mi = idre.exec(hash), itemId = mi&&mi[2];
if (!listId) {
var list = new TodoList();
var item = new TodoItem();
list.addObject(item);
listId = list._id;
itemId = item._id;
}
this.forward(listId,itemId);
};
prototype.forward = function (listId, itemId) {
var self = this;
var fwdList;
if (!listId) {
var item = this.getItem();
listId = item.childList;
}
if (!listId) {
fwdList = new TodoList();
listId = fwdList._id;
item.set({childList: listId});
} else {
fwdList = this.host.get('/TodoList#'+listId); // TODO fn+id sig
}
// we may need to fetch the data from the server so we use a callback, yes
fwdList.once('.init',function(){
if (!fwdList.length()) {
defaultModels.forEach(function(i){
fwdList.addObject(new TodoItem(i));
})
}
itemId = itemId || fwdList.objectAt(0)._id;
window.localStorage.setItem(".itemId", "#" + itemId);
window.localStorage.setItem(".listId", "/" + listId);
self.path.push({
listId: listId,
itemId: itemId
});
self.refresh();
});
};
return S;
}(TodoApp));
function extend$(sub, sup){
function fun(){} fun.prototype = (sub.superclass = sup).prototype;
(sub.prototype = new fun).constructor = sub;
if (typeof sup.extended == 'function') sup.extended(sub);
return sub;
}
function import$(obj, src){
var own = {}.hasOwnProperty;
for (var key in src) if (own.call(src, key)) obj[key] = src[key];
return obj;
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _util = require('../util');
var _styleUtils = require('style-utils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var PathPlugin = function PathPlugin(target, vars) {
this.target = target;
var path = typeof vars === 'string' ? vars : vars.x || vars.y || vars.rotate;
this.vars = vars;
this.path = (0, _util.parsePath)(path);
this.start = {};
this.pathLength = this.path.getTotalLength();
};
PathPlugin.prototype = {
name: 'path',
useStyle: 'transform',
getComputedStyle: function getComputedStyle() {
return document.defaultView ? document.defaultView.getComputedStyle(this.target) : {};
},
getPoint: function getPoint(offset) {
var o = offset || 0;
var p = this.pathLength * this.progress + o;
return this.path.getPointAtLength(p);
},
getAnimStart: function getAnimStart() {
var computedStyle = this.getComputedStyle();
var transform = (0, _styleUtils.getTransform)(computedStyle[(0, _styleUtils.checkStyleName)('transform')]);
this.start = transform;
this.data = (0, _extends3["default"])({}, transform);
},
setRatio: function setRatio(r, t) {
this.progress = r;
var p = this.getPoint();
var p0 = this.getPoint(-1);
var p1 = this.getPoint(1);
if (typeof this.vars === 'string') {
this.data.translateX = p.x + this.start.translateX;
this.data.translateY = p.y + this.start.translateY;
this.data.rotate = Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI;
} else {
this.data.translateX = this.vars.x ? p.x + this.start.translateX : this.data.translateX;
this.data.translateY = this.vars.y ? p.y + this.start.translateY : this.data.translateY;
this.data.rotate = this.vars.rotate ? Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI : this.data.rotate;
}
t.style.transform = (0, _util.getTransformValue)(this.data);
}
};
exports["default"] = PathPlugin;
module.exports = exports['default']; |
(function(){
'use strict';
angular.module('myApp.AdminModule')
.service('userService', ['$q', UserService]);
/**
* Users DataService
* Uses embedded, hard-coded data model; acts asynchronously to simulate
* remote data service call(s).
*
* @returns {{loadAll: Function}}
* @constructor
*/
function UserService($q){
var users = [
{
name: 'Lia Lugo',
avatar: 'svg-1',
content: 'I love cheese, especially airedale queso. Cheese and biscuits halloumi cauliflower cheese cottage cheese swiss boursin fondue caerphilly. Cow port-salut camembert de normandie macaroni cheese feta who moved my cheese babybel boursin. Red leicester roquefort boursin squirty cheese jarlsberg blue castello caerphilly chalk and cheese. Lancashire.'
},
{
name: 'George Duke',
avatar: 'svg-2',
content: 'Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris.'
},
{
name: 'Gener Delosreyes',
avatar: 'svg-3',
content: "Raw denim pour-over readymade Etsy Pitchfork. Four dollar toast pickled locavore bitters McSweeney's blog. Try-hard art party Shoreditch selfies. Odd Future butcher VHS, disrupt pop-up Thundercats chillwave vinyl jean shorts taxidermy master cleanse letterpress Wes Anderson mustache Helvetica. Schlitz bicycle rights chillwave irony lumberhungry Kickstarter next level sriracha typewriter Intelligentsia, migas kogi heirloom tousled. Disrupt 3 wolf moon lomo four loko. Pug mlkshk fanny pack literally hoodie bespoke, put a bird on it Marfa messenger bag kogi VHS."
},
{
name: 'Lawrence Ray',
avatar: 'svg-4',
content: 'Scratch the furniture spit up on light gray carpet instead of adjacent linoleum so eat a plant, kill a hand pelt around the house and up and down stairs chasing phantoms run in circles, or claw drapes. Always hungry pelt around the house and up and down stairs chasing phantoms.'
},
{
name: 'Ernesto Urbina',
avatar: 'svg-5',
content: 'Webtwo ipsum dolor sit amet, eskobo chumby doostang bebo. Bubbli greplin stypi prezi mzinga heroku wakoopa, shopify airbnb dogster dopplr gooru jumo, reddit plickers edmodo stypi zillow etsy.'
},
{
name: 'Gani Ferrer',
avatar: 'svg-6',
content: "Lebowski ipsum yeah? What do you think happens when you get rad? You turn in your library card? Get a new driver's license? Stop being awesome? Dolor sit amet, consectetur adipiscing elit praesent ac magna justo pellentesque ac lectus. You don't go out and make a living dressed like that in the middle of a weekday. Quis elit blandit fringilla a ut turpis praesent felis ligula, malesuada suscipit malesuada."
}
];
// Promise-based API
return {
loadAllUsers : function() {
// Simulate async nature of real remote calls
return $q.when(users);
}
};
}
})(); |
/*!
* @license twgl.js 2.8.2 Copyright (c) 2015, Gregg Tavares All Rights Reserved.
* Available via the MIT license.
* see: http://github.com/greggman/twgl.js for details
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["twgl"] = factory();
else
root["twgl"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(1), __webpack_require__(10), __webpack_require__(11), __webpack_require__(12)], __WEBPACK_AMD_DEFINE_RESULT__ = function (twgl, m4, v3, primitives) {
"use strict";
twgl.m4 = m4;
twgl.v3 = v3;
twgl.primitives = primitives;
return twgl;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(2), __webpack_require__(5), __webpack_require__(7), __webpack_require__(6), __webpack_require__(8), __webpack_require__(3), __webpack_require__(9), __webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (attributes, draw, framebuffers, programs, textures, typedArrays, vertexArrays, utils) {
"use strict";
/**
* The main TWGL module.
*
* For most use cases you shouldn't need anything outside this module.
* Exceptions between the stuff added to twgl-full (v3, m4, primitives)
*
* @module twgl
* @borrows module:twgl/attributes.setAttribInfoBufferFromArray as setAttribInfoBufferFromArray
* @borrows module:twgl/attributes.createBufferInfoFromArrays as createBufferInfoFromArrays
* @borrows module:twgl/attributes.createVertexArrayInfo as createVertexArrayInfo
* @borrows module:twgl/draw.drawBufferInfo as drawBufferInfo
* @borrows module:twgl/draw.drawObjectList as drawObjectList
* @borrows module:twgl/framebuffers.createFramebufferInfo as createFramebufferInfo
* @borrows module:twgl/framebuffers.resizeFramebufferInfo as resizeFramebufferInfo
* @borrows module:twgl/framebuffers.bindFramebufferInfo as bindFramebufferInfo
* @borrows module:twgl/programs.createProgramInfo as createProgramInfo
* @borrows module:twgl/programs.createUniformBlockInfo as createUniformBlockInfo
* @borrows module:twgl/programs.bindUniformBlock as bindUniformBlock
* @borrows module:twgl/programs.setUniformBlock as setUniformBlock
* @borrows module:twgl/programs.setBlockUniforms as setBlockUniforms
* @borrows module:twgl/programs.setUniforms as setUniforms
* @borrows module:twgl/programs.setBuffersAndAttributes as setBuffersAndAttributes
* @borrows module:twgl/textures.setTextureFromArray as setTextureFromArray
* @borrows module:twgl/textures.createTexture as createTexture
* @borrows module:twgl/textures.resizeTexture as resizeTexture
* @borrows module:twgl/textures.createTextures as createTextures
*/
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
var defaults = {
enableVertexArrayObjects: true
};
/**
* Various default settings for twgl.
*
* Note: You can call this any number of times. Example:
*
* twgl.setDefaults({ textureColor: [1, 0, 0, 1] });
* twgl.setDefaults({ attribPrefix: 'a_' });
*
* is equivalent to
*
* twgl.setDefaults({
* textureColor: [1, 0, 0, 1],
* attribPrefix: 'a_',
* });
*
* @typedef {Object} Defaults
* @property {string} attribPrefix The prefix to stick on attributes
*
* When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`
* as it makes it clear where they came from. But, when building geometry I prefer using unprefixed names.
*
* In otherwords I'll create arrays of geometry like this
*
* var arrays = {
* position: ...
* normal: ...
* texcoord: ...
* };
*
* But need those mapped to attributes and my attributes start with `a_`.
*
* Default: `""`
*
* @property {number[]} textureColor Array of 4 values in the range 0 to 1
*
* The default texture color is used when loading textures from
* urls. Because the URL will be loaded async we'd like to be
* able to use the texture immediately. By putting a 1x1 pixel
* color in the texture we can start using the texture before
* the URL has loaded.
*
* Default: `[0.5, 0.75, 1, 1]`
*
* @property {string} crossOrigin
*
* If not undefined sets the crossOrigin attribute on images
* that twgl creates when downloading images for textures.
*
* Also see {@link module:twgl.TextureOptions}.
*
* @property {bool} enableVertexArrayObjects
*
* If true then in WebGL 1.0 will attempt to get the `OES_vertex_array_object` extension.
* If successful it will copy create/bind/delete/isVertexArrayOES from the extension to
* the WebGLRenderingContext removing the OES at the end which is the standard entry point
* for WebGL 2.
*
* Note: According to webglstats.com 90% of devices support `OES_vertex_array_object`.
* If you just want to count on support I suggest using [this polyfill](https://github.com/KhronosGroup/WebGL/blob/master/sdk/demos/google/resources/OESVertexArrayObject.js)
* or ignoring devices that don't support them.
*
* Default: `true`
*
* @memberOf module:twgl
*/
/**
* Sets various defaults for twgl.
*
* In the interest of terseness which is kind of the point
* of twgl I've integrated a few of the older functions here
*
* @param {module:twgl.Defaults} newDefaults The default settings.
* @memberOf module:twgl
*/
function setDefaults(newDefaults) {
utils.copyExistingProperties(newDefaults, defaults);
attributes.setDefaults_(newDefaults); // eslint-disable-line
textures.setDefaults_(newDefaults); // eslint-disable-line
}
/**
* Adds Vertex Array Objects to WebGL 1 GL contexts if available
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
*/
function addVertexArrayObjectSupport(gl) {
if (!gl || !defaults.enableVertexArrayObjects) {
return;
}
if (utils.isWebGL1(gl)) {
var ext = gl.getExtension("OES_vertex_array_object");
if (ext) {
gl.createVertexArray = function () {
return ext.createVertexArrayOES();
};
gl.deleteVertexArray = function (v) {
ext.deleteVertexArrayOES(v);
};
gl.isVertexArray = function (v) {
return ext.isVertexArrayOES(v);
};
gl.bindVertexArray = function (v) {
ext.bindVertexArrayOES(v);
};
gl.VERTEX_ARRAY_BINDING = ext.VERTEX_ARRAY_BINDING_OES;
}
}
}
/**
* Creates a webgl context.
* @param {HTMLCanvasElement} canvas The canvas tag to get
* context from. If one is not passed in one will be
* created.
* @return {WebGLRenderingContext} The created context.
*/
function create3DContext(canvas, opt_attribs) {
var names = ["webgl", "experimental-webgl"];
var context = null;
for (var ii = 0; ii < names.length; ++ii) {
try {
context = canvas.getContext(names[ii], opt_attribs);
} catch (e) {} // eslint-disable-line
if (context) {
break;
}
}
return context;
}
/**
* Gets a WebGL context.
* @param {HTMLCanvasElement} canvas a canvas element.
* @param {WebGLContextCreationAttirbutes} [opt_attribs] optional webgl context creation attributes
* @memberOf module:twgl
*/
function getWebGLContext(canvas, opt_attribs) {
var gl = create3DContext(canvas, opt_attribs);
addVertexArrayObjectSupport(gl);
return gl;
}
/**
* Creates a webgl context.
*
* Will return a WebGL2 context if possible.
*
* You can check if it's WebGL2 with
*
* twgl.isWebGL2(gl);
*
* @param {HTMLCanvasElement} canvas The canvas tag to get
* context from. If one is not passed in one will be
* created.
* @return {WebGLRenderingContext} The created context.
*/
function createContext(canvas, opt_attribs) {
var names = ["webgl2", "webgl", "experimental-webgl"];
var context = null;
for (var ii = 0; ii < names.length; ++ii) {
try {
context = canvas.getContext(names[ii], opt_attribs);
} catch (e) {} // eslint-disable-line
if (context) {
break;
}
}
return context;
}
/**
* Gets a WebGL context. Will create a WebGL2 context if possible.
*
* You can check if it's WebGL2 with
*
* function isWebGL2(gl) {
* return gl.getParameter(gl.VERSION).indexOf("WebGL 2.0 ") == 0;
* }
*
* @param {HTMLCanvasElement} canvas a canvas element.
* @param {WebGLContextCreationAttirbutes} [opt_attribs] optional webgl context creation attributes
* @return {WebGLRenderingContext} The created context.
* @memberOf module:twgl
*/
function getContext(canvas, opt_attribs) {
var gl = createContext(canvas, opt_attribs);
addVertexArrayObjectSupport(gl);
return gl;
}
/**
* Resize a canvas to match the size it's displayed.
* @param {HTMLCanvasElement} canvas The canvas to resize.
* @param {number} [multiplier] So you can pass in `window.devicePixelRatio` if you want to.
* @return {boolean} true if the canvas was resized.
* @memberOf module:twgl
*/
function resizeCanvasToDisplaySize(canvas, multiplier) {
multiplier = multiplier || 1;
multiplier = Math.max(1, multiplier);
var width = canvas.clientWidth * multiplier | 0;
var height = canvas.clientHeight * multiplier | 0;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
return false;
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
var api = {
"getContext": getContext,
"getWebGLContext": getWebGLContext,
"isWebGL1": utils.isWebGL1,
"isWebGL2": utils.isWebGL2,
"resizeCanvasToDisplaySize": resizeCanvasToDisplaySize,
"setDefaults": setDefaults
};
function notPrivate(name) {
return name[name.length - 1] !== '_';
}
function copyPublicProperties(src, dst) {
Object.keys(src).filter(notPrivate).forEach(function (key) {
dst[key] = src[key];
});
return dst;
}
var apis = {
attributes: attributes,
draw: draw,
framebuffers: framebuffers,
programs: programs,
textures: textures,
typedArrays: typedArrays,
vertexArrays: vertexArrays
};
Object.keys(apis).forEach(function (name) {
var srcApi = apis[name];
copyPublicProperties(srcApi, api);
api[name] = copyPublicProperties(srcApi, {});
});
return api;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(3), __webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (typedArrays, utils) {
"use strict";
/**
* Low level attribute and buffer related functions
*
* You should generally not need to use these functions. They are provided
* for those cases where you're doing something out of the ordinary
* and you need lower level access.
*
* For backward compatibily they are available at both `twgl.attributes` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/attributes
*/
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
var defaults = {
attribPrefix: ""
};
/**
* Sets the default attrib prefix
*
* When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`
* as it makes it clear where they came from. But, when building geometry I prefer using unprefixed names.
*
* In otherwords I'll create arrays of geometry like this
*
* var arrays = {
* position: ...
* normal: ...
* texcoord: ...
* };
*
* But need those mapped to attributes and my attributes start with `a_`.
*
* @deprecated see {@link module:twgl.setDefaults}
* @param {string} prefix prefix for attribs
* @memberOf module:twgl/attributes
*/
function setAttributePrefix(prefix) {
defaults.attribPrefix = prefix;
}
function setDefaults(newDefaults) {
utils.copyExistingProperties(newDefaults, defaults);
}
function setBufferFromTypedArray(gl, type, buffer, array, drawType) {
gl.bindBuffer(type, buffer);
gl.bufferData(type, array, drawType || gl.STATIC_DRAW);
}
/**
* Given typed array creates a WebGLBuffer and copies the typed array
* into it.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {ArrayBuffer|ArrayBufferView|WebGLBuffer} typedArray the typed array. Note: If a WebGLBuffer is passed in it will just be returned. No action will be taken
* @param {number} [type] the GL bind type for the buffer. Default = `gl.ARRAY_BUFFER`.
* @param {number} [drawType] the GL draw type for the buffer. Default = 'gl.STATIC_DRAW`.
* @return {WebGLBuffer} the created WebGLBuffer
* @memberOf module:twgl/attributes
*/
function createBufferFromTypedArray(gl, typedArray, type, drawType) {
if (typedArray instanceof WebGLBuffer) {
return typedArray;
}
type = type || gl.ARRAY_BUFFER;
var buffer = gl.createBuffer();
setBufferFromTypedArray(gl, type, buffer, typedArray, drawType);
return buffer;
}
function isIndices(name) {
return name === "indices";
}
// This is really just a guess. Though I can't really imagine using
// anything else? Maybe for some compression?
function getNormalizationForTypedArray(typedArray) {
if (typedArray instanceof Int8Array) {
return true;
} // eslint-disable-line
if (typedArray instanceof Uint8Array) {
return true;
} // eslint-disable-line
return false;
}
function getArray(array) {
return array.length ? array : array.data;
}
var texcoordRE = /coord|texture/i;
var colorRE = /color|colour/i;
function guessNumComponentsFromName(name, length) {
var numComponents;
if (texcoordRE.test(name)) {
numComponents = 2;
} else if (colorRE.test(name)) {
numComponents = 4;
} else {
numComponents = 3; // position, normals, indices ...
}
if (length % numComponents > 0) {
throw "Can not guess numComponents for attribute '" + name + "'. Tried " + numComponents + " but " + length + " values is not evenly divisible by " + numComponents + ". You should specify it.";
}
return numComponents;
}
function getNumComponents(array, arrayName) {
return array.numComponents || array.size || guessNumComponentsFromName(arrayName, getArray(array).length);
}
function makeTypedArray(array, name) {
if (typedArrays.isArrayBuffer(array)) {
return array;
}
if (typedArrays.isArrayBuffer(array.data)) {
return array.data;
}
if (Array.isArray(array)) {
array = {
data: array
};
}
var Type = array.type;
if (!Type) {
if (isIndices(name)) {
Type = Uint16Array;
} else {
Type = Float32Array;
}
}
return new Type(array.data);
}
/**
* The info for an attribute. This is effectively just the arguments to `gl.vertexAttribPointer` plus the WebGLBuffer
* for the attribute.
*
* @typedef {Object} AttribInfo
* @property {number} [numComponents] the number of components for this attribute.
* @property {number} [size] synonym for `numComponents`.
* @property {number} [type] the type of the attribute (eg. `gl.FLOAT`, `gl.UNSIGNED_BYTE`, etc...) Default = `gl.FLOAT`
* @property {boolean} [normalized] whether or not to normalize the data. Default = false
* @property {number} [offset] offset into buffer in bytes. Default = 0
* @property {number} [stride] the stride in bytes per element. Default = 0
* @property {WebGLBuffer} buffer the buffer that contains the data for this attribute
* @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW
* @memberOf module:twgl
*/
/**
* Use this type of array spec when TWGL can't guess the type or number of compoments of an array
* @typedef {Object} FullArraySpec
* @property {(number[]|ArrayBuffer)} data The data of the array.
* @property {number} [numComponents] number of components for `vertexAttribPointer`. Default is based on the name of the array.
* If `coord` is in the name assumes `numComponents = 2`.
* If `color` is in the name assumes `numComponents = 4`.
* otherwise assumes `numComponents = 3`
* @property {constructor} type The type. This is only used if `data` is a JavaScript array. It is the constructor for the typedarray. (eg. `Uint8Array`).
* For example if you want colors in a `Uint8Array` you might have a `FullArraySpec` like `{ type: Uint8Array, data: [255,0,255,255, ...], }`.
* @property {number} [size] synonym for `numComponents`.
* @property {boolean} [normalize] normalize for `vertexAttribPointer`. Default is true if type is `Int8Array` or `Uint8Array` otherwise false.
* @property {number} [stride] stride for `vertexAttribPointer`. Default = 0
* @property {number} [offset] offset for `vertexAttribPointer`. Default = 0
* @property {string} [attrib] name of attribute this array maps to. Defaults to same name as array prefixed by the default attribPrefix.
* @property {string} [name] synonym for `attrib`.
* @property {string} [attribName] synonym for `attrib`.
* @memberOf module:twgl
*/
/**
* An individual array in {@link module:twgl.Arrays}
*
* When passed to {@link module:twgl.createBufferInfoFromArrays} if an ArraySpec is `number[]` or `ArrayBuffer`
* the types will be guessed based on the name. `indices` will be `Uint16Array`, everything else will
* be `Float32Array`
*
* @typedef {(number[]|ArrayBuffer|module:twgl.FullArraySpec)} ArraySpec
* @memberOf module:twgl
*/
/**
* This is a JavaScript object of arrays by name. The names should match your shader's attributes. If your
* attributes have a common prefix you can specify it by calling {@link module:twgl.setAttributePrefix}.
*
* Bare JavaScript Arrays
*
* var arrays = {
* position: [-1, 1, 0],
* normal: [0, 1, 0],
* ...
* }
*
* Bare TypedArrays
*
* var arrays = {
* position: new Float32Array([-1, 1, 0]),
* color: new Uint8Array([255, 128, 64, 255]),
* ...
* }
*
* * Will guess at `numComponents` if not specified based on name.
*
* If `coord` is in the name assumes `numComponents = 2`
*
* If `color` is in the name assumes `numComponents = 4`
*
* otherwise assumes `numComponents = 3`
*
* Objects with various fields. See {@link module:twgl.FullArraySpec}.
*
* var arrays = {
* position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
* texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
* normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },
* indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },
* };
*
* @typedef {Object.<string, module:twgl.ArraySpec>} Arrays
* @memberOf module:twgl
*/
/**
* Creates a set of attribute data and WebGLBuffers from set of arrays
*
* Given
*
* var arrays = {
* position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
* texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
* normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },
* color: { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, },
* indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },
* };
*
* returns something like
*
* var attribs = {
* position: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },
* texcoord: { numComponents: 2, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },
* normal: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },
* color: { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true, buffer: WebGLBuffer, },
* };
*
* notes:
*
* * Arrays can take various forms
*
* Bare JavaScript Arrays
*
* var arrays = {
* position: [-1, 1, 0],
* normal: [0, 1, 0],
* ...
* }
*
* Bare TypedArrays
*
* var arrays = {
* position: new Float32Array([-1, 1, 0]),
* color: new Uint8Array([255, 128, 64, 255]),
* ...
* }
*
* * Will guess at `numComponents` if not specified based on name.
*
* If `coord` is in the name assumes `numComponents = 2`
*
* If `color` is in the name assumes `numComponents = 4`
*
* otherwise assumes `numComponents = 3`
*
* @param {WebGLRenderingContext} gl The webgl rendering context.
* @param {module:twgl.Arrays} arrays The arrays
* @return {Object.<string, module:twgl.AttribInfo>} the attribs
* @memberOf module:twgl/attributes
*/
function createAttribsFromArrays(gl, arrays) {
var attribs = {};
Object.keys(arrays).forEach(function (arrayName) {
if (!isIndices(arrayName)) {
var array = arrays[arrayName];
var attribName = array.attrib || array.name || array.attribName || defaults.attribPrefix + arrayName;
var typedArray = makeTypedArray(array, arrayName);
attribs[attribName] = {
buffer: createBufferFromTypedArray(gl, typedArray, undefined, array.drawType),
numComponents: getNumComponents(array, arrayName),
type: typedArrays.getGLTypeForTypedArray(typedArray),
normalize: array.normalize !== undefined ? array.normalize : getNormalizationForTypedArray(typedArray),
stride: array.stride || 0,
offset: array.offset || 0,
drawType: array.drawType
};
}
});
return attribs;
}
/**
* Sets the contents of a buffer attached to an attribInfo
*
* This is helper function to dynamically update a buffer.
*
* Let's say you make a bufferInfo
*
* var arrays = {
* position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),
* texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),
* normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
* indices: new Uint16Array([0, 1, 2, 1, 2, 3]),
* };
* var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);
*
* And you want to dynamically upate the positions. You could do this
*
* // assuming arrays.position has already been updated with new data.
* twgl.setAttribInfoBufferFromArray(gl, bufferInfo.attribs.position, arrays.position);
*
* @param {WebGLRenderingContext} gl
* @param {AttribInfo} attribInfo The attribInfo who's buffer contents to set. NOTE: If you have an attribute prefix
* the name of the attribute will include the prefix.
* @param {ArraySpec} array Note: it is arguably ineffient to pass in anything but a typed array because anything
* else will have to be converted to a typed array before it can be used by WebGL. During init time that
* inefficiency is usually not important but if you're updating data dynamically best to be efficient.
* @param {number} [offset] an optional offset into the buffer. This is only an offset into the WebGL buffer
* not the array. To pass in an offset into the array itself use a typed array and create an `ArrayBufferView`
* for the portion of the array you want to use.
*
* var someArray = new Float32Array(1000); // an array with 1000 floats
* var someSubArray = new Float32Array(someArray.buffer, offsetInBytes, sizeInUnits); // a view into someArray
*
* Now you can pass `someSubArray` into setAttribInfoBufferFromArray`
* @memberOf module:twgl/attributes
*/
function setAttribInfoBufferFromArray(gl, attribInfo, array, offset) {
array = makeTypedArray(array);
if (offset !== undefined) {
gl.bindBuffer(gl.ARRAY_BUFFER, attribInfo.buffer);
gl.bufferSubData(gl.ARRAY_BUFFER, offset, array);
} else {
setBufferFromTypedArray(gl, gl.ARRAY_BUFFER, attribInfo.buffer, array, attribInfo.drawType);
}
}
/**
* tries to get the number of elements from a set of arrays.
*/
var getNumElementsFromNonIndexedArrays = function () {
var positionKeys = ['position', 'positions', 'a_position'];
return function getNumElementsFromNonIndexedArrays(arrays) {
var key;
for (var ii = 0; ii < positionKeys.length; ++ii) {
key = positionKeys[ii];
if (key in arrays) {
break;
}
}
if (ii === positionKeys.length) {
key = Object.keys(arrays)[0];
}
var array = arrays[key];
var length = getArray(array).length;
var numComponents = getNumComponents(array, key);
var numElements = length / numComponents;
if (length % numComponents > 0) {
throw "numComponents " + numComponents + " not correct for length " + length;
}
return numElements;
};
}();
/**
* @typedef {Object} BufferInfo
* @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.
* @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..
* @property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.
* @property {Object.<string, module:twgl.AttribInfo>} [attribs] The attribs approriate to call `setAttributes`
* @memberOf module:twgl
*/
/**
* Creates a BufferInfo from an object of arrays.
*
* This can be passed to {@link module:twgl.setBuffersAndAttributes} and to
* {@link module:twgl:drawBufferInfo}.
*
* Given an object like
*
* var arrays = {
* position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
* texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
* normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },
* indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },
* };
*
* Creates an BufferInfo like this
*
* bufferInfo = {
* numElements: 4, // or whatever the number of elements is
* indices: WebGLBuffer, // this property will not exist if there are no indices
* attribs: {
* a_position: { buffer: WebGLBuffer, numComponents: 3, },
* a_normal: { buffer: WebGLBuffer, numComponents: 3, },
* a_texcoord: { buffer: WebGLBuffer, numComponents: 2, },
* },
* };
*
* The properties of arrays can be JavaScript arrays in which case the number of components
* will be guessed.
*
* var arrays = {
* position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],
* texcoord: [0, 0, 0, 1, 1, 0, 1, 1],
* normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
* indices: [0, 1, 2, 1, 2, 3],
* };
*
* They can also by TypedArrays
*
* var arrays = {
* position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),
* texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),
* normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
* indices: new Uint16Array([0, 1, 2, 1, 2, 3]),
* };
*
* Or augmentedTypedArrays
*
* var positions = createAugmentedTypedArray(3, 4);
* var texcoords = createAugmentedTypedArray(2, 4);
* var normals = createAugmentedTypedArray(3, 4);
* var indices = createAugmentedTypedArray(3, 2, Uint16Array);
*
* positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]);
* texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]);
* normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);
* indices.push([0, 1, 2, 1, 2, 3]);
*
* var arrays = {
* position: positions,
* texcoord: texcoords,
* normal: normals,
* indices: indices,
* };
*
* For the last example it is equivalent to
*
* var bufferInfo = {
* attribs: {
* a_position: { numComponents: 3, buffer: gl.createBuffer(), },
* a_texcoods: { numComponents: 2, buffer: gl.createBuffer(), },
* a_normals: { numComponents: 3, buffer: gl.createBuffer(), },
* },
* indices: gl.createBuffer(),
* numElements: 6,
* };
*
* gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_position.buffer);
* gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);
* gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_texcoord.buffer);
* gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);
* gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_normal.buffer);
* gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW);
* gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices);
* gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {module:twgl.Arrays} arrays Your data
* @return {module:twgl.BufferInfo} A BufferInfo
* @memberOf module:twgl/attributes
*/
function createBufferInfoFromArrays(gl, arrays) {
var bufferInfo = {
attribs: createAttribsFromArrays(gl, arrays)
};
var indices = arrays.indices;
if (indices) {
indices = makeTypedArray(indices, "indices");
bufferInfo.indices = createBufferFromTypedArray(gl, indices, gl.ELEMENT_ARRAY_BUFFER);
bufferInfo.numElements = indices.length;
bufferInfo.elementType = typedArrays.getGLTypeForTypedArray(indices);
} else {
bufferInfo.numElements = getNumElementsFromNonIndexedArrays(arrays);
}
return bufferInfo;
}
/**
* Creates a buffer from an array, typed array, or array spec
*
* Given something like this
*
* [1, 2, 3],
*
* or
*
* new Uint16Array([1,2,3]);
*
* or
*
* {
* data: [1, 2, 3],
* type: Uint8Array,
* }
*
* returns a WebGLBuffer that constains the given data.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext.
* @param {module:twgl.ArraySpec} array an array, typed array, or array spec.
* @param {string} arrayName name of array. Used to guess the type if type can not be dervied other wise.
* @return {WebGLBuffer} a WebGLBuffer containing the data in array.
* @memberOf module:twgl/attributes
*/
function createBufferFromArray(gl, array, arrayName) {
var type = arrayName === "indices" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
var typedArray = makeTypedArray(array, arrayName);
return createBufferFromTypedArray(gl, typedArray, type);
}
/**
* Creates buffers from arrays or typed arrays
*
* Given something like this
*
* var arrays = {
* positions: [1, 2, 3],
* normals: [0, 0, 1],
* }
*
* returns something like
*
* buffers = {
* positions: WebGLBuffer,
* normals: WebGLBuffer,
* }
*
* If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext.
* @param {module:twgl.Arrays} arrays
* @return {Object<string, WebGLBuffer>} returns an object with one WebGLBuffer per array
* @memberOf module:twgl/attributes
*/
function createBuffersFromArrays(gl, arrays) {
var buffers = {};
Object.keys(arrays).forEach(function (key) {
buffers[key] = createBufferFromArray(gl, arrays[key], key);
});
// Ugh!
if (arrays.indices) {
buffers.numElements = arrays.indices.length;
buffers.elementType = typedArrays.getGLTypeForTypedArray(makeTypedArray(arrays.indices), 'indices');
} else {
buffers.numElements = getNumElementsFromNonIndexedArrays(arrays);
}
return buffers;
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"createAttribsFromArrays": createAttribsFromArrays,
"createBuffersFromArrays": createBuffersFromArrays,
"createBufferFromArray": createBufferFromArray,
"createBufferFromTypedArray": createBufferFromTypedArray,
"createBufferInfoFromArrays": createBufferInfoFromArrays,
"setAttribInfoBufferFromArray": setAttribInfoBufferFromArray,
"setAttributePrefix": setAttributePrefix,
"setDefaults_": setDefaults,
"getNumComponents_": getNumComponents,
"getArray_": getArray
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
"use strict";
/**
* Low level shader typed array related functions
*
* You should generally not need to use these functions. They are provided
* for those cases where you're doing something out of the ordinary
* and you need lower level access.
*
* For backward compatibily they are available at both `twgl.typedArray` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/typedArray
*/
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
/* DataType */
var BYTE = 0x1400;
var UNSIGNED_BYTE = 0x1401;
var SHORT = 0x1402;
var UNSIGNED_SHORT = 0x1403;
var INT = 0x1404;
var UNSIGNED_INT = 0x1405;
var FLOAT = 0x1406;
var UNSIGNED_SHORT_4_4_4_4 = 0x8033;
var UNSIGNED_SHORT_5_5_5_1 = 0x8034;
var UNSIGNED_SHORT_5_6_5 = 0x8363;
var HALF_FLOAT = 0x140B;
var UNSIGNED_INT_2_10_10_10_REV = 0x8368;
var UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;
var UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;
var FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD;
var UNSIGNED_INT_24_8 = 0x84FA;
var glTypeToTypedArray = {};
{
var tt = glTypeToTypedArray;
tt[BYTE] = Int8Array;
tt[UNSIGNED_BYTE] = Uint8Array;
tt[SHORT] = Int16Array;
tt[UNSIGNED_SHORT] = Uint16Array;
tt[INT] = Int32Array;
tt[UNSIGNED_INT] = Uint32Array;
tt[FLOAT] = Float32Array;
tt[UNSIGNED_SHORT_4_4_4_4] = Uint16Array;
tt[UNSIGNED_SHORT_5_5_5_1] = Uint16Array;
tt[UNSIGNED_SHORT_5_6_5] = Uint16Array;
tt[HALF_FLOAT] = Uint16Array;
tt[UNSIGNED_INT_2_10_10_10_REV] = Uint32Array;
tt[UNSIGNED_INT_10F_11F_11F_REV] = Uint32Array;
tt[UNSIGNED_INT_5_9_9_9_REV] = Uint32Array;
tt[FLOAT_32_UNSIGNED_INT_24_8_REV] = Uint32Array;
tt[UNSIGNED_INT_24_8] = Uint32Array;
}
/**
* Get the GL type for a typedArray
* @param {ArrayBuffer|ArrayBufferView} typedArray a typedArray
* @return {number} the GL type for array. For example pass in an `Int8Array` and `gl.BYTE` will
* be returned. Pass in a `Uint32Array` and `gl.UNSIGNED_INT` will be returned
* @memberOf module:twgl/typedArray
*/
function getGLTypeForTypedArray(typedArray) {
if (typedArray instanceof Int8Array) {
return BYTE;
} // eslint-disable-line
if (typedArray instanceof Uint8Array) {
return UNSIGNED_BYTE;
} // eslint-disable-line
if (typedArray instanceof Uint8ClampedArray) {
return UNSIGNED_BYTE;
} // eslint-disable-line
if (typedArray instanceof Int16Array) {
return SHORT;
} // eslint-disable-line
if (typedArray instanceof Uint16Array) {
return UNSIGNED_SHORT;
} // eslint-disable-line
if (typedArray instanceof Int32Array) {
return INT;
} // eslint-disable-line
if (typedArray instanceof Uint32Array) {
return UNSIGNED_INT;
} // eslint-disable-line
if (typedArray instanceof Float32Array) {
return FLOAT;
} // eslint-disable-line
throw "unsupported typed array type";
}
/**
* Get the typed array constructor for a given GL type
* @param {number} type the GL type. (eg: `gl.UNSIGNED_INT`)
* @return {function} the constructor for a the corresponding typed array. (eg. `Uint32Array`).
* @memberOf module:twgl/typedArray
*/
function getTypedArrayTypeForGLType(type) {
var CTOR = glTypeToTypedArray[type];
if (!CTOR) {
throw "unknown gl type";
}
return CTOR;
}
function isArrayBuffer(a) {
return a && a.buffer && a.buffer instanceof ArrayBuffer;
}
// Using quotes prevents Uglify from changing the names.
return {
"getGLTypeForTypedArray": getGLTypeForTypedArray,
"getTypedArrayTypeForGLType": getTypedArrayTypeForGLType,
"isArrayBuffer": isArrayBuffer
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
"use strict";
/**
* Copy an object 1 level deep
* @param {object} src object to copy
* @return {object} the copy
*/
function shallowCopy(src) {
var dst = {};
Object.keys(src).forEach(function (key) {
dst[key] = src[key];
});
return dst;
}
/**
* Copy named properties
*
* @param {string[]} names names of properties to copy
* @param {object} src object to copy properties from
* @param {object} dst object to copy properties to
*/
function copyNamedProperties(names, src, dst) {
names.forEach(function (name) {
var value = src[name];
if (value !== undefined) {
dst[name] = value;
}
});
}
/**
* Copies properties from source to dest only if a matching key is in dest
*
* @param {Object.<string, ?>} src the source
* @param {Object.<string, ?>} dst the dest
*/
function copyExistingProperties(src, dst) {
Object.keys(dst).forEach(function (key) {
if (dst.hasOwnProperty(key) && src.hasOwnProperty(key)) {
dst[key] = src[key];
}
});
}
/**
* Gets the gl version as a number
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @return {number} version of gl
*/
//function getVersionAsNumber(gl) {
// return parseFloat(gl.getParameter(gl.VERSION).substr(6));
//}
/**
* Check if context is WebGL 2.0
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @return {bool} true if it's WebGL 2.0
* @memberOf module:twgl
*/
function isWebGL2(gl) {
// This is the correct check but it's slow
//return gl.getParameter(gl.VERSION).indexOf("WebGL 2.0") === 0;
// This might also be the correct check but I'm assuming it's slow-ish
// return gl instanceof WebGL2RenderingContext;
return !!gl.texStorage2D;
}
/**
* Check if context is WebGL 1.0
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @return {bool} true if it's WebGL 1.0
* @memberOf module:twgl
*/
function isWebGL1(gl) {
// This is the correct check but it's slow
//var version = getVersionAsNumber(gl);
//return version <= 1.0 && version > 0.0; // because as of 2016/5 Edge returns 0.96
// This might also be the correct check but I'm assuming it's slow-ish
// return gl instanceof WebGLRenderingContext;
return !gl.texStorage2D;
}
var error = window.console && window.console.error && typeof window.console.error === "function" ? window.console.error.bind(window.console) : function () {};
var warn = window.console && window.console.warn && typeof window.console.warn === "function" ? window.console.warn.bind(window.console) : function () {};
return {
copyExistingProperties: copyExistingProperties,
copyNamedProperties: copyNamedProperties,
shallowCopy: shallowCopy,
isWebGL1: isWebGL1,
isWebGL2: isWebGL2,
error: error,
warn: warn
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (programs) {
"use strict";
/**
* Drawing related functions
*
* For backward compatibily they are available at both `twgl.draw` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/draw
*/
/**
* Calls `gl.drawElements` or `gl.drawArrays`, whichever is appropriate
*
* normally you'd call `gl.drawElements` or `gl.drawArrays` yourself
* but calling this means if you switch from indexed data to non-indexed
* data you don't have to remember to update your draw call.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} bufferInfo A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays} or
* a VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}
* @param {enum} [type] eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...). Defaults to `gl.TRIANGLES`
* @param {number} [count] An optional count. Defaults to bufferInfo.numElements
* @param {number} [offset] An optional offset. Defaults to 0.
* @memberOf module:twgl/draw
*/
function drawBufferInfo(gl, bufferInfo, type, count, offset) {
type = type === undefined ? gl.TRIANGLES : type;
var indices = bufferInfo.indices;
var elementType = bufferInfo.elementType;
var numElements = count === undefined ? bufferInfo.numElements : count;
offset = offset === undefined ? 0 : offset;
if (elementType || indices) {
gl.drawElements(type, numElements, elementType === undefined ? gl.UNSIGNED_SHORT : bufferInfo.elementType, offset);
} else {
gl.drawArrays(type, offset, numElements);
}
}
/**
* A DrawObject is useful for putting objects in to an array and passing them to {@link module:twgl.drawObjectList}.
*
* You need either a `BufferInfo` or a `VertexArrayInfo`.
*
* @typedef {Object} DrawObject
* @property {boolean} [active] whether or not to draw. Default = `true` (must be `false` to be not true). In otherwords `undefined` = `true`
* @property {number} [type] type to draw eg. `gl.TRIANGLES`, `gl.LINES`, etc...
* @property {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo}
* @property {module:twgl.BufferInfo} [bufferInfo] A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays}
* @property {module:twgl.VertexArrayInfo} [vertexArrayInfo] A VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}
* @property {Object<string, ?>} uniforms The values for the uniforms.
* You can pass multiple objects by putting them in an array. For example
*
* var sharedUniforms = {
* u_fogNear: 10,
* u_projection: ...
* ...
* };
*
* var localUniforms = {
* u_world: ...
* u_diffuseColor: ...
* };
*
* var drawObj = {
* ...
* uniforms: [sharedUniforms, localUniforms],
* };
*
* @property {number} [offset] the offset to pass to `gl.drawArrays` or `gl.drawElements`. Defaults to 0.
* @property {number} [count] the count to pass to `gl.drawArrays` or `gl.drawElemnts`. Defaults to bufferInfo.numElements.
* @memberOf module:twgl
*/
/**
* Draws a list of objects
* @param {DrawObject[]} objectsToDraw an array of objects to draw.
* @memberOf module:twgl/draw
*/
function drawObjectList(gl, objectsToDraw) {
var lastUsedProgramInfo = null;
var lastUsedBufferInfo = null;
objectsToDraw.forEach(function (object) {
if (object.active === false) {
return;
}
var programInfo = object.programInfo;
var bufferInfo = object.vertexArrayInfo || object.bufferInfo;
var bindBuffers = false;
var type = object.type === undefined ? gl.TRIANGLES : object.type;
if (programInfo !== lastUsedProgramInfo) {
lastUsedProgramInfo = programInfo;
gl.useProgram(programInfo.program);
// We have to rebind buffers when changing programs because we
// only bind buffers the program uses. So if 2 programs use the same
// bufferInfo but the 1st one uses only positions the when the
// we switch to the 2nd one some of the attributes will not be on.
bindBuffers = true;
}
// Setup all the needed attributes.
if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {
if (lastUsedBufferInfo && lastUsedBufferInfo.vertexArrayObject && !bufferInfo.vertexArrayObject) {
gl.bindVertexArray(null);
}
lastUsedBufferInfo = bufferInfo;
programs.setBuffersAndAttributes(gl, programInfo, bufferInfo);
}
// Set the uniforms.
programs.setUniforms(programInfo, object.uniforms);
// Draw
drawBufferInfo(gl, bufferInfo, type, object.count, object.offset);
});
if (lastUsedBufferInfo.vertexArrayObject) {
gl.bindVertexArray(null);
}
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"drawBufferInfo": drawBufferInfo,
"drawObjectList": drawObjectList
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (utils) {
"use strict";
/**
* Low level shader program related functions
*
* You should generally not need to use these functions. They are provided
* for those cases where you're doing something out of the ordinary
* and you need lower level access.
*
* For backward compatibily they are available at both `twgl.programs` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/programs
*/
var error = utils.error;
var warn = utils.warn;
var FLOAT = 0x1406;
var FLOAT_VEC2 = 0x8B50;
var FLOAT_VEC3 = 0x8B51;
var FLOAT_VEC4 = 0x8B52;
var INT = 0x1404;
var INT_VEC2 = 0x8B53;
var INT_VEC3 = 0x8B54;
var INT_VEC4 = 0x8B55;
var BOOL = 0x8B56;
var BOOL_VEC2 = 0x8B57;
var BOOL_VEC3 = 0x8B58;
var BOOL_VEC4 = 0x8B59;
var FLOAT_MAT2 = 0x8B5A;
var FLOAT_MAT3 = 0x8B5B;
var FLOAT_MAT4 = 0x8B5C;
var SAMPLER_2D = 0x8B5E;
var SAMPLER_CUBE = 0x8B60;
var SAMPLER_3D = 0x8B5F;
var SAMPLER_2D_SHADOW = 0x8B62;
var FLOAT_MAT2x3 = 0x8B65;
var FLOAT_MAT2x4 = 0x8B66;
var FLOAT_MAT3x2 = 0x8B67;
var FLOAT_MAT3x4 = 0x8B68;
var FLOAT_MAT4x2 = 0x8B69;
var FLOAT_MAT4x3 = 0x8B6A;
var SAMPLER_2D_ARRAY = 0x8DC1;
var SAMPLER_2D_ARRAY_SHADOW = 0x8DC4;
var SAMPLER_CUBE_SHADOW = 0x8DC5;
var UNSIGNED_INT = 0x1405;
var UNSIGNED_INT_VEC2 = 0x8DC6;
var UNSIGNED_INT_VEC3 = 0x8DC7;
var UNSIGNED_INT_VEC4 = 0x8DC8;
var INT_SAMPLER_2D = 0x8DCA;
var INT_SAMPLER_3D = 0x8DCB;
var INT_SAMPLER_CUBE = 0x8DCC;
var INT_SAMPLER_2D_ARRAY = 0x8DCF;
var UNSIGNED_INT_SAMPLER_2D = 0x8DD2;
var UNSIGNED_INT_SAMPLER_3D = 0x8DD3;
var UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4;
var UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7;
var TEXTURE_2D = 0x0DE1;
var TEXTURE_CUBE_MAP = 0x8513;
var TEXTURE_3D = 0x806F;
var TEXTURE_2D_ARRAY = 0x8C1A;
var typeMap = {};
/**
* Returns the corresponding bind point for a given sampler type
*/
function getBindPointForSamplerType(gl, type) {
return typeMap[type].bindPoint;
}
// This kind of sucks! If you could compose functions as in `var fn = gl[name];`
// this code could be a lot smaller but that is sadly really slow (T_T)
function floatSetter(gl, location) {
return function (v) {
gl.uniform1f(location, v);
};
}
function floatArraySetter(gl, location) {
return function (v) {
gl.uniform1fv(location, v);
};
}
function floatVec2Setter(gl, location) {
return function (v) {
gl.uniform2fv(location, v);
};
}
function floatVec3Setter(gl, location) {
return function (v) {
gl.uniform3fv(location, v);
};
}
function floatVec4Setter(gl, location) {
return function (v) {
gl.uniform4fv(location, v);
};
}
function intSetter(gl, location) {
return function (v) {
gl.uniform1i(location, v);
};
}
function intArraySetter(gl, location) {
return function (v) {
gl.uniform1iv(location, v);
};
}
function intVec2Setter(gl, location) {
return function (v) {
gl.uniform2iv(location, v);
};
}
function intVec3Setter(gl, location) {
return function (v) {
gl.uniform3iv(location, v);
};
}
function intVec4Setter(gl, location) {
return function (v) {
gl.uniform4iv(location, v);
};
}
function uintSetter(gl, location) {
return function (v) {
gl.uniform1ui(location, v);
};
}
function uintArraySetter(gl, location) {
return function (v) {
gl.uniform1uiv(location, v);
};
}
function uintVec2Setter(gl, location) {
return function (v) {
gl.uniform2uiv(location, v);
};
}
function uintVec3Setter(gl, location) {
return function (v) {
gl.uniform3uiv(location, v);
};
}
function uintVec4Setter(gl, location) {
return function (v) {
gl.uniform4uiv(location, v);
};
}
function floatMat2Setter(gl, location) {
return function (v) {
gl.uniformMatrix2fv(location, false, v);
};
}
function floatMat3Setter(gl, location) {
return function (v) {
gl.uniformMatrix3fv(location, false, v);
};
}
function floatMat4Setter(gl, location) {
return function (v) {
gl.uniformMatrix4fv(location, false, v);
};
}
function floatMat23Setter(gl, location) {
return function (v) {
gl.uniformMatrix2x3fv(location, false, v);
};
}
function floatMat32Setter(gl, location) {
return function (v) {
gl.uniformMatrix3x2fv(location, false, v);
};
}
function floatMat24Setter(gl, location) {
return function (v) {
gl.uniformMatrix2x4fv(location, false, v);
};
}
function floatMat42Setter(gl, location) {
return function (v) {
gl.uniformMatrix4x2fv(location, false, v);
};
}
function floatMat34Setter(gl, location) {
return function (v) {
gl.uniformMatrix3x4fv(location, false, v);
};
}
function floatMat43Setter(gl, location) {
return function (v) {
gl.uniformMatrix4x3fv(location, false, v);
};
}
function samplerSetter(gl, type, unit, location) {
var bindPoint = getBindPointForSamplerType(gl, type);
return function (textureOrPair) {
var texture = void 0;
if (textureOrPair instanceof WebGLTexture) {
texture = textureOrPair;
} else {
texture = textureOrPair.texture;
gl.bindSampler(unit, textureOrPair.sampler);
}
gl.uniform1i(location, unit);
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(bindPoint, texture);
};
}
function samplerArraySetter(gl, type, unit, location, size) {
var bindPoint = getBindPointForSamplerType(gl, type);
var units = new Int32Array(size);
for (var ii = 0; ii < size; ++ii) {
units[ii] = unit + ii;
}
return function (textures) {
gl.uniform1iv(location, units);
textures.forEach(function (textureOrPair, index) {
gl.activeTexture(gl.TEXTURE0 + units[index]);
var texture = void 0;
if (textureOrPair instanceof WebGLTexture) {
texture = textureOrPair;
} else {
texture = textureOrPair.texture;
gl.bindSampler(unit, textureOrPair.sampler);
}
gl.bindTexture(bindPoint, texture);
});
};
}
typeMap[FLOAT] = { Type: Float32Array, size: 4, setter: floatSetter, arraySetter: floatArraySetter };
typeMap[FLOAT_VEC2] = { Type: Float32Array, size: 8, setter: floatVec2Setter };
typeMap[FLOAT_VEC3] = { Type: Float32Array, size: 12, setter: floatVec3Setter };
typeMap[FLOAT_VEC4] = { Type: Float32Array, size: 16, setter: floatVec4Setter };
typeMap[INT] = { Type: Int32Array, size: 4, setter: intSetter, arraySetter: intArraySetter };
typeMap[INT_VEC2] = { Type: Int32Array, size: 8, setter: intVec2Setter };
typeMap[INT_VEC3] = { Type: Int32Array, size: 12, setter: intVec3Setter };
typeMap[INT_VEC4] = { Type: Int32Array, size: 16, setter: intVec4Setter };
typeMap[UNSIGNED_INT] = { Type: Uint32Array, size: 4, setter: uintSetter, arraySetter: uintArraySetter };
typeMap[UNSIGNED_INT_VEC2] = { Type: Uint32Array, size: 8, setter: uintVec2Setter };
typeMap[UNSIGNED_INT_VEC3] = { Type: Uint32Array, size: 12, setter: uintVec3Setter };
typeMap[UNSIGNED_INT_VEC4] = { Type: Uint32Array, size: 16, setter: uintVec4Setter };
typeMap[BOOL] = { Type: Uint32Array, size: 4, setter: intSetter, arraySetter: intArraySetter };
typeMap[BOOL_VEC2] = { Type: Uint32Array, size: 8, setter: intVec2Setter };
typeMap[BOOL_VEC3] = { Type: Uint32Array, size: 12, setter: intVec3Setter };
typeMap[BOOL_VEC4] = { Type: Uint32Array, size: 16, setter: intVec4Setter };
typeMap[FLOAT_MAT2] = { Type: Float32Array, size: 16, setter: floatMat2Setter };
typeMap[FLOAT_MAT3] = { Type: Float32Array, size: 36, setter: floatMat3Setter };
typeMap[FLOAT_MAT4] = { Type: Float32Array, size: 64, setter: floatMat4Setter };
typeMap[FLOAT_MAT2x3] = { Type: Float32Array, size: 24, setter: floatMat23Setter };
typeMap[FLOAT_MAT2x4] = { Type: Float32Array, size: 32, setter: floatMat24Setter };
typeMap[FLOAT_MAT3x2] = { Type: Float32Array, size: 24, setter: floatMat32Setter };
typeMap[FLOAT_MAT3x4] = { Type: Float32Array, size: 48, setter: floatMat34Setter };
typeMap[FLOAT_MAT4x2] = { Type: Float32Array, size: 32, setter: floatMat42Setter };
typeMap[FLOAT_MAT4x3] = { Type: Float32Array, size: 48, setter: floatMat43Setter };
typeMap[SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D };
typeMap[SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP };
typeMap[SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D };
typeMap[SAMPLER_2D_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D };
typeMap[SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY };
typeMap[SAMPLER_2D_ARRAY_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY };
typeMap[SAMPLER_CUBE_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP };
typeMap[INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D };
typeMap[INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D };
typeMap[INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP };
typeMap[INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY };
typeMap[UNSIGNED_INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D };
typeMap[UNSIGNED_INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D };
typeMap[UNSIGNED_INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP };
typeMap[UNSIGNED_INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY };
function floatAttribSetter(gl, index) {
return function (b) {
gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer);
gl.enableVertexAttribArray(index);
gl.vertexAttribPointer(index, b.numComponents || b.size, b.type || gl.FLOAT, b.normalize || false, b.stride || 0, b.offset || 0);
};
}
function intAttribSetter(gl, index) {
return function (b) {
gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer);
gl.enableVertexAttribArray(index);
gl.vertexAttribIPointer(index, b.numComponents || b.size, b.type || gl.INT, b.stride || 0, b.offset || 0);
};
}
function matAttribSetter(gl, index, typeInfo) {
var defaultSize = typeInfo.size;
var count = typeInfo.count;
return function (b) {
gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer);
var numComponents = b.size || b.numComponents || defaultSize;
var size = numComponents / count;
var type = b.type || gl.FLOAT;
var typeInfo = typeMap[type];
var stride = typeInfo.size * numComponents;
var normalize = b.normalize || false;
var offset = b.offset || 0;
var rowOffset = stride / count;
for (var i = 0; i < count; ++i) {
gl.enableVertexAttribArray(index + i);
gl.vertexAttribPointer(index + i, size, type, normalize, stride, offset + rowOffset * i);
}
};
}
var attrTypeMap = {};
attrTypeMap[FLOAT] = { size: 4, setter: floatAttribSetter };
attrTypeMap[FLOAT_VEC2] = { size: 8, setter: floatAttribSetter };
attrTypeMap[FLOAT_VEC3] = { size: 12, setter: floatAttribSetter };
attrTypeMap[FLOAT_VEC4] = { size: 16, setter: floatAttribSetter };
attrTypeMap[INT] = { size: 4, setter: intAttribSetter };
attrTypeMap[INT_VEC2] = { size: 8, setter: intAttribSetter };
attrTypeMap[INT_VEC3] = { size: 12, setter: intAttribSetter };
attrTypeMap[INT_VEC4] = { size: 16, setter: intAttribSetter };
attrTypeMap[UNSIGNED_INT] = { size: 4, setter: intAttribSetter };
attrTypeMap[UNSIGNED_INT_VEC2] = { size: 8, setter: intAttribSetter };
attrTypeMap[UNSIGNED_INT_VEC3] = { size: 12, setter: intAttribSetter };
attrTypeMap[UNSIGNED_INT_VEC4] = { size: 16, setter: intAttribSetter };
attrTypeMap[BOOL] = { size: 4, setter: intAttribSetter };
attrTypeMap[BOOL_VEC2] = { size: 8, setter: intAttribSetter };
attrTypeMap[BOOL_VEC3] = { size: 12, setter: intAttribSetter };
attrTypeMap[BOOL_VEC4] = { size: 16, setter: intAttribSetter };
attrTypeMap[FLOAT_MAT2] = { size: 4, setter: matAttribSetter, count: 2 };
attrTypeMap[FLOAT_MAT3] = { size: 9, setter: matAttribSetter, count: 3 };
attrTypeMap[FLOAT_MAT4] = { size: 16, setter: matAttribSetter, count: 4 };
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
/**
* Error Callback
* @callback ErrorCallback
* @param {string} msg error message.
* @param {number} [lineOffset] amount to add to line number
* @memberOf module:twgl
*/
function addLineNumbers(src, lineOffset) {
lineOffset = lineOffset || 0;
++lineOffset;
return src.split("\n").map(function (line, ndx) {
return ndx + lineOffset + ": " + line;
}).join("\n");
}
var spaceRE = /^[ \t]*\n/;
/**
* Loads a shader.
* @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
* @param {string} shaderSource The shader source.
* @param {number} shaderType The type of shader.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors.
* @return {WebGLShader} The created shader.
*/
function loadShader(gl, shaderSource, shaderType, opt_errorCallback) {
var errFn = opt_errorCallback || error;
// Create the shader object
var shader = gl.createShader(shaderType);
// Remove the first end of line because WebGL 2.0 requires
// #version 300 es
// as the first line. No whitespace allowed before that line
// so
//
// <script>
// #version 300 es
// </script>
//
// Has one line before it which is invalid according to GLSL ES 3.00
//
var lineOffset = 0;
if (spaceRE.test(shaderSource)) {
lineOffset = 1;
shaderSource = shaderSource.replace(spaceRE, '');
}
// Load the shader source
gl.shaderSource(shader, shaderSource);
// Compile the shader
gl.compileShader(shader);
// Check the compile status
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
// Something went wrong during compilation; get the error
var lastError = gl.getShaderInfoLog(shader);
errFn(addLineNumbers(shaderSource, lineOffset) + "\n*** Error compiling shader: " + lastError);
gl.deleteShader(shader);
return null;
}
return shader;
}
/**
* @typedef {Object} ProgramOptions
* @property {function(string)} [errorCallback] callback for errors
* @property {Object.<string,number>} [attribLocations] a attribute name to location map
* @memberOf module:twgl
*/
/**
* Gets the program options based on all these optional arguments
* @param {module:twgl.ProgramOptions|string[]} [opt_attribs] Options for the program or an array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {module:twgl.ProgramOptions} an instance of ProgramOptions based on the arguments pased on
*/
function getProgramOptions(opt_attribs, opt_locations, opt_errorCallback) {
if (typeof opt_locations === 'function') {
opt_errorCallback = opt_locations;
opt_locations = undefined;
}
if (typeof opt_attribs === 'function') {
opt_errorCallback = opt_attribs;
opt_attribs = undefined;
} else if (opt_attribs && !Array.isArray(opt_attribs)) {
// If we have an errorCallback we can just return this object
// Otherwise we need to construct one with default errorCallback
if (opt_attribs.errorCallback) {
return opt_attribs;
}
var opt = opt_attribs;
opt_errorCallback = opt.errorCallback;
opt_attribs = opt.attribLocations;
}
var options = {
errorCallback: opt_errorCallback || error
};
if (opt_attribs) {
var attribLocations = {};
if (Array.isArray(opt_attribs)) {
opt_attribs.forEach(function (attrib, ndx) {
attribLocations[attrib] = opt_locations ? opt_locations[ndx] : ndx;
});
} else {
attribLocations = opt_attribs;
}
options.attribLocations = attribLocations;
}
return options;
}
/**
* Creates a program, attaches shaders, binds attrib locations, links the
* program and calls useProgram.
*
* NOTE: There are 4 signatures for this function
*
* twgl.createProgram(gl, [vs, fs], options);
* twgl.createProgram(gl, [vs, fs], opt_errFunc);
* twgl.createProgram(gl, [vs, fs], opt_attribs, opt_errFunc);
* twgl.createProgram(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);
*
* @param {WebGLShader[]} shaders The shaders to attach
* @param {module:twgl.ProgramOptions|string[]} [opt_attribs] Options for the program or an array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {WebGLProgram?} the created program or null if error.
* @memberOf module:twgl/programs
*/
function createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {
var progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);
var program = gl.createProgram();
shaders.forEach(function (shader) {
gl.attachShader(program, shader);
});
if (progOptions.attribLocations) {
Object.keys(progOptions.attribLocations).forEach(function (attrib) {
gl.bindAttribLocation(program, progOptions.attribLocations[attrib], attrib);
});
}
gl.linkProgram(program);
// Check the link status
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
// something went wrong with the link
var lastError = gl.getProgramInfoLog(program);
progOptions.errorCallback("Error in program linking:" + lastError);
gl.deleteProgram(program);
return null;
}
return program;
}
/**
* Loads a shader from a script tag.
* @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
* @param {string} scriptId The id of the script tag.
* @param {number} [opt_shaderType] The type of shader. If not passed in it will
* be derived from the type of the script tag.
* @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors.
* @return {WebGLShader?} The created shader or null if error.
*/
function createShaderFromScript(gl, scriptId, opt_shaderType, opt_errorCallback) {
var shaderSource = "";
var shaderType;
var shaderScript = document.getElementById(scriptId);
if (!shaderScript) {
throw "*** Error: unknown script element" + scriptId;
}
shaderSource = shaderScript.text;
if (!opt_shaderType) {
if (shaderScript.type === "x-shader/x-vertex") {
shaderType = gl.VERTEX_SHADER;
} else if (shaderScript.type === "x-shader/x-fragment") {
shaderType = gl.FRAGMENT_SHADER;
} else if (shaderType !== gl.VERTEX_SHADER && shaderType !== gl.FRAGMENT_SHADER) {
throw "*** Error: unknown shader type";
}
}
return loadShader(gl, shaderSource, opt_shaderType ? opt_shaderType : shaderType, opt_errorCallback);
}
var defaultShaderType = ["VERTEX_SHADER", "FRAGMENT_SHADER"];
/**
* Creates a program from 2 script tags.
*
* NOTE: There are 4 signatures for this function
*
* twgl.createProgramFromScripts(gl, [vs, fs], opt_options);
* twgl.createProgramFromScripts(gl, [vs, fs], opt_errFunc);
* twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_errFunc);
* twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {string[]} shaderScriptIds Array of ids of the script
* tags for the shaders. The first is assumed to be the
* vertex shader, the second the fragment shader.
* @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {WebGLProgram} The created program.
* @memberOf module:twgl/programs
*/
function createProgramFromScripts(gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {
var progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);
var shaders = [];
for (var ii = 0; ii < shaderScriptIds.length; ++ii) {
var shader = createShaderFromScript(gl, shaderScriptIds[ii], gl[defaultShaderType[ii]], progOptions.errorCallback);
if (!shader) {
return null;
}
shaders.push(shader);
}
return createProgram(gl, shaders, progOptions);
}
/**
* Creates a program from 2 sources.
*
* NOTE: There are 4 signatures for this function
*
* twgl.createProgramFromSource(gl, [vs, fs], opt_options);
* twgl.createProgramFromSource(gl, [vs, fs], opt_errFunc);
* twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_errFunc);
* twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {string[]} shaderSourcess Array of sources for the
* shaders. The first is assumed to be the vertex shader,
* the second the fragment shader.
* @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {WebGLProgram} The created program.
* @memberOf module:twgl/programs
*/
function createProgramFromSources(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {
var progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);
var shaders = [];
for (var ii = 0; ii < shaderSources.length; ++ii) {
var shader = loadShader(gl, shaderSources[ii], gl[defaultShaderType[ii]], progOptions.errorCallback);
if (!shader) {
return null;
}
shaders.push(shader);
}
return createProgram(gl, shaders, progOptions);
}
/**
* Creates setter functions for all uniforms of a shader
* program.
*
* @see {@link module:twgl.setUniforms}
*
* @param {WebGLProgram} program the program to create setters for.
* @returns {Object.<string, function>} an object with a setter by name for each uniform
* @memberOf module:twgl/programs
*/
function createUniformSetters(gl, program) {
var textureUnit = 0;
/**
* Creates a setter for a uniform of the given program with it's
* location embedded in the setter.
* @param {WebGLProgram} program
* @param {WebGLUniformInfo} uniformInfo
* @returns {function} the created setter.
*/
function createUniformSetter(program, uniformInfo) {
var location = gl.getUniformLocation(program, uniformInfo.name);
var isArray = uniformInfo.size > 1 && uniformInfo.name.substr(-3) === "[0]";
var type = uniformInfo.type;
var typeInfo = typeMap[type];
if (!typeInfo) {
throw "unknown type: 0x" + type.toString(16); // we should never get here.
}
if (typeInfo.bindPoint) {
// it's a sampler
var unit = textureUnit;
textureUnit += uniformInfo.size;
if (isArray) {
return typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size);
} else {
return typeInfo.setter(gl, type, unit, location, uniformInfo.size);
}
} else {
if (typeInfo.arraySetter && isArray) {
return typeInfo.arraySetter(gl, location);
} else {
return typeInfo.setter(gl, location);
}
}
}
var uniformSetters = {};
var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
for (var ii = 0; ii < numUniforms; ++ii) {
var uniformInfo = gl.getActiveUniform(program, ii);
if (!uniformInfo) {
break;
}
var name = uniformInfo.name;
// remove the array suffix.
if (name.substr(-3) === "[0]") {
name = name.substr(0, name.length - 3);
}
var setter = createUniformSetter(program, uniformInfo);
uniformSetters[name] = setter;
}
return uniformSetters;
}
/**
* @typedef {Object} UniformData
* @property {number} type The WebGL type enum for this uniform
* @property {number} size The number of elements for this uniform
* @property {number} blockNdx The block index this uniform appears in
* @property {number} offset The byte offset in the block for this uniform's value
* @memberOf module:twgl
*/
/**
* The specification for one UniformBlockObject
*
* @typedef {Object} BlockSpec
* @property {number} index The index of the block.
* @property {number} size The size in bytes needed for the block
* @property {number[]} uniformIndices The indices of the uniforms used by the block. These indices
* correspond to entries in a UniformData array in the {@link module:twgl.UniformBlockSpec}.
* @property {bool} usedByVertexShader Self explanitory
* @property {bool} usedByFragmentShader Self explanitory
* @property {bool} used Self explanitory
* @memberOf module:twgl
*/
/**
* A `UniformBlockSpec` represents the data needed to create and bind
* UniformBlockObjects for a given program
*
* @typedef {Object} UniformBlockSpec
* @property {Object.<string, module:twgl.BlockSpec> blockSpecs The BlockSpec for each block by block name
* @property {UniformData[]} uniformData An array of data for each uniform by uniform index.
* @memberOf module:twgl
*/
/**
* Creates a UniformBlockSpec for the given program.
*
* A UniformBlockSpec represents the data needed to create and bind
* UniformBlockObjects
*
* @param {WebGL2RenderingContext} gl A WebGL2 Rendering Context
* @param {WebGLProgram} program A WebGLProgram for a successfully linked program
* @return {module:twgl.UniformBlockSpec} The created UniformBlockSpec
* @memberOf module:twgl/programs
*/
function createUniformBlockSpecFromProgram(gl, program) {
var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
var uniformData = [];
var uniformIndices = [];
for (var ii = 0; ii < numUniforms; ++ii) {
uniformIndices.push(ii);
uniformData.push({});
var uniformInfo = gl.getActiveUniform(program, ii);
if (!uniformInfo) {
break;
}
// REMOVE [0]?
uniformData[ii].name = uniformInfo.name;
}
[["UNIFORM_TYPE", "type"], ["UNIFORM_SIZE", "size"], // num elements
["UNIFORM_BLOCK_INDEX", "blockNdx"], ["UNIFORM_OFFSET", "offset"]].forEach(function (pair) {
var pname = pair[0];
var key = pair[1];
gl.getActiveUniforms(program, uniformIndices, gl[pname]).forEach(function (value, ndx) {
uniformData[ndx][key] = value;
});
});
var blockSpecs = {};
var numUniformBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
for (ii = 0; ii < numUniformBlocks; ++ii) {
var name = gl.getActiveUniformBlockName(program, ii);
var blockSpec = {
index: ii,
usedByVertexShader: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),
usedByFragmentShader: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),
size: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_DATA_SIZE),
uniformIndices: gl.getActiveUniformBlockParameter(program, ii, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES)
};
blockSpec.used = blockSpec.usedByVertexSahder || blockSpec.usedByFragmentShader;
blockSpecs[name] = blockSpec;
}
return {
blockSpecs: blockSpecs,
uniformData: uniformData
};
}
var arraySuffixRE = /\[\d+\]\.$/; // better way to check?
/**
* Represents a UniformBlockObject including an ArrayBuffer with all the uniform values
* and a corresponding WebGLBuffer to hold those values on the GPU
*
* @typedef {Object} UniformBlockInfo
* @property {string} name The name of the block
* @property {ArrayBuffer} array The array buffer that contains the uniform values
* @property {Float32Array} asFloat A float view on the array buffer. This is useful
* inspecting the contents of the buffer in the debugger.
* @property {WebGLBuffer} buffer A WebGL buffer that will hold a copy of the uniform values for rendering.
* @property {number} [offset] offset into buffer
* @property {Object.<string, ArrayBufferView>} uniforms A uniform name to ArrayBufferView map.
* each Uniform has a correctly typed `ArrayBufferView` into array at the correct offset
* and length of that uniform. So for example a float uniform would have a 1 float `Float32Array`
* view. A single mat4 would have a 16 element `Float32Array` view. An ivec2 would have an
* `Int32Array` view, etc.
* @memberOf module:twgl
*/
/**
* Creates a `UniformBlockInfo` for the specified block
*
* Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy
* `UniformBlockInfo` is returned**. This is because when debugging GLSL
* it is common to comment out large portions of a shader or for example set
* the final output to a constant. When that happens blocks get optimized out.
* If this function did not create dummy blocks your code would crash when debugging.
*
* @param {WebGL2RenderingContext} gl A WebGL2RenderingContext
* @param {WebGLProgram} program A WebGLProgram
* @param {module:twgl.UniformBlockSpec} uinformBlockSpec. A UniformBlockSpec as returned
* from {@link module:twgl.createUniformBlockSpecFromProgram}.
* @param {string} blockName The name of the block.
* @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo
* @memberOf module:twgl/programs
*/
function createUniformBlockInfoFromProgram(gl, program, uniformBlockSpec, blockName) {
var blockSpecs = uniformBlockSpec.blockSpecs;
var uniformData = uniformBlockSpec.uniformData;
var blockSpec = blockSpecs[blockName];
if (!blockSpec) {
warn("no uniform block object named:", blockName);
return {
name: blockName,
uniforms: {}
};
}
var array = new ArrayBuffer(blockSpec.size);
var buffer = gl.createBuffer();
var uniformBufferIndex = blockSpec.index;
gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
gl.uniformBlockBinding(program, blockSpec.index, uniformBufferIndex);
var prefix = blockName + ".";
if (arraySuffixRE.test(prefix)) {
prefix = prefix.replace(arraySuffixRE, ".");
}
var uniforms = {};
blockSpec.uniformIndices.forEach(function (uniformNdx) {
var data = uniformData[uniformNdx];
var typeInfo = typeMap[data.type];
var Type = typeInfo.Type;
var length = data.size * typeInfo.size;
var name = data.name;
if (name.substr(0, prefix.length) === prefix) {
name = name.substr(prefix.length);
}
uniforms[name] = new Type(array, data.offset, length / Type.BYTES_PER_ELEMENT);
});
return {
name: blockName,
array: array,
asFloat: new Float32Array(array), // for debugging
buffer: buffer,
uniforms: uniforms
};
}
/**
* Creates a `UniformBlockInfo` for the specified block
*
* Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy
* `UniformBlockInfo` is returned**. This is because when debugging GLSL
* it is common to comment out large portions of a shader or for example set
* the final output to a constant. When that happens blocks get optimized out.
* If this function did not create dummy blocks your code would crash when debugging.
*
* @param {WebGL2RenderingContext} gl A WebGL2RenderingContext
* @param {module:twgl.ProgramInfo} programInfo a `ProgramInfo`
* as returned from {@link module:twgl.createProgramInfo}
* @param {string} blockName The name of the block.
* @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo
* @memberOf module:twgl/programs
*/
function createUniformBlockInfo(gl, programInfo, blockName) {
return createUniformBlockInfoFromProgram(gl, programInfo.program, programInfo.uniformBlockSpec, blockName);
}
/**
* Binds a unform block to the matching uniform block point.
* Matches by blocks by name so blocks must have the same name not just the same
* structure.
*
* If you have changed any values and you upload the valus into the corresponding WebGLBuffer
* call {@link module:twgl.setUniformBlock} instead.
*
* @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.
* @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`
* as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as
* returned from {@link module:twgl.createUniformBlockSpecFromProgram}.
* @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from
* {@link module:twgl.createUniformBlockInfo}.
* @return {bool} true if buffer was bound. If the programInfo has no block with the same block name
* no buffer is bound.
* @memberOf module:twgl/programs
*/
function bindUniformBlock(gl, programInfo, uniformBlockInfo) {
var uniformBlockSpec = programInfo.uniformBlockSpec || programInfo;
var blockSpec = uniformBlockSpec.blockSpecs[uniformBlockInfo.name];
if (blockSpec) {
var bufferBindIndex = blockSpec.index;
gl.bindBufferRange(gl.UNIFORM_BUFFER, bufferBindIndex, uniformBlockInfo.buffer, uniformBlockInfo.offset || 0, uniformBlockInfo.array.byteLength);
return true;
}
return false;
}
/**
* Uploads the current uniform values to the corresponding WebGLBuffer
* and binds that buffer to the program's corresponding bind point for the uniform block object.
*
* If you haven't changed any values and you only need to bind the uniform block object
* call {@link module:twgl.bindUniformBlock} instead.
*
* @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.
* @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`
* as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as
* returned from {@link module:twgl.createUniformBlockSpecFromProgram}.
* @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from
* {@link module:twgl.createUniformBlockInfo}.
* @memberOf module:twgl/programs
*/
function setUniformBlock(gl, programInfo, uniformBlockInfo) {
if (bindUniformBlock(gl, programInfo, uniformBlockInfo)) {
gl.bufferData(gl.UNIFORM_BUFFER, uniformBlockInfo.array, gl.DYNAMIC_DRAW);
}
}
/**
* Sets values of a uniform block object
*
* @param {module:twgl.UniformBlockInfo} uniformBlockInfo A UniformBlockInfo as returned by {@link module:twgl.createUniformBlockInfo}.
* @param {Object.<string, ?>} values A uniform name to value map where the value is correct for the given
* type of uniform. So for example given a block like
*
* uniform SomeBlock {
* float someFloat;
* vec2 someVec2;
* vec3 someVec3Array[2];
* int someInt;
* }
*
* You can set the values of the uniform block with
*
* twgl.setBlockUniforms(someBlockInfo, {
* someFloat: 12.3,
* someVec2: [1, 2],
* someVec3Array: [1, 2, 3, 4, 5, 6],
* someInt: 5,
* }
*
* Arrays can be JavaScript arrays or typed arrays
*
* Any name that doesn't match will be ignored
* @memberOf module:twgl/programs
*/
function setBlockUniforms(uniformBlockInfo, values) {
var uniforms = uniformBlockInfo.uniforms;
for (var name in values) {
var array = uniforms[name];
if (array) {
var value = values[name];
if (value.length) {
array.set(value);
} else {
array[0] = value;
}
}
}
}
/**
* Set uniforms and binds related textures.
*
* example:
*
* var programInfo = createProgramInfo(
* gl, ["some-vs", "some-fs"]);
*
* var tex1 = gl.createTexture();
* var tex2 = gl.createTexture();
*
* ... assume we setup the textures with data ...
*
* var uniforms = {
* u_someSampler: tex1,
* u_someOtherSampler: tex2,
* u_someColor: [1,0,0,1],
* u_somePosition: [0,1,1],
* u_someMatrix: [
* 1,0,0,0,
* 0,1,0,0,
* 0,0,1,0,
* 0,0,0,0,
* ],
* };
*
* gl.useProgram(program);
*
* This will automatically bind the textures AND set the
* uniforms.
*
* twgl.setUniforms(programInfo, uniforms);
*
* For the example above it is equivalent to
*
* var texUnit = 0;
* gl.activeTexture(gl.TEXTURE0 + texUnit);
* gl.bindTexture(gl.TEXTURE_2D, tex1);
* gl.uniform1i(u_someSamplerLocation, texUnit++);
* gl.activeTexture(gl.TEXTURE0 + texUnit);
* gl.bindTexture(gl.TEXTURE_2D, tex2);
* gl.uniform1i(u_someSamplerLocation, texUnit++);
* gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]);
* gl.uniform3fv(u_somePositionLocation, [0, 1, 1]);
* gl.uniformMatrix4fv(u_someMatrix, false, [
* 1,0,0,0,
* 0,1,0,0,
* 0,0,1,0,
* 0,0,0,0,
* ]);
*
* Note it is perfectly reasonable to call `setUniforms` multiple times. For example
*
* var uniforms = {
* u_someSampler: tex1,
* u_someOtherSampler: tex2,
* };
*
* var moreUniforms {
* u_someColor: [1,0,0,1],
* u_somePosition: [0,1,1],
* u_someMatrix: [
* 1,0,0,0,
* 0,1,0,0,
* 0,0,1,0,
* 0,0,0,0,
* ],
* };
*
* twgl.setUniforms(programInfo, uniforms);
* twgl.setUniforms(programInfo, moreUniforms);
*
* You can also add WebGLSamplers to uniform samplers as in
*
* var uniforms = {
* u_someSampler: {
* texture: someWebGLTexture,
* sampler: someWebGLSampler,
* },
* };
*
* In which case both the sampler and texture will be bound to the
* same unit.
*
* @param {(module:twgl.ProgramInfo|Object.<string, function>)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from
* `createUniformSetters`.
* @param {Object.<string, ?>} values an object with values for the
* uniforms.
* You can pass multiple objects by putting them in an array or by calling with more arguments.For example
*
* var sharedUniforms = {
* u_fogNear: 10,
* u_projection: ...
* ...
* };
*
* var localUniforms = {
* u_world: ...
* u_diffuseColor: ...
* };
*
* twgl.setUniforms(programInfo, sharedUniforms, localUniforms);
*
* // is the same as
*
* twgl.setUniforms(programInfo, [sharedUniforms, localUniforms]);
*
* // is the same as
*
* twgl.setUniforms(programInfo, sharedUniforms);
* twgl.setUniforms(programInfo, localUniforms};
*
* @memberOf module:twgl/programs
*/
function setUniforms(setters, values) {
// eslint-disable-line
var actualSetters = setters.uniformSetters || setters;
var numArgs = arguments.length;
for (var andx = 1; andx < numArgs; ++andx) {
var vals = arguments[andx];
if (Array.isArray(vals)) {
var numValues = vals.length;
for (var ii = 0; ii < numValues; ++ii) {
setUniforms(actualSetters, vals[ii]);
}
} else {
for (var name in vals) {
var setter = actualSetters[name];
if (setter) {
setter(vals[name]);
}
}
}
}
}
/**
* Creates setter functions for all attributes of a shader
* program. You can pass this to {@link module:twgl.setBuffersAndAttributes} to set all your buffers and attributes.
*
* @see {@link module:twgl.setAttributes} for example
* @param {WebGLProgram} program the program to create setters for.
* @return {Object.<string, function>} an object with a setter for each attribute by name.
* @memberOf module:twgl/programs
*/
function createAttributeSetters(gl, program) {
var attribSetters = {};
var numAttribs = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (var ii = 0; ii < numAttribs; ++ii) {
var attribInfo = gl.getActiveAttrib(program, ii);
if (!attribInfo) {
break;
}
var index = gl.getAttribLocation(program, attribInfo.name);
var typeInfo = attrTypeMap[attribInfo.type];
attribSetters[attribInfo.name] = typeInfo.setter(gl, index, typeInfo);
}
return attribSetters;
}
/**
* Sets attributes and binds buffers (deprecated... use {@link module:twgl.setBuffersAndAttributes})
*
* Example:
*
* var program = createProgramFromScripts(
* gl, ["some-vs", "some-fs");
*
* var attribSetters = createAttributeSetters(program);
*
* var positionBuffer = gl.createBuffer();
* var texcoordBuffer = gl.createBuffer();
*
* var attribs = {
* a_position: {buffer: positionBuffer, numComponents: 3},
* a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
* };
*
* gl.useProgram(program);
*
* This will automatically bind the buffers AND set the
* attributes.
*
* setAttributes(attribSetters, attribs);
*
* Properties of attribs. For each attrib you can add
* properties:
*
* * type: the type of data in the buffer. Default = gl.FLOAT
* * normalize: whether or not to normalize the data. Default = false
* * stride: the stride. Default = 0
* * offset: offset into the buffer. Default = 0
*
* For example if you had 3 value float positions, 2 value
* float texcoord and 4 value uint8 colors you'd setup your
* attribs like this
*
* var attribs = {
* a_position: {buffer: positionBuffer, numComponents: 3},
* a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
* a_color: {
* buffer: colorBuffer,
* numComponents: 4,
* type: gl.UNSIGNED_BYTE,
* normalize: true,
* },
* };
*
* @param {Object.<string, function>} setters Attribute setters as returned from createAttributeSetters
* @param {Object.<string, module:twgl.AttribInfo>} buffers AttribInfos mapped by attribute name.
* @memberOf module:twgl/programs
* @deprecated use {@link module:twgl.setBuffersAndAttributes}
*/
function setAttributes(setters, buffers) {
for (var name in buffers) {
var setter = setters[name];
if (setter) {
setter(buffers[name]);
}
}
}
/**
* Sets attributes and buffers including the `ELEMENT_ARRAY_BUFFER` if appropriate
*
* Example:
*
* var programInfo = createProgramInfo(
* gl, ["some-vs", "some-fs");
*
* var arrays = {
* position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
* texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
* };
*
* var bufferInfo = createBufferInfoFromArrays(gl, arrays);
*
* gl.useProgram(programInfo.program);
*
* This will automatically bind the buffers AND set the
* attributes.
*
* setBuffersAndAttributes(gl, programInfo, bufferInfo);
*
* For the example above it is equivilent to
*
* gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
* gl.enableVertexAttribArray(a_positionLocation);
* gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0);
* gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
* gl.enableVertexAttribArray(a_texcoordLocation);
* gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext.
* @param {(module:twgl.ProgramInfo|Object.<string, function>)} setters A `ProgramInfo` as returned from {@link module:twgl.createProgrmaInfo} or Attribute setters as returned from {@link module:twgl.createAttributeSetters}
* @param {(module:twgl.BufferInfo|module:twgl.vertexArrayInfo)} buffers a `BufferInfo` as returned from {@link module:twgl.createBufferInfoFromArrays}.
* or a `VertexArrayInfo` as returned from {@link module:twgl.createVertexArrayInfo}
* @memberOf module:twgl/programs
*/
function setBuffersAndAttributes(gl, programInfo, buffers) {
if (buffers.vertexArrayObject) {
gl.bindVertexArray(buffers.vertexArrayObject);
} else {
setAttributes(programInfo.attribSetters || programInfo, buffers.attribs);
if (buffers.indices) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
}
}
}
/**
* @typedef {Object} ProgramInfo
* @property {WebGLProgram} program A shader program
* @property {Object<string, function>} uniformSetters object of setters as returned from createUniformSetters,
* @property {Object<string, function>} attribSetters object of setters as returned from createAttribSetters,
* @memberOf module:twgl
*/
/**
* Creates a ProgramInfo from an existing program.
*
* A ProgramInfo contains
*
* programInfo = {
* program: WebGLProgram,
* uniformSetters: object of setters as returned from createUniformSetters,
* attribSetters: object of setters as returned from createAttribSetters,
* }
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {WebGLProgram} program an existing WebGLProgram.
* @return {module:twgl.ProgramInfo} The created ProgramInfo.
* @memberOf module:twgl/programs
*/
function createProgramInfoFromProgram(gl, program) {
var uniformSetters = createUniformSetters(gl, program);
var attribSetters = createAttributeSetters(gl, program);
var programInfo = {
program: program,
uniformSetters: uniformSetters,
attribSetters: attribSetters
};
if (utils.isWebGL2(gl)) {
programInfo.uniformBlockSpec = createUniformBlockSpecFromProgram(gl, program);
}
return programInfo;
}
/**
* Creates a ProgramInfo from 2 sources.
*
* A ProgramInfo contains
*
* programInfo = {
* program: WebGLProgram,
* uniformSetters: object of setters as returned from createUniformSetters,
* attribSetters: object of setters as returned from createAttribSetters,
* }
*
* NOTE: There are 4 signatures for this function
*
* twgl.createProgramInfo(gl, [vs, fs], options);
* twgl.createProgramInfo(gl, [vs, fs], opt_errFunc);
* twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_errFunc);
* twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {string[]} shaderSourcess Array of sources for the
* shaders or ids. The first is assumed to be the vertex shader,
* the second the fragment shader.
* @param {module:twgl.ProgramOptions|string[]} [opt_attribs] Options for the program or an array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the attributes. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {module:twgl.ProgramInfo?} The created ProgramInfo or null if it failed to link or compile
* @memberOf module:twgl/programs
*/
function createProgramInfo(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {
var progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);
var good = true;
shaderSources = shaderSources.map(function (source) {
// Lets assume if there is no \n it's an id
if (source.indexOf("\n") < 0) {
var script = document.getElementById(source);
if (!script) {
progOptions.errorCallback("no element with id: " + source);
good = false;
} else {
source = script.text;
}
}
return source;
});
if (!good) {
return null;
}
var program = createProgramFromSources(gl, shaderSources, progOptions);
if (!program) {
return null;
}
return createProgramInfoFromProgram(gl, program);
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"createAttributeSetters": createAttributeSetters,
"createProgram": createProgram,
"createProgramFromScripts": createProgramFromScripts,
"createProgramFromSources": createProgramFromSources,
"createProgramInfo": createProgramInfo,
"createProgramInfoFromProgram": createProgramInfoFromProgram,
"createUniformSetters": createUniformSetters,
"createUniformBlockSpecFromProgram": createUniformBlockSpecFromProgram,
"createUniformBlockInfoFromProgram": createUniformBlockInfoFromProgram,
"createUniformBlockInfo": createUniformBlockInfo,
"setAttributes": setAttributes,
"setBuffersAndAttributes": setBuffersAndAttributes,
"setUniforms": setUniforms,
"setUniformBlock": setUniformBlock,
"setBlockUniforms": setBlockUniforms,
"bindUniformBlock": bindUniformBlock
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(8), __webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (textures, utils) {
"use strict";
/**
* Framebuffer related functions
*
* For backward compatibily they are available at both `twgl.framebuffer` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/framebuffers
*/
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
var UNSIGNED_BYTE = 0x1401;
/* PixelFormat */
var DEPTH_COMPONENT = 0x1902;
var RGBA = 0x1908;
/* Framebuffer Object. */
var RGBA4 = 0x8056;
var RGB5_A1 = 0x8057;
var RGB565 = 0x8D62;
var DEPTH_COMPONENT16 = 0x81A5;
var STENCIL_INDEX = 0x1901;
var STENCIL_INDEX8 = 0x8D48;
var DEPTH_STENCIL = 0x84F9;
var COLOR_ATTACHMENT0 = 0x8CE0;
var DEPTH_ATTACHMENT = 0x8D00;
var STENCIL_ATTACHMENT = 0x8D20;
var DEPTH_STENCIL_ATTACHMENT = 0x821A;
/* TextureWrapMode */
var REPEAT = 0x2901; // eslint-disable-line
var CLAMP_TO_EDGE = 0x812F;
var MIRRORED_REPEAT = 0x8370; // eslint-disable-line
/* TextureMagFilter */
var NEAREST = 0x2600; // eslint-disable-line
var LINEAR = 0x2601;
/* TextureMinFilter */
var NEAREST_MIPMAP_NEAREST = 0x2700; // eslint-disable-line
var LINEAR_MIPMAP_NEAREST = 0x2701; // eslint-disable-line
var NEAREST_MIPMAP_LINEAR = 0x2702; // eslint-disable-line
var LINEAR_MIPMAP_LINEAR = 0x2703; // eslint-disable-line
/**
* The options for a framebuffer attachment.
*
* Note: For a `format` that is a texture include all the texture
* options from {@link module:twgl.TextureOptions} for example
* `min`, `mag`, `clamp`, etc... Note that unlike {@link module:twgl.TextureOptions}
* `auto` defaults to `false` for attachment textures but `min` and `mag` default
* to `gl.LINEAR` and `wrap` defaults to `CLAMP_TO_EDGE`
*
* @typedef {Object} AttachmentOptions
* @property {number} [attach] The attachment point. Defaults
* to `gl.COLOR_ATTACTMENT0 + ndx` unless type is a depth or stencil type
* then it's gl.DEPTH_ATTACHMENT or `gl.DEPTH_STENCIL_ATTACHMENT` depending
* on the format or attachment type.
* @property {number} [format] The format. If one of `gl.RGBA4`,
* `gl.RGB565`, `gl.RGB5_A1`, `gl.DEPTH_COMPONENT16`,
* `gl.STENCIL_INDEX8` or `gl.DEPTH_STENCIL` then will create a
* renderbuffer. Otherwise will create a texture. Default = `gl.RGBA`
* @property {number} [type] The type. Used for texture. Default = `gl.UNSIGNED_BYTE`.
* @property {number} [target] The texture target for `gl.framebufferTexture2D`.
* Defaults to `gl.TEXTURE_2D`. Set to appropriate face for cube maps.
* @property {number} [level] level for `gl.framebufferTexture2D`. Defaults to 0.
* @property {WebGLObject} [attachment] An existing renderbuffer or texture.
* If provided will attach this Object. This allows you to share
* attachemnts across framebuffers.
* @memberOf module:twgl
*/
var defaultAttachments = [{ format: RGBA, type: UNSIGNED_BYTE, min: LINEAR, wrap: CLAMP_TO_EDGE }, { format: DEPTH_STENCIL }];
var attachmentsByFormat = {};
attachmentsByFormat[DEPTH_STENCIL] = DEPTH_STENCIL_ATTACHMENT;
attachmentsByFormat[STENCIL_INDEX] = STENCIL_ATTACHMENT;
attachmentsByFormat[STENCIL_INDEX8] = STENCIL_ATTACHMENT;
attachmentsByFormat[DEPTH_COMPONENT] = DEPTH_ATTACHMENT;
attachmentsByFormat[DEPTH_COMPONENT16] = DEPTH_ATTACHMENT;
function getAttachmentPointForFormat(format) {
return attachmentsByFormat[format];
}
var renderbufferFormats = {};
renderbufferFormats[RGBA4] = true;
renderbufferFormats[RGB5_A1] = true;
renderbufferFormats[RGB565] = true;
renderbufferFormats[DEPTH_STENCIL] = true;
renderbufferFormats[DEPTH_COMPONENT16] = true;
renderbufferFormats[STENCIL_INDEX] = true;
renderbufferFormats[STENCIL_INDEX8] = true;
function isRenderbufferFormat(format) {
return renderbufferFormats[format];
}
/**
* @typedef {Object} FramebufferInfo
* @property {WebGLFramebuffer} framebuffer The WebGLFramebuffer for this framebufferInfo
* @property {WebGLObject[]} attachments The created attachments in the same order as passed in to {@link module:twgl.createFramebufferInfo}.
* @memberOf module:twgl
*/
/**
* Creates a framebuffer and attachments.
*
* This returns a {@link module:twgl.FramebufferInfo} because it needs to return the attachments as well as the framebuffer.
*
* The simplest usage
*
* // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer
* var fbi = twgl.createFramebufferInfo(gl);
*
* More complex usage
*
* // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer
* var attachments = [
* { format: RGB565, mag: NEAREST },
* { format: STENCIL_INDEX8 },
* ]
* var fbi = twgl.createFramebufferInfo(gl, attachments);
*
* Passing in a specific size
*
* var width = 256;
* var height = 256;
* var fbi = twgl.createFramebufferInfo(gl, attachments, width, height);
*
* **Note!!** It is up to you to check if the framebuffer is renderable by calling `gl.checkFramebufferStatus`.
* [WebGL only guarantees 3 combinations of attachments work](https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.6).
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.AttachmentOptions[]} [attachments] which attachments to create. If not provided the default is a framebuffer with an
* `RGBA`, `UNSIGNED_BYTE` texture `COLOR_ATTACHMENT0` and a `DEPTH_STENCIL` renderbuffer `DEPTH_STENCIL_ATTACHMENT`.
* @param {number} [width] the width for the attachments. Default = size of drawingBuffer
* @param {number} [height] the height for the attachments. Defautt = size of drawingBuffer
* @return {module:twgl.FramebufferInfo} the framebuffer and attachments.
* @memberOf module:twgl/framebuffers
*/
function createFramebufferInfo(gl, attachments, width, height) {
var target = gl.FRAMEBUFFER;
var fb = gl.createFramebuffer();
gl.bindFramebuffer(target, fb);
width = width || gl.drawingBufferWidth;
height = height || gl.drawingBufferHeight;
attachments = attachments || defaultAttachments;
var colorAttachmentCount = 0;
var framebufferInfo = {
framebuffer: fb,
attachments: [],
width: width,
height: height
};
attachments.forEach(function (attachmentOptions) {
var attachment = attachmentOptions.attachment;
var format = attachmentOptions.format;
var attachmentPoint = getAttachmentPointForFormat(format);
if (!attachmentPoint) {
attachmentPoint = COLOR_ATTACHMENT0 + colorAttachmentCount++;
}
if (!attachment) {
if (isRenderbufferFormat(format)) {
attachment = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, attachment);
gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height);
} else {
var textureOptions = utils.shallowCopy(attachmentOptions);
textureOptions.width = width;
textureOptions.height = height;
if (textureOptions.auto === undefined) {
textureOptions.auto = false;
textureOptions.min = textureOptions.min || gl.LINEAR;
textureOptions.mag = textureOptions.mag || gl.LINEAR;
textureOptions.wrapS = textureOptions.wrapS || textureOptions.wrap || gl.CLAMP_TO_EDGE;
textureOptions.wrapT = textureOptions.wrapT || textureOptions.wrap || gl.CLAMP_TO_EDGE;
}
attachment = textures.createTexture(gl, textureOptions);
}
}
if (attachment instanceof WebGLRenderbuffer) {
gl.framebufferRenderbuffer(target, attachmentPoint, gl.RENDERBUFFER, attachment);
} else if (attachment instanceof WebGLTexture) {
gl.framebufferTexture2D(target, attachmentPoint, attachmentOptions.texTarget || gl.TEXTURE_2D, attachment, attachmentOptions.level || 0);
} else {
throw "unknown attachment type";
}
framebufferInfo.attachments.push(attachment);
});
return framebufferInfo;
}
/**
* Resizes the attachments of a framebuffer.
*
* You need to pass in the same `attachments` as you passed in {@link module:twgl.createFramebufferInfo}
* because TWGL has no idea the format/type of each attachment.
*
* The simplest usage
*
* // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer
* var fbi = twgl.createFramebufferInfo(gl);
*
* ...
*
* function render() {
* if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {
* // resize the attachments
* twgl.resizeFramebufferInfo(gl, fbi);
* }
*
* More complex usage
*
* // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer
* var attachments = [
* { format: RGB565, mag: NEAREST },
* { format: STENCIL_INDEX8 },
* ]
* var fbi = twgl.createFramebufferInfo(gl, attachments);
*
* ...
*
* function render() {
* if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {
* // resize the attachments to match
* twgl.resizeFramebufferInfo(gl, fbi, attachments);
* }
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.FramebufferInfo} framebufferInfo a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.
* @param {module:twgl.AttachmentOptions[]} [attachments] the same attachments options as passed to {@link module:twgl.createFramebufferInfo}.
* @param {number} [width] the width for the attachments. Default = size of drawingBuffer
* @param {number} [height] the height for the attachments. Defautt = size of drawingBuffer
* @memberOf module:twgl/framebuffers
*/
function resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height) {
width = width || gl.drawingBufferWidth;
height = height || gl.drawingBufferHeight;
framebufferInfo.width = width;
framebufferInfo.height = height;
attachments = attachments || defaultAttachments;
attachments.forEach(function (attachmentOptions, ndx) {
var attachment = framebufferInfo.attachments[ndx];
var format = attachmentOptions.format;
if (attachment instanceof WebGLRenderbuffer) {
gl.bindRenderbuffer(gl.RENDERBUFFER, attachment);
gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height);
} else if (attachment instanceof WebGLTexture) {
textures.resizeTexture(gl, attachment, attachmentOptions, width, height);
} else {
throw "unknown attachment type";
}
});
}
/**
* Binds a framebuffer
*
* This function pretty much soley exists because I spent hours
* trying to figure out why something I wrote wasn't working only
* to realize I forget to set the viewport dimensions.
* My hope is this function will fix that.
*
* It is effectively the same as
*
* gl.bindFramebuffer(gl.FRAMEBUFFER, someFramebufferInfo.framebuffer);
* gl.viewport(0, 0, someFramebufferInfo.width, someFramebufferInfo.height);
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.FramebufferInfo} [framebufferInfo] a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.
* If not passed will bind the canvas.
* @param {number} [target] The target. If not passed `gl.FRAMEBUFFER` will be used.
* @memberOf module:twgl/framebuffers
*/
function bindFramebufferInfo(gl, framebufferInfo, target) {
target = target || gl.FRAMEBUFFER;
if (framebufferInfo) {
gl.bindFramebuffer(target, framebufferInfo.framebuffer);
gl.viewport(0, 0, framebufferInfo.width, framebufferInfo.height);
} else {
gl.bindFramebuffer(target, null);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
}
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"bindFramebufferInfo": bindFramebufferInfo,
"createFramebufferInfo": createFramebufferInfo,
"resizeFramebufferInfo": resizeFramebufferInfo
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(3), __webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (typedArrays, utils) {
"use strict";
/**
* Low level texture related functions
*
* You should generally not need to use these functions. They are provided
* for those cases where you're doing something out of the ordinary
* and you need lower level access.
*
* For backward compatibily they are available at both `twgl.textures` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/textures
*/
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
var defaults = {
textureColor: new Uint8Array([128, 192, 255, 255]),
textureOptions: {},
crossOrigin: undefined
};
var isArrayBuffer = typedArrays.isArrayBuffer;
// Should we make this on demand?
var ctx = document.createElement("canvas").getContext("2d");
/* PixelFormat */
var ALPHA = 0x1906;
var RGB = 0x1907;
var RGBA = 0x1908;
var LUMINANCE = 0x1909;
var LUMINANCE_ALPHA = 0x190A;
var DEPTH_COMPONENT = 0x1902;
var DEPTH_STENCIL = 0x84F9;
/* TextureWrapMode */
var REPEAT = 0x2901; // eslint-disable-line
var MIRRORED_REPEAT = 0x8370; // eslint-disable-line
/* TextureMagFilter */
var NEAREST = 0x2600; // eslint-disable-line
/* TextureMinFilter */
var NEAREST_MIPMAP_NEAREST = 0x2700; // eslint-disable-line
var LINEAR_MIPMAP_NEAREST = 0x2701; // eslint-disable-line
var NEAREST_MIPMAP_LINEAR = 0x2702; // eslint-disable-line
var LINEAR_MIPMAP_LINEAR = 0x2703; // eslint-disable-line
var R8 = 0x8229;
var R8_SNORM = 0x8F94;
var R16F = 0x822D;
var R32F = 0x822E;
var R8UI = 0x8232;
var R8I = 0x8231;
var RG16UI = 0x823A;
var RG16I = 0x8239;
var RG32UI = 0x823C;
var RG32I = 0x823B;
var RG8 = 0x822B;
var RG8_SNORM = 0x8F95;
var RG16F = 0x822F;
var RG32F = 0x8230;
var RG8UI = 0x8238;
var RG8I = 0x8237;
var R16UI = 0x8234;
var R16I = 0x8233;
var R32UI = 0x8236;
var R32I = 0x8235;
var RGB8 = 0x8051;
var SRGB8 = 0x8C41;
var RGB565 = 0x8D62;
var RGB8_SNORM = 0x8F96;
var R11F_G11F_B10F = 0x8C3A;
var RGB9_E5 = 0x8C3D;
var RGB16F = 0x881B;
var RGB32F = 0x8815;
var RGB8UI = 0x8D7D;
var RGB8I = 0x8D8F;
var RGB16UI = 0x8D77;
var RGB16I = 0x8D89;
var RGB32UI = 0x8D71;
var RGB32I = 0x8D83;
var RGBA8 = 0x8058;
var SRGB8_ALPHA8 = 0x8C43;
var RGBA8_SNORM = 0x8F97;
var RGB5_A1 = 0x8057;
var RGBA4 = 0x8056;
var RGB10_A2 = 0x8059;
var RGBA16F = 0x881A;
var RGBA32F = 0x8814;
var RGBA8UI = 0x8D7C;
var RGBA8I = 0x8D8E;
var RGB10_A2UI = 0x906F;
var RGBA16UI = 0x8D76;
var RGBA16I = 0x8D88;
var RGBA32I = 0x8D82;
var RGBA32UI = 0x8D70;
var DEPTH_COMPONENT16 = 0x81A5;
var DEPTH_COMPONENT24 = 0x81A6;
var DEPTH_COMPONENT32F = 0x8CAC;
var DEPTH32F_STENCIL8 = 0x8CAD;
var DEPTH24_STENCIL8 = 0x88F0;
/* DataType */
var BYTE = 0x1400;
var UNSIGNED_BYTE = 0x1401;
var SHORT = 0x1402;
var UNSIGNED_SHORT = 0x1403;
var INT = 0x1404;
var UNSIGNED_INT = 0x1405;
var FLOAT = 0x1406;
var UNSIGNED_SHORT_4_4_4_4 = 0x8033;
var UNSIGNED_SHORT_5_5_5_1 = 0x8034;
var UNSIGNED_SHORT_5_6_5 = 0x8363;
var HALF_FLOAT = 0x140B;
var UNSIGNED_INT_2_10_10_10_REV = 0x8368;
var UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;
var UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;
var FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD;
var UNSIGNED_INT_24_8 = 0x84FA;
var RG = 0x8227;
var RG_INTEGER = 0x8228;
var RED = 0x1903;
var RED_INTEGER = 0x8D94;
var RGB_INTEGER = 0x8D98;
var RGBA_INTEGER = 0x8D99;
var formatInfo = {};
{
// NOTE: this is named `numColorComponents` vs `numComponents` so we can let Uglify mangle
// the name.
var f = formatInfo;
f[ALPHA] = { numColorComponents: 1 };
f[LUMINANCE] = { numColorComponents: 1 };
f[LUMINANCE_ALPHA] = { numColorComponents: 2 };
f[RGB] = { numColorComponents: 3 };
f[RGBA] = { numColorComponents: 4 };
f[RED] = { numColorComponents: 1 };
f[RED_INTEGER] = { numColorComponents: 1 };
f[RG] = { numColorComponents: 2 };
f[RG_INTEGER] = { numColorComponents: 2 };
f[RGB] = { numColorComponents: 3 };
f[RGB_INTEGER] = { numColorComponents: 3 };
f[RGBA] = { numColorComponents: 4 };
f[RGBA_INTEGER] = { numColorComponents: 4 };
f[DEPTH_COMPONENT] = { numColorComponents: 1 };
f[DEPTH_STENCIL] = { numColorComponents: 2 };
}
var textureInternalFormatInfo = {};
{
(function () {
// NOTE: these properties need unique names so we can let Uglify mangle the name.
var t = textureInternalFormatInfo;
// unsized formats
t[ALPHA] = { textureFormat: ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 4], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT] };
t[LUMINANCE] = { textureFormat: LUMINANCE, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 4], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT] };
t[LUMINANCE_ALPHA] = { textureFormat: LUMINANCE_ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [2, 4, 8], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT] };
t[RGB] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 6, 12, 2], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT, UNSIGNED_SHORT_5_6_5] };
t[RGBA] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 8, 16, 2, 2], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_5_5_5_1] };
// sized formats
t[R8] = { textureFormat: RED, colorRenderable: true, textureFilterable: true, bytesPerElement: 1, type: UNSIGNED_BYTE };
t[R8_SNORM] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: 1, type: BYTE };
t[R16F] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [4, 2], type: [FLOAT, HALF_FLOAT] };
t[R32F] = { textureFormat: RED, colorRenderable: false, textureFilterable: false, bytesPerElement: 4, type: FLOAT };
t[R8UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 1, type: UNSIGNED_BYTE };
t[R8I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 1, type: BYTE };
t[R16UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: UNSIGNED_SHORT };
t[R16I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: SHORT };
t[R32UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT };
t[R32I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: INT };
t[RG8] = { textureFormat: RG, colorRenderable: true, textureFilterable: true, bytesPerElement: 2, type: UNSIGNED_BYTE };
t[RG8_SNORM] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: 2, type: BYTE };
t[RG16F] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [8, 4], type: [FLOAT, HALF_FLOAT] };
t[RG32F] = { textureFormat: RG, colorRenderable: false, textureFilterable: false, bytesPerElement: 8, type: FLOAT };
t[RG8UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: UNSIGNED_BYTE };
t[RG8I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: BYTE };
t[RG16UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_SHORT };
t[RG16I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: SHORT };
t[RG32UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: UNSIGNED_INT };
t[RG32I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: INT };
t[RGB8] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: 3, type: UNSIGNED_BYTE };
t[SRGB8] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: 3, type: UNSIGNED_BYTE };
t[RGB565] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 2], type: [UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5] };
t[RGB8_SNORM] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: 3, type: BYTE };
t[R11F_G11F_B10F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT, HALF_FLOAT, UNSIGNED_INT_10F_11F_11F_REV] };
t[RGB9_E5] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT, HALF_FLOAT, UNSIGNED_INT_5_9_9_9_REV] };
t[RGB16F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6], type: [FLOAT, HALF_FLOAT] };
t[RGB32F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: false, bytesPerElement: 12, type: FLOAT };
t[RGB8UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 3, type: UNSIGNED_BYTE };
t[RGB8I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 3, type: BYTE };
t[RGB16UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 6, type: UNSIGNED_SHORT };
t[RGB16I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 6, type: SHORT };
t[RGB32UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 12, type: UNSIGNED_INT };
t[RGB32I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 12, type: INT };
t[RGBA8] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: 4, type: UNSIGNED_BYTE };
t[SRGB8_ALPHA8] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: 4, type: UNSIGNED_BYTE };
t[RGBA8_SNORM] = { textureFormat: RGBA, colorRenderable: false, textureFilterable: true, bytesPerElement: 4, type: BYTE };
t[RGB5_A1] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2, 4], type: [UNSIGNED_BYTE, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_INT_2_10_10_10_REV] };
t[RGBA4] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2], type: [UNSIGNED_BYTE, UNSIGNED_SHORT_4_4_4_4] };
t[RGB10_A2] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: 4, type: UNSIGNED_INT_2_10_10_10_REV };
t[RGBA16F] = { textureFormat: RGBA, colorRenderable: false, textureFilterable: true, bytesPerElement: [16, 8], type: [FLOAT, HALF_FLOAT] };
t[RGBA32F] = { textureFormat: RGBA, colorRenderable: false, textureFilterable: false, bytesPerElement: 16, type: FLOAT };
t[RGBA8UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_BYTE };
t[RGBA8I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: BYTE };
t[RGB10_A2UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT_2_10_10_10_REV };
t[RGBA16UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: UNSIGNED_SHORT };
t[RGBA16I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: SHORT };
t[RGBA32I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 16, type: INT };
t[RGBA32UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 16, type: UNSIGNED_INT };
// Sized Internal
t[DEPTH_COMPONENT16] = { textureFormat: DEPTH_COMPONENT, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_SHORT, UNSIGNED_INT] };
t[DEPTH_COMPONENT24] = { textureFormat: DEPTH_COMPONENT, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT };
t[DEPTH_COMPONENT32F] = { textureFormat: DEPTH_COMPONENT, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: FLOAT };
t[DEPTH24_STENCIL8] = { textureFormat: DEPTH_STENCIL, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT_24_8 };
t[DEPTH32F_STENCIL8] = { textureFormat: DEPTH_STENCIL, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: FLOAT_32_UNSIGNED_INT_24_8_REV };
Object.keys(t).forEach(function (internalFormat) {
var info = t[internalFormat];
info.bytesPerElementMap = {};
if (Array.isArray(info.bytesPerElement)) {
info.bytesPerElement.forEach(function (bytesPerElement, ndx) {
var type = info.type[ndx];
info.bytesPerElementMap[type] = bytesPerElement;
});
} else {
var type = info.type;
info.bytesPerElementMap[type] = info.bytesPerElement;
}
});
})();
}
/**
* Gets the number of bytes per element for a given internalFormat / type
* @param {number} internalFormat The internalFormat parameter from texImage2D etc..
* @param {number} type The type parameter for texImage2D etc..
* @return {number} the number of bytes per element for the given internalFormat, type combo
* @memberOf module:twgl/textures
*/
function getBytesPerElementForInternalFormat(internalFormat, type) {
var info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
var bytesPerElement = info.bytesPerElementMap[type];
if (bytesPerElement === undefined) {
throw "unknown internal format";
}
return bytesPerElement;
}
/**
* Gets the format for a given internalFormat
*
* @param {number} internalFormat The internal format
* @return {{format:number, type:number}} the corresponding format and type
*/
function getFormatAndTypeForInternalFormat(internalFormat) {
var info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
return {
format: info.textureFormat,
type: Array.isArray(info.type) ? info.type[0] : info.type
};
}
/**
* Returns true if value is power of 2
* @param {number} value number to check.
* @return true if value is power of 2
*/
function isPowerOf2(value) {
return (value & value - 1) === 0;
}
/**
* Gets whether or not we can generate mips for the given format
* @param {number} internalFormat The internalFormat parameter from texImage2D etc..
* @param {number} type The type parameter for texImage2D etc..
* @return {boolean} true if we can generate mips
*/
function canGenerateMipmap(gl, width, height, internalFormat /*, type */) {
if (!utils.isWebGL2(gl)) {
return isPowerOf2(width) && isPowerOf2(height);
}
var info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
return info.colorRenderable && info.textureFilterable;
}
/**
* Gets whether or not we can generate mips for the given format
* @param {number} internalFormat The internalFormat parameter from texImage2D etc..
* @param {number} type The type parameter for texImage2D etc..
* @return {boolean} true if we can generate mips
*/
function canFilter(internalFormat /*, type */) {
var info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
return info.textureFilterable;
}
/**
* Gets the number of compontents for a given image format.
* @param {number} format the format.
* @return {number} the number of components for the format.
* @memberOf module:twgl/textures
*/
function getNumComponentsForFormat(format) {
var info = formatInfo[format];
if (!info) {
throw "unknown format: " + format;
}
return info.numColorComponents;
}
/**
* Gets the texture type for a given array type.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @return {number} the gl texture type
*/
function getTextureTypeForArrayType(gl, src, defaultType) {
if (isArrayBuffer(src)) {
return typedArrays.getGLTypeForTypedArray(src);
}
return defaultType || gl.UNSIGNED_BYTE;
}
function guessDimensions(gl, target, width, height, numElements) {
if (numElements % 1 !== 0) {
throw "can't guess dimensions";
}
if (!width && !height) {
var size = Math.sqrt(numElements / (target === gl.TEXTURE_CUBE_MAP ? 6 : 1));
if (size % 1 === 0) {
width = size;
height = size;
} else {
width = numElements;
height = 1;
}
} else if (!height) {
height = numElements / width;
if (height % 1) {
throw "can't guess dimensions";
}
} else if (!width) {
width = numElements / height;
if (width % 1) {
throw "can't guess dimensions";
}
}
return {
width: width,
height: height
};
}
/**
* Sets the default texture color.
*
* The default texture color is used when loading textures from
* urls. Because the URL will be loaded async we'd like to be
* able to use the texture immediately. By putting a 1x1 pixel
* color in the texture we can start using the texture before
* the URL has loaded.
*
* @param {number[]} color Array of 4 values in the range 0 to 1
* @deprecated see {@link module:twgl.setDefaults}
* @memberOf module:twgl/textures
*/
function setDefaultTextureColor(color) {
defaults.textureColor = new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);
}
function setDefaults(newDefaults) {
utils.copyExistingProperties(newDefaults, defaults);
if (newDefaults.textureColor) {
setDefaultTextureColor(newDefaults.textureColor);
}
}
/**
* Gets a string for gl enum
*
* Note: Several enums are the same. Without more
* context (which function) it's impossible to always
* give the correct enum.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {number} value the value of the enum you want to look up.
*/
var glEnumToString = function () {
var enums;
function init(gl) {
if (!enums) {
enums = {};
for (var key in gl) {
if (typeof gl[key] === 'number') {
enums[gl[key]] = key;
}
}
}
}
return function glEnumToString(gl, value) {
init(gl);
return enums[value] || "0x" + value.toString(16);
};
}();
/**
* A function to generate the source for a texture.
* @callback TextureFunc
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {module:twgl.TextureOptions} options the texture options
* @return {*} Returns any of the things documentented for `src` for {@link module:twgl.TextureOptions}.
* @memberOf module:twgl
*/
/**
* Texture options passed to most texture functions. Each function will use whatever options
* are appropriate for its needs. This lets you pass the same options to all functions.
*
* @typedef {Object} TextureOptions
* @property {number} [target] the type of texture `gl.TEXTURE_2D` or `gl.TEXTURE_CUBE_MAP`. Defaults to `gl.TEXTURE_2D`.
* @property {number} [width] the width of the texture. Only used if src is an array or typed array or null.
* @property {number} [height] the height of a texture. Only used if src is an array or typed array or null.
* @property {number} [depth] the depth of a texture. Only used if src is an array or type array or null and target is `TEXTURE_3D` .
* @property {number} [min] the min filter setting (eg. `gl.LINEAR`). Defaults to `gl.NEAREST_MIPMAP_LINEAR`
* or if texture is not a power of 2 on both dimensions then defaults to `gl.LINEAR`.
* @property {number} [mag] the mag filter setting (eg. `gl.LINEAR`). Defaults to `gl.LINEAR`
* @property {number} [minMag] both the min and mag filter settings.
* @property {number} [internalFormat] internal format for texture. Defaults to `gl.RGBA`
* @property {number} [format] format for texture. Defaults to `gl.RGBA`.
* @property {number} [type] type for texture. Defaults to `gl.UNSIGNED_BYTE` unless `src` is ArrayBuffer. If `src`
* is ArrayBuffer defaults to type that matches ArrayBuffer type.
* @property {number} [wrap] Texture wrapping for both S and T (and R if TEXTURE_3D or WebGLSampler). Defaults to `gl.REPEAT` for 2D unless src is WebGL1 and src not npot and `gl.CLAMP_TO_EDGE` for cube
* @property {number} [wrapS] Texture wrapping for S. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.
* @property {number} [wrapT] Texture wrapping for T. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.
* @property {number} [wrapR] Texture wrapping for R. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.
* @property {number} [minLod] TEXTURE_MIN_LOD setting
* @property {number} [maxLod] TEXTURE_MAX_LOD setting
* @property {number} [baseLevel] TEXTURE_BASE_LEVEL setting
* @property {number} [maxLevel] TEXTURE_MAX_LEVEL setting
* @property {number} [unpackAlignment] The `gl.UNPACK_ALIGNMENT` used when uploading an array. Defaults to 1.
* @property {number} [premultiplyAlpha] Whether or not to premultiply alpha. Defaults to whatever the current setting is.
* This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override
* the current setting for specific textures.
* @property {number} [flipY] Whether or not to flip the texture vertically on upload. Defaults to whatever the current setting is.
* This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override
* the current setting for specific textures.
* @property {number} [colorspaceConversion] Whether or not to let the browser do colorspace conversion of the texture on upload. Defaults to whatever the current setting is.
* This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override
* the current setting for specific textures.
* @property {(number[]|ArrayBuffer)} color color used as temporary 1x1 pixel color for textures loaded async when src is a string.
* If it's a JavaScript array assumes color is 0 to 1 like most GL colors as in `[1, 0, 0, 1] = red=1, green=0, blue=0, alpha=0`.
* Defaults to `[0.5, 0.75, 1, 1]`. See {@link module:twgl.setDefaultTextureColor}. If `false` texture is set. Can be used to re-load a texture
* @property {boolean} [auto] If not `false` then texture working filtering is set automatically for non-power of 2 images and
* mips are generated for power of 2 images.
* @property {number[]} [cubeFaceOrder] The order that cube faces are pulled out of an img or set of images. The default is
*
* [gl.TEXTURE_CUBE_MAP_POSITIVE_X,
* gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
* gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
* gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
* gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
* gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]
*
* @property {(number[]|ArrayBuffer|HTMLCanvasElement|HTMLImageElement|HTMLVideoElement|string|string[]|module:twgl.TextureFunc)} [src] source for texture
*
* If `string` then it's assumed to be a URL to an image. The image will be downloaded async. A usable
* 1x1 pixel texture will be returned immediatley. The texture will be updated once the image has downloaded.
* If `target` is `gl.TEXTURE_CUBE_MAP` will attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3.
* The pieces will be uploaded in `cubeFaceOrder`
*
* If `string[]` then it must have 6 entries, one for each face of a cube map. Target must be `gl.TEXTURE_CUBE_MAP`.
*
* If `HTMLElement` then it wil be used immediately to create the contents of the texture. Examples `HTMLImageElement`,
* `HTMLCanvasElement`, `HTMLVideoElement`.
*
* If `number[]` or `ArrayBuffer` it's assumed to be data for a texture. If `width` or `height` is
* not specified it is guessed as follows. First the number of elements is computed by `src.length / numComponets`
* where `numComponents` is derived from `format`. If `target` is `gl.TEXTURE_CUBE_MAP` then `numElements` is divided
* by 6. Then
*
* * If neither `width` nor `height` are specified and `sqrt(numElements)` is an integer then width and height
* are set to `sqrt(numElements)`. Otherwise `width = numElements` and `height = 1`.
*
* * If only one of `width` or `height` is specified then the other equals `numElements / specifiedDimension`.
*
* If `number[]` will be converted to `type`.
*
* If `src` is a function it will be called with a `WebGLRenderingContext` and these options.
* Whatever it returns is subject to these rules. So it can return a string url, an `HTMLElement`
* an array etc...
*
* If `src` is undefined then an empty texture will be created of size `width` by `height`.
*
* @property {string} [crossOrigin] What to set the crossOrigin property of images when they are downloaded.
* default: undefined. Also see {@link module:twgl.setDefaults}.
*
* @memberOf module:twgl
*/
// NOTE: While querying GL is considered slow it's not remotely as slow
// as uploading a texture. On top of that you're unlikely to call this in
// a perf critical loop. Even if upload a texture every frame that's unlikely
// to be more than 1 or 2 textures a frame. In other words, the benefits of
// making the API easy to use outweigh any supposed perf benefits
var lastPackState = {};
/**
* Saves any packing state that will be set based on the options.
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
*/
function savePackState(gl, options) {
if (options.colorspaceConversion !== undefined) {
lastPackState.colorspaceConversion = gl.getParameter(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL);
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, options.colorspaceConversion);
}
if (options.premultiplyAlpha !== undefined) {
lastPackState.premultiplyAlpha = gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlpha);
}
if (options.flipY !== undefined) {
lastPackState.flipY = gl.getParameter(gl.UNPACK_FLIP_Y_WEBGL);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, options.flipY);
}
}
/**
* Restores any packing state that was set based on the options.
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
*/
function restorePackState(gl, options) {
if (options.colorspaceConversion !== undefined) {
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, lastPackState.colorspaceConversion);
}
if (options.premultiplyAlpha !== undefined) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, lastPackState.premultiplyAlpha);
}
if (options.flipY !== undefined) {
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, lastPackState.flipY);
}
}
/**
* Sets the parameters of a texture or sampler
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {number|WebGLSampler} target texture target or sampler
* @param {function()} parameteriFn texParamteri or samplerParameteri fn
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
*/
function setTextureSamplerParameters(gl, target, parameteriFn, options) {
if (options.minMag) {
parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.minMag);
parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.minMag);
}
if (options.min) {
parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.min);
}
if (options.mag) {
parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.mag);
}
if (options.wrap) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrap);
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrap);
if (target === gl.TEXTURE_3D || target instanceof WebGLSampler) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrap);
}
}
if (options.wrapR) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrapR);
}
if (options.wrapS) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrapS);
}
if (options.wrapT) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrapT);
}
if (options.minLod) {
parameteriFn.call(gl, target, gl.TEXTURE_MIN_LOD, options.minLod);
}
if (options.maxLod) {
parameteriFn.call(gl, target, gl.TEXTURE_MAX_LOD, options.maxLod);
}
if (options.baseLevel) {
parameteriFn.call(gl, target, gl.TEXTURE_BASE_LEVEL, options.baseLevel);
}
if (options.maxLevel) {
parameteriFn.call(gl, target, gl.TEXTURE_MAX_LEVEL, options.maxLevel);
}
}
/**
* Sets the texture parameters of a texture.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @memberOf module:twgl/textures
*/
function setTextureParameters(gl, tex, options) {
var target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
setTextureSamplerParameters(gl, target, gl.texParameteri, options);
}
/**
* Sets the sampler parameters of a sampler.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLSampler} sampler the WebGLSampler to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @memberOf module:twgl/textures
*/
function setSamplerParameters(gl, sampler, options) {
setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options);
}
/**
* Creates a new sampler object and sets parameters.
*
* Example:
*
* const sampler = twgl.createSampler(gl, {
* minMag: gl.NEAREST, // sets both TEXTURE_MIN_FILTER and TEXTURE_MAG_FILTER
* wrap: gl.CLAMP_TO_NEAREST, // sets both TEXTURE_WRAP_S and TEXTURE_WRAP_T and TEXTURE_WRAP_R
* });
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {Object.<string,module:twgl.TextureOptions>} options A object of TextureOptions one per sampler.
* @return {Object.<string,WebGLSampler>} the created samplers by name
*/
function createSampler(gl, options) {
var sampler = gl.createSampler();
setSamplerParameters(gl, sampler, options);
return sampler;
}
/**
* Creates a multiple sampler objects and sets parameters on each.
*
* Example:
*
* const samplers = twgl.createSamplers(gl, {
* nearest: {
* minMag: gl.NEAREST,
* },
* nearestClampS: {
* minMag: gl.NEAREST,
* wrapS: gl.CLAMP_TO_NEAREST,
* },
* linear: {
* minMag: gl.LINEAR,
* },
* nearestClamp: {
* minMag: gl.NEAREST,
* wrap: gl.CLAMP_TO_EDGE,
* },
* linearClamp: {
* minMag: gl.LINEAR,
* wrap: gl.CLAMP_TO_EDGE,
* },
* linearClampT: {
* minMag: gl.LINEAR,
* wrapT: gl.CLAMP_TO_EDGE,
* },
* });
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set on the sampler
*/
function createSamplers(gl, samplerOptions) {
var samplers = {};
Object.keys(samplerOptions).forEach(function (name) {
samplers[name] = createSampler(gl, samplerOptions[name]);
});
return samplers;
}
/**
* Makes a 1x1 pixel
* If no color is passed in uses the default color which can be set by calling `setDefaultTextureColor`.
* @param {(number[]|ArrayBuffer)} [color] The color using 0-1 values
* @return {Uint8Array} Unit8Array with color.
*/
function make1Pixel(color) {
color = color || defaults.textureColor;
if (isArrayBuffer(color)) {
return color;
}
return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);
}
/**
* Sets filtering or generates mips for texture based on width or height
* If width or height is not passed in uses `options.width` and//or `options.height`
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @param {number} [width] width of texture
* @param {number} [height] height of texture
* @param {number} [internalFormat] The internalFormat parameter from texImage2D etc..
* @param {number} [type] The type parameter for texImage2D etc..
* @memberOf module:twgl/textures
*/
function setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type) {
options = options || defaults.textureOptions;
internalFormat = internalFormat || gl.RGBA;
type = type || gl.UNSIGNED_BYTE;
var target = options.target || gl.TEXTURE_2D;
width = width || options.width;
height = height || options.height;
gl.bindTexture(target, tex);
if (canGenerateMipmap(gl, width, height, internalFormat, type)) {
gl.generateMipmap(target);
} else {
var filtering = canFilter(internalFormat, type) ? gl.LINEAR : gl.NEAREST;
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filtering);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filtering);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
}
/**
* Gets an array of cubemap face enums
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @return {number[]} cubemap face enums
*/
function getCubeFaceOrder(gl, options) {
options = options || {};
return options.cubeFaceOrder || [gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];
}
/**
* @typedef {Object} FaceInfo
* @property {number} face gl enum for texImage2D
* @property {number} ndx face index (0 - 5) into source data
* @ignore
*/
/**
* Gets an array of FaceInfos
* There's a bug in some NVidia drivers that will crash the driver if
* `gl.TEXTURE_CUBE_MAP_POSITIVE_X` is not uploaded first. So, we take
* the user's desired order from his faces to WebGL and make sure we
* do the faces in WebGL order
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @return {FaceInfo[]} cubemap face infos. Arguably the `face` property of each element is redundent but
* it's needed internally to sort the array of `ndx` properties by `face`.
*/
function getCubeFacesWithNdx(gl, options) {
var faces = getCubeFaceOrder(gl, options);
// work around bug in NVidia drivers. We have to upload the first face first else the driver crashes :(
var facesWithNdx = faces.map(function (face, ndx) {
return { face: face, ndx: ndx };
});
facesWithNdx.sort(function (a, b) {
return a.face - b.face;
});
return facesWithNdx;
}
/**
* Set a texture from the contents of an element. Will also set
* texture filtering or generate mips based on the dimensions of the element
* unless `options.auto === false`. If `target === gl.TEXTURE_CUBE_MAP` will
* attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {HTMLElement} element a canvas, img, or video element.
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @memberOf module:twgl/textures
* @kind function
*/
function setTextureFromElement(gl, tex, element, options) {
options = options || defaults.textureOptions;
var target = options.target || gl.TEXTURE_2D;
var width = element.width;
var height = element.height;
var internalFormat = options.internalFormat || options.format || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var format = options.format || formatType.format;
var type = options.type || formatType.type;
savePackState(gl, options);
gl.bindTexture(target, tex);
if (target === gl.TEXTURE_CUBE_MAP) {
// guess the parts
var imgWidth = element.width;
var imgHeight = element.height;
var size;
var slices;
if (imgWidth / 6 === imgHeight) {
// It's 6x1
size = imgHeight;
slices = [0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0];
} else if (imgHeight / 6 === imgWidth) {
// It's 1x6
size = imgWidth;
slices = [0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5];
} else if (imgWidth / 3 === imgHeight / 2) {
// It's 3x2
size = imgWidth / 3;
slices = [0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1];
} else if (imgWidth / 2 === imgHeight / 3) {
// It's 2x3
size = imgWidth / 2;
slices = [0, 0, 1, 0, 0, 1, 1, 1, 0, 2, 1, 2];
} else {
throw "can't figure out cube map from element: " + (element.src ? element.src : element.nodeName);
}
ctx.canvas.width = size;
ctx.canvas.height = size;
width = size;
height = size;
getCubeFacesWithNdx(gl, options).forEach(function (f) {
var xOffset = slices[f.ndx * 2 + 0] * size;
var yOffset = slices[f.ndx * 2 + 1] * size;
ctx.drawImage(element, xOffset, yOffset, size, size, 0, 0, size, size);
gl.texImage2D(f.face, 0, internalFormat, format, type, ctx.canvas);
});
// Free up the canvas memory
ctx.canvas.width = 1;
ctx.canvas.height = 1;
} else if (target === gl.TEXTURE_3D) {
var smallest = Math.min(element.width, element.height);
var largest = Math.max(element.width, element.height);
var depth = largest / smallest;
if (depth % 1 !== 0) {
throw "can not compute 3D dimensions of element";
}
var xMult = element.width === largest ? 1 : 0;
var yMult = element.height === largest ? 1 : 0;
gl.texImage3D(target, 0, internalFormat, smallest, smallest, smallest, 0, format, type, null);
// remove this is texSubImage3D gets width and height arguments
ctx.canvas.width = smallest;
ctx.canvas.height = smallest;
for (var d = 0; d < depth; ++d) {
// gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, d * smallest);
// gl.texSubImage3D(target, 0, 0, 0, d, format, type, element);
var srcX = d * smallest * xMult;
var srcY = d * smallest * yMult;
var srcW = smallest;
var srcH = smallest;
var dstX = 0;
var dstY = 0;
var dstW = smallest;
var dstH = smallest;
ctx.drawImage(element, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH);
gl.texSubImage3D(target, 0, 0, 0, d, smallest, smallest, 1, format, type, ctx.canvas);
}
ctx.canvas.width = 0;
ctx.canvas.height = 0;
// FIX (save state)
// gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
} else {
gl.texImage2D(target, 0, internalFormat, format, type, element);
}
restorePackState(gl, options);
if (options.auto !== false) {
setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type);
}
setTextureParameters(gl, tex, options);
}
function noop() {}
/**
* Loads an image
* @param {string} url url to image
* @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null
* if there was an error
* @return {HTMLImageElement} the image being loaded.
*/
function loadImage(url, crossOrigin, callback) {
callback = callback || noop;
var img = new Image();
crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults.crossOrigin;
if (crossOrigin !== undefined) {
img.crossOrigin = crossOrigin;
}
function clearEventHandlers() {
img.removeEventListener('error', onError); // eslint-disable-line
img.removeEventListener('load', onLoad); // eslint-disable-line
img = null;
}
function onError() {
var msg = "couldn't load image: " + url;
utils.error(msg);
callback(msg, img);
clearEventHandlers();
}
function onLoad() {
callback(null, img);
clearEventHandlers();
}
img.addEventListener('error', onError);
img.addEventListener('load', onLoad);
img.src = url;
return img;
}
/**
* Sets a texture to a 1x1 pixel color. If `options.color === false` is nothing happens. If it's not set
* the default texture color is used which can be set by calling `setDefaultTextureColor`.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @memberOf module:twgl/textures
*/
function setTextureTo1PixelColor(gl, tex, options) {
options = options || defaults.textureOptions;
var target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
if (options.color === false) {
return;
}
// Assume it's a URL
// Put 1x1 pixels in texture. That makes it renderable immediately regardless of filtering.
var color = make1Pixel(options.color);
if (target === gl.TEXTURE_CUBE_MAP) {
for (var ii = 0; ii < 6; ++ii) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, color);
}
} else if (target === gl.TEXTURE_3D || target === gl.TEXTURE_2D_ARRAY) {
gl.texImage3D(target, 0, gl.RGBA, 1, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, color);
} else {
gl.texImage2D(target, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, color);
}
}
/**
* The src image(s) used to create a texture.
*
* When you call {@link module:twgl.createTexture} or {@link module:twgl.createTextures}
* you can pass in urls for images to load into the textures. If it's a single url
* then this will be a single HTMLImageElement. If it's an array of urls used for a cubemap
* this will be a corresponding array of images for the cubemap.
*
* @typedef {HTMLImageElement|HTMLImageElement[]} TextureSrc
* @memberOf module:twgl
*/
/**
* A callback for when an image finished downloading and been uploaded into a texture
* @callback TextureReadyCallback
* @param {*} err If truthy there was an error.
* @param {WebGLTexture} texture the texture.
* @param {module:twgl.TextureSrc} souce image(s) used to as the src for the texture
* @memberOf module:twgl
*/
/**
* A callback for when all images have finished downloading and been uploaded into their respective textures
* @callback TexturesReadyCallback
* @param {*} err If truthy there was an error.
* @param {Object.<string, WebGLTexture>} textures the created textures by name. Same as returned by {@link module:twgl.createTextures}.
* @param {Object.<string, module:twgl.TextureSrc>} sources the image(s) used for the texture by name.
* @memberOf module:twgl
*/
/**
* A callback for when an image finished downloading and been uploaded into a texture
* @callback CubemapReadyCallback
* @param {*} err If truthy there was an error.
* @param {WebGLTexture} tex the texture.
* @param {HTMLImageElement[]} imgs the images for each face.
* @memberOf module:twgl
*/
/**
* A callback for when an image finished downloading and been uploaded into a texture
* @callback ThreeDReadyCallback
* @param {*} err If truthy there was an error.
* @param {WebGLTexture} tex the texture.
* @param {HTMLImageElement[]} imgs the images for each slice.
* @memberOf module:twgl
*/
/**
* Loads a texture from an image from a Url as specified in `options.src`
* If `options.color !== false` will set the texture to a 1x1 pixel color so that the texture is
* immediately useable. It will be updated with the contents of the image once the image has finished
* downloading. Filtering options will be set as approriate for image unless `options.auto === false`.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* @param {module:twgl.TextureReadyCallback} [callback] A function to be called when the image has finished loading. err will
* be non null if there was an error.
* @return {HTMLImageElement} the image being downloaded.
* @memberOf module:twgl/textures
*/
function loadTextureFromUrl(gl, tex, options, callback) {
callback = callback || noop;
options = options || defaults.textureOptions;
setTextureTo1PixelColor(gl, tex, options);
// Because it's async we need to copy the options.
options = utils.shallowCopy(options);
var img = loadImage(options.src, options.crossOrigin, function (err, img) {
if (err) {
callback(err, tex, img);
} else {
setTextureFromElement(gl, tex, img, options);
callback(null, tex, img);
}
});
return img;
}
/**
* Loads a cubemap from 6 urls as specified in `options.src`. Will set the cubemap to a 1x1 pixel color
* so that it is usable immediately unless `option.color === false`.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @param {module:twgl.CubemapReadyCallback} [callback] A function to be called when all the images have finished loading. err will
* be non null if there was an error.
* @memberOf module:twgl/textures
*/
function loadCubemapFromUrls(gl, tex, options, callback) {
callback = callback || noop;
var urls = options.src;
if (urls.length !== 6) {
throw "there must be 6 urls for a cubemap";
}
var internalFormat = options.internalFormat || options.format || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var format = options.format || formatType.format;
var type = options.type || gl.UNSIGNED_BYTE;
var target = options.target || gl.TEXTURE_2D;
if (target !== gl.TEXTURE_CUBE_MAP) {
throw "target must be TEXTURE_CUBE_MAP";
}
setTextureTo1PixelColor(gl, tex, options);
// Because it's async we need to copy the options.
options = utils.shallowCopy(options);
var numToLoad = 6;
var errors = [];
var imgs;
var faces = getCubeFaceOrder(gl, options);
function uploadImg(faceTarget) {
return function (err, img) {
--numToLoad;
if (err) {
errors.push(err);
} else {
if (img.width !== img.height) {
errors.push("cubemap face img is not a square: " + img.src);
} else {
savePackState(gl, options);
gl.bindTexture(target, tex);
// So assuming this is the first image we now have one face that's img sized
// and 5 faces that are 1x1 pixel so size the other faces
if (numToLoad === 5) {
// use the default order
getCubeFaceOrder(gl).forEach(function (otherTarget) {
// Should we re-use the same face or a color?
gl.texImage2D(otherTarget, 0, internalFormat, format, type, img);
});
} else {
gl.texImage2D(faceTarget, 0, internalFormat, format, type, img);
}
restorePackState(gl, options);
gl.generateMipmap(target);
}
}
if (numToLoad === 0) {
callback(errors.length ? errors : undefined, imgs, tex);
}
};
}
imgs = urls.map(function (url, ndx) {
return loadImage(url, options.crossOrigin, uploadImg(faces[ndx]));
});
}
/**
* Loads a 2d array or 3d texture from urls as specified in `options.src`.
* Will set the texture to a 1x1 pixel color
* so that it is usable immediately unless `option.color === false`.
*
* If the width and height is not specified the width and height of the first
* image loaded will be used. Note that since images are loaded async
* which image downloads first is unknown.
*
* If an image is not the same size as the width and height it will be scaled
* to that width and height.
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @param {module:twgl.ThreeDReadyCallback} [callback] A function to be called when all the images have finished loading. err will
* be non null if there was an error.
* @memberOf module:twgl/textures
*/
function loadSlicesFromUrls(gl, tex, options, callback) {
callback = callback || noop;
var urls = options.src;
var internalFormat = options.internalFormat || options.format || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var format = options.format || formatType.format;
var type = options.type || gl.UNSIGNED_BYTE;
var target = options.target || gl.TEXTURE_2D_ARRAY;
if (target !== gl.TEXTURE_3D && target !== gl.TEXTURE_2D_ARRAY) {
throw "target must be TEXTURE_3D or TEXTURE_2D_ARRAY";
}
setTextureTo1PixelColor(gl, tex, options);
// Because it's async we need to copy the options.
options = utils.shallowCopy(options);
var numToLoad = urls.length;
var errors = [];
var imgs;
var width = options.width;
var height = options.height;
var depth = urls.length;
var firstImage = true;
function uploadImg(slice) {
return function (err, img) {
--numToLoad;
if (err) {
errors.push(err);
} else {
savePackState(gl, options);
gl.bindTexture(target, tex);
if (firstImage) {
firstImage = false;
width = options.width || img.width;
height = options.height || img.height;
gl.texImage3D(target, 0, internalFormat, width, height, depth, 0, format, type, null);
// put it in every slice otherwise some slices will be 0,0,0,0
for (var s = 0; s < depth; ++s) {
gl.texSubImage3D(target, 0, 0, 0, s, width, height, 1, format, type, img);
}
} else {
var src = img;
if (img.width !== width || img.height !== height) {
// Size the image to fix
src = ctx.canvas;
ctx.canvas.width = width;
ctx.canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
}
gl.texSubImage3D(target, 0, 0, 0, slice, width, height, 1, format, type, src);
// free the canvas memory
if (src === ctx.canvas) {
ctx.canvas.width = 0;
ctx.canvas.height = 0;
}
}
restorePackState(gl, options);
gl.generateMipmap(target);
}
if (numToLoad === 0) {
callback(errors.length ? errors : undefined, imgs, tex);
}
};
}
imgs = urls.map(function (url, ndx) {
return loadImage(url, options.crossOrigin, uploadImg(ndx));
});
}
/**
* Sets a texture from an array or typed array. If the width or height is not provided will attempt to
* guess the size. See {@link module:twgl.TextureOptions}.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {(number[]|ArrayBuffer)} src An array or typed arry with texture data.
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @memberOf module:twgl/textures
*/
function setTextureFromArray(gl, tex, src, options) {
options = options || defaults.textureOptions;
var target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
var width = options.width;
var height = options.height;
var depth = options.depth;
var internalFormat = options.internalFormat || options.format || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var format = options.format || formatType.format;
var type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);
if (!isArrayBuffer(src)) {
var Type = typedArrays.getTypedArrayTypeForGLType(type);
src = new Type(src);
} else {
if (src instanceof Uint8ClampedArray) {
src = new Uint8Array(src.buffer);
}
}
var bytesPerElement = getBytesPerElementForInternalFormat(internalFormat, type);
var numElements = src.byteLength / bytesPerElement; // TODO: check UNPACK_ALIGNMENT?
if (numElements % 1) {
throw "length wrong size for format: " + glEnumToString(gl, format);
}
var dimensions;
if (target === gl.TEXTURE_3D) {
if (!width && !height && !depth) {
var size = Math.cbrt(numElements);
if (size % 1 !== 0) {
throw "can't guess cube size of array of numElements: " + numElements;
}
width = size;
height = size;
depth = size;
} else if (width && (!height || !depth)) {
dimensions = guessDimensions(gl, target, height, depth, numElements / width);
height = dimensions.width;
depth = dimensions.height;
} else if (height && (!width || !depth)) {
dimensions = guessDimensions(gl, target, width, depth, numElements / height);
width = dimensions.width;
depth = dimensions.height;
} else {
dimensions = guessDimensions(gl, target, width, height, numElements / depth);
width = dimensions.width;
height = dimensions.height;
}
} else {
dimensions = guessDimensions(gl, target, width, height, numElements);
width = dimensions.width;
height = dimensions.height;
}
gl.pixelStorei(gl.UNPACK_ALIGNMENT, options.unpackAlignment || 1);
savePackState(gl, options);
if (target === gl.TEXTURE_CUBE_MAP) {
(function () {
var elementsPerElement = bytesPerElement / src.BYTES_PER_ELEMENT;
var faceSize = numElements / 6 * elementsPerElement;
getCubeFacesWithNdx(gl, options).forEach(function (f) {
var offset = faceSize * f.ndx;
var data = src.subarray(offset, offset + faceSize);
gl.texImage2D(f.face, 0, internalFormat, width, height, 0, format, type, data);
});
})();
} else if (target === gl.TEXTURE_3D) {
gl.texImage3D(target, 0, internalFormat, width, height, depth, 0, format, type, src);
} else {
gl.texImage2D(target, 0, internalFormat, width, height, 0, format, type, src);
}
restorePackState(gl, options);
return {
width: width,
height: height,
depth: depth,
type: type
};
}
/**
* Sets a texture with no contents of a certain size. In other words calls `gl.texImage2D` with `null`.
* You must set `options.width` and `options.height`.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @memberOf module:twgl/textures
*/
function setEmptyTexture(gl, tex, options) {
var target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
var internalFormat = options.internalFormat || options.format || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var format = options.format || formatType.format;
var type = options.type || formatType.type;
savePackState(gl, options);
if (target === gl.TEXTURE_CUBE_MAP) {
for (var ii = 0; ii < 6; ++ii) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, 0, internalFormat, options.width, options.height, 0, format, type, null);
}
} else if (target === gl.TEXTURE_3D) {
gl.texImage3D(target, 0, internalFormat, options.width, options.height, options.depth, 0, format, type, null);
} else {
gl.texImage2D(target, 0, internalFormat, options.width, options.height, 0, format, type, null);
}
restorePackState(gl, options);
}
/**
* Creates a texture based on the options passed in.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* @param {module:twgl.TextureReadyCallback} [callback] A callback called when an image has been downloaded and uploaded to the texture.
* @return {WebGLTexture} the created texture.
* @memberOf module:twgl/textures
*/
function createTexture(gl, options, callback) {
callback = callback || noop;
options = options || defaults.textureOptions;
var tex = gl.createTexture();
var target = options.target || gl.TEXTURE_2D;
var width = options.width || 1;
var height = options.height || 1;
var internalFormat = options.internalFormat || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var type = options.type || formatType.type;
gl.bindTexture(target, tex);
if (target === gl.TEXTURE_CUBE_MAP) {
// this should have been the default for CUBEMAPS :(
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
var src = options.src;
if (src) {
if (typeof src === "function") {
src = src(gl, options);
}
if (typeof src === "string") {
loadTextureFromUrl(gl, tex, options, callback);
} else if (isArrayBuffer(src) || Array.isArray(src) && (typeof src[0] === 'number' || Array.isArray(src[0]) || isArrayBuffer(src[0]))) {
var dimensions = setTextureFromArray(gl, tex, src, options);
width = dimensions.width;
height = dimensions.height;
type = dimensions.type;
} else if (Array.isArray(src) && typeof src[0] === 'string') {
if (target === gl.TEXTURE_CUBE_MAP) {
loadCubemapFromUrls(gl, tex, options, callback);
} else {
loadSlicesFromUrls(gl, tex, options, callback);
}
} else if (src instanceof HTMLElement) {
setTextureFromElement(gl, tex, src, options);
width = src.width;
height = src.height;
} else {
throw "unsupported src type";
}
} else {
setEmptyTexture(gl, tex, options);
}
if (options.auto !== false) {
setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type);
}
setTextureParameters(gl, tex, options);
return tex;
}
/**
* Resizes a texture based on the options passed in.
*
* Note: This is not a generic resize anything function.
* It's mostly used by {@link module:twgl.resizeFramebufferInfo}
* It will use `options.src` if it exists to try to determine a `type`
* otherwise it will assume `gl.UNSIGNED_BYTE`. No data is provided
* for the texture. Texture parameters will be set accordingly
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the texture to resize
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @param {number} [width] the new width. If not passed in will use `options.width`
* @param {number} [height] the new height. If not passed in will use `options.height`
* @memberOf module:twgl/textures
*/
function resizeTexture(gl, tex, options, width, height) {
width = width || options.width;
height = height || options.height;
var target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
var internalFormat = options.internalFormat || options.format || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var format = options.format || formatType.format;
var type;
var src = options.src;
if (!src) {
type = options.type || formatType.type;
} else if (isArrayBuffer(src) || Array.isArray(src) && typeof src[0] === 'number') {
type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);
} else {
type = options.type || formatType.type;
}
if (target === gl.TEXTURE_CUBE_MAP) {
for (var ii = 0; ii < 6; ++ii) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, 0, format, width, height, 0, format, type, null);
}
} else {
gl.texImage2D(target, 0, format, width, height, 0, format, type, null);
}
}
/**
* Check if a src is an async request.
* if src is a string we're going to download an image
* if src is an array of strings we're going to download cubemap images
* @param {*} src The src from a TextureOptions
* @returns {bool} true if src is async.
*/
function isAsyncSrc(src) {
return typeof src === 'string' || Array.isArray(src) && typeof src[0] === 'string';
}
/**
* Creates a bunch of textures based on the passed in options.
*
* Example:
*
* var textures = twgl.createTextures(gl, {
* // a power of 2 image
* hftIcon: { src: "images/hft-icon-16.png", mag: gl.NEAREST },
* // a non-power of 2 image
* clover: { src: "images/clover.jpg" },
* // From a canvas
* fromCanvas: { src: ctx.canvas },
* // A cubemap from 6 images
* yokohama: {
* target: gl.TEXTURE_CUBE_MAP,
* src: [
* 'images/yokohama/posx.jpg',
* 'images/yokohama/negx.jpg',
* 'images/yokohama/posy.jpg',
* 'images/yokohama/negy.jpg',
* 'images/yokohama/posz.jpg',
* 'images/yokohama/negz.jpg',
* ],
* },
* // A cubemap from 1 image (can be 1x6, 2x3, 3x2, 6x1)
* goldengate: {
* target: gl.TEXTURE_CUBE_MAP,
* src: 'images/goldengate.jpg',
* },
* // A 2x2 pixel texture from a JavaScript array
* checker: {
* mag: gl.NEAREST,
* min: gl.LINEAR,
* src: [
* 255,255,255,255,
* 192,192,192,255,
* 192,192,192,255,
* 255,255,255,255,
* ],
* },
* // a 1x2 pixel texture from a typed array.
* stripe: {
* mag: gl.NEAREST,
* min: gl.LINEAR,
* format: gl.LUMINANCE,
* src: new Uint8Array([
* 255,
* 128,
* 255,
* 128,
* 255,
* 128,
* 255,
* 128,
* ]),
* width: 1,
* },
* });
*
* Now
*
* * `textures.hftIcon` will be a 2d texture
* * `textures.clover` will be a 2d texture
* * `textures.fromCanvas` will be a 2d texture
* * `textures.yohohama` will be a cubemap texture
* * `textures.goldengate` will be a cubemap texture
* * `textures.checker` will be a 2d texture
* * `textures.stripe` will be a 2d texture
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {Object.<string,module:twgl.TextureOptions>} options A object of TextureOptions one per texture.
* @param {module:twgl.TexturesReadyCallback} [callback] A callback called when all textures have been downloaded.
* @return {Object.<string,WebGLTexture>} the created textures by name
* @memberOf module:twgl/textures
*/
function createTextures(gl, textureOptions, callback) {
callback = callback || noop;
var numDownloading = 0;
var errors = [];
var textures = {};
var images = {};
function callCallbackIfReady() {
if (numDownloading === 0) {
setTimeout(function () {
callback(errors.length ? errors : undefined, textures, images);
}, 0);
}
}
Object.keys(textureOptions).forEach(function (name) {
var options = textureOptions[name];
var onLoadFn;
if (isAsyncSrc(options.src)) {
onLoadFn = function onLoadFn(err, tex, img) {
images[name] = img;
--numDownloading;
if (err) {
errors.push(err);
}
callCallbackIfReady();
};
++numDownloading;
}
textures[name] = createTexture(gl, options, onLoadFn);
});
// queue the callback if there are no images to download.
// We do this because if your code is structured to wait for
// images to download but then you comment out all the async
// images your code would break.
callCallbackIfReady();
return textures;
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"setDefaults_": setDefaults,
"createSampler": createSampler,
"createSamplers": createSamplers,
"setSamplerParameters": setSamplerParameters,
"createTexture": createTexture,
"setEmptyTexture": setEmptyTexture,
"setTextureFromArray": setTextureFromArray,
"loadTextureFromUrl": loadTextureFromUrl,
"setTextureFromElement": setTextureFromElement,
"setTextureFilteringForSize": setTextureFilteringForSize,
"setTextureParameters": setTextureParameters,
"setDefaultTextureColor": setDefaultTextureColor,
"createTextures": createTextures,
"resizeTexture": resizeTexture,
"getNumComponentsForFormat": getNumComponentsForFormat,
"getBytesPerElementForInternalFormat": getBytesPerElementForInternalFormat
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (programs) {
"use strict";
/**
* vertex array object related functions
*
* You should generally not need to use these functions. They are provided
* for those cases where you're doing something out of the ordinary
* and you need lower level access.
*
* For backward compatibily they are available at both `twgl.attributes` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/vertexArrays
*/
/**
* @typedef {Object} VertexArrayInfo
* @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.
* @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..
* @property {WebGLVertexArrayObject} [vertexArrayObject] a vertex array object
* @memberOf module:twgl
*/
/**
* Creates a VertexArrayInfo from a BufferInfo and one or more ProgramInfos
*
* This can be passed to {@link module:twgl.setBuffersAndAttributes} and to
* {@link module:twgl:drawBufferInfo}.
*
* > **IMPORTANT:** Vertex Array Objects are **not** a direct analog for a BufferInfo. Vertex Array Objects
* assign buffers to specific attributes at creation time. That means they can only be used with programs
* who's attributes use the same attribute locations for the same purposes.
*
* > Bind your attribute locations by passing an array of attribute names to {@link module:twgl.createProgramInfo}
* or use WebGL 2's GLSL ES 3's `layout(location = <num>)` to make sure locations match.
*
* also
*
* > **IMPORTANT:** After calling twgl.setBuffersAndAttribute with a BufferInfo that uses a Vertex Array Object
* that Vertex Array Object will be bound. That means **ANY MANIPULATION OF ELEMENT_ARRAY_BUFFER or ATTRIBUTES**
* will affect the Vertex Array Object state.
*
* > Call `gl.bindVertexArray(null)` to get back manipulating the global attributes and ELEMENT_ARRAY_BUFFER.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {module:twgl.ProgramInfo|module:twgl.ProgramInfo[]} programInfo a programInfo or array of programInfos
* @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...
*
* You need to make sure every attribute that will be used is bound. So for example assume shader 1
* uses attributes A, B, C and shader 2 uses attributes A, B, D. If you only pass in the programInfo
* for shader 1 then only attributes A, B, and C will have their attributes set because TWGL doesn't
* now attribute D's location.
*
* So, you can pass in both shader 1 and shader 2's programInfo
*
* @return {module:twgl.VertexArrayInfo} The created VertexArrayInfo
*
* @memberOf module:twgl/vertexArrays
*/
function createVertexArrayInfo(gl, programInfos, bufferInfo) {
var vao = gl.createVertexArray();
gl.bindVertexArray(vao);
if (!programInfos.length) {
programInfos = [programInfos];
}
programInfos.forEach(function (programInfo) {
programs.setBuffersAndAttributes(gl, programInfo, bufferInfo);
});
gl.bindVertexArray(null);
return {
numElements: bufferInfo.numElements,
elementType: bufferInfo.elementType,
vertexArrayObject: vao
};
}
/**
* Creates a vertex array object and then sets the attributes on it
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
* @param {Object.<string, function>} setters Attribute setters as returned from createAttributeSetters
* @param {Object.<string, module:twgl.AttribInfo>} attribs AttribInfos mapped by attribute name.
* @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices
* @memberOf module:twgl/vertexArrays
*/
function createVAOAndSetAttributes(gl, setters, attribs, indices) {
var vao = gl.createVertexArray();
gl.bindVertexArray(vao);
programs.setAttributes(setters, attribs);
if (indices) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices);
}
// We unbind this because otherwise any change to ELEMENT_ARRAY_BUFFER
// like when creating buffers for other stuff will mess up this VAO's binding
gl.bindVertexArray(null);
return vao;
}
/**
* Creates a vertex array object and then sets the attributes
* on it
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {Object.<string, function>| module:twgl.ProgramInfo} programInfo as returned from createProgramInfo or Attribute setters as returned from createAttributeSetters
* @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...
* @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices
* @memberOf module:twgl/vertexArrays
*/
function createVAOFromBufferInfo(gl, programInfo, bufferInfo) {
return createVAOAndSetAttributes(gl, programInfo.attribSetters || programInfo, bufferInfo.attribs, bufferInfo.indices);
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"createVertexArrayInfo": createVertexArrayInfo,
"createVAOAndSetAttributes": createVAOAndSetAttributes,
"createVAOFromBufferInfo": createVAOFromBufferInfo
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(11)], __WEBPACK_AMD_DEFINE_RESULT__ = function (v3) {
"use strict";
/**
* 4x4 Matrix math math functions.
*
* Almost all functions take an optional `dst` argument. If it is not passed in the
* functions will create a new matrix. In other words you can do this
*
* var mat = m4.translation([1, 2, 3]); // Creates a new translation matrix
*
* or
*
* var mat = m4.create();
* m4.translation([1, 2, 3], mat); // Puts translation matrix in mat.
*
* The first style is often easier but depending on where it's used it generates garbage where
* as there is almost never allocation with the second style.
*
* It is always save to pass any matrix as the destination. So for example
*
* var mat = m4.identity();
* var trans = m4.translation([1, 2, 3]);
* m4.multiply(mat, trans, mat); // Multiplies mat * trans and puts result in mat.
*
* @module twgl/m4
*/
var MatType = Float32Array;
var tempV3a = v3.create();
var tempV3b = v3.create();
var tempV3c = v3.create();
/**
* A JavaScript array with 16 values or a Float32Array with 16 values.
* When created by the library will create the default type which is `Float32Array`
* but can be set by calling {@link module:twgl/m4.setDefaultType}.
* @typedef {(number[]|Float32Array)} Mat4
* @memberOf module:twgl/m4
*/
/**
* Sets the type this library creates for a Mat4
* @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`
* @return {constructor} previous constructor for Mat4
*/
function setDefaultType(ctor) {
var oldType = MatType;
MatType = ctor;
return oldType;
}
/**
* Negates a matrix.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} -m.
* @memberOf module:twgl/m4
*/
function negate(m, dst) {
dst = dst || new MatType(16);
dst[0] = -m[0];
dst[1] = -m[1];
dst[2] = -m[2];
dst[3] = -m[3];
dst[4] = -m[4];
dst[5] = -m[5];
dst[6] = -m[6];
dst[7] = -m[7];
dst[8] = -m[8];
dst[9] = -m[9];
dst[10] = -m[10];
dst[11] = -m[11];
dst[12] = -m[12];
dst[13] = -m[13];
dst[14] = -m[14];
dst[15] = -m[15];
return dst;
}
/**
* Copies a matrix.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {module:twgl/m4.Mat4} [dst] The matrix.
* @return {module:twgl/m4.Mat4} A copy of m.
* @memberOf module:twgl/m4
*/
function copy(m, dst) {
dst = dst || new MatType(16);
dst[0] = m[0];
dst[1] = m[1];
dst[2] = m[2];
dst[3] = m[3];
dst[4] = m[4];
dst[5] = m[5];
dst[6] = m[6];
dst[7] = m[7];
dst[8] = m[8];
dst[9] = m[9];
dst[10] = m[10];
dst[11] = m[11];
dst[12] = m[12];
dst[13] = m[13];
dst[14] = m[14];
dst[15] = m[15];
return dst;
}
/**
* Creates an n-by-n identity matrix.
*
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} An n-by-n identity matrix.
* @memberOf module:twgl/m4
*/
function identity(dst) {
dst = dst || new MatType(16);
dst[0] = 1;
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = 1;
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = 1;
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1;
return dst;
}
/**
* Takes the transpose of a matrix.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The transpose of m.
* @memberOf module:twgl/m4
*/
function transpose(m, dst) {
dst = dst || new MatType(16);
if (dst === m) {
var t;
t = m[1];
m[1] = m[4];
m[4] = t;
t = m[2];
m[2] = m[8];
m[8] = t;
t = m[3];
m[3] = m[12];
m[12] = t;
t = m[6];
m[6] = m[9];
m[9] = t;
t = m[7];
m[7] = m[13];
m[13] = t;
t = m[11];
m[11] = m[14];
m[14] = t;
return dst;
}
var m00 = m[0 * 4 + 0];
var m01 = m[0 * 4 + 1];
var m02 = m[0 * 4 + 2];
var m03 = m[0 * 4 + 3];
var m10 = m[1 * 4 + 0];
var m11 = m[1 * 4 + 1];
var m12 = m[1 * 4 + 2];
var m13 = m[1 * 4 + 3];
var m20 = m[2 * 4 + 0];
var m21 = m[2 * 4 + 1];
var m22 = m[2 * 4 + 2];
var m23 = m[2 * 4 + 3];
var m30 = m[3 * 4 + 0];
var m31 = m[3 * 4 + 1];
var m32 = m[3 * 4 + 2];
var m33 = m[3 * 4 + 3];
dst[0] = m00;
dst[1] = m10;
dst[2] = m20;
dst[3] = m30;
dst[4] = m01;
dst[5] = m11;
dst[6] = m21;
dst[7] = m31;
dst[8] = m02;
dst[9] = m12;
dst[10] = m22;
dst[11] = m32;
dst[12] = m03;
dst[13] = m13;
dst[14] = m23;
dst[15] = m33;
return dst;
}
/**
* Computes the inverse of a 4-by-4 matrix.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The inverse of m.
* @memberOf module:twgl/m4
*/
function inverse(m, dst) {
dst = dst || new MatType(16);
var m00 = m[0 * 4 + 0];
var m01 = m[0 * 4 + 1];
var m02 = m[0 * 4 + 2];
var m03 = m[0 * 4 + 3];
var m10 = m[1 * 4 + 0];
var m11 = m[1 * 4 + 1];
var m12 = m[1 * 4 + 2];
var m13 = m[1 * 4 + 3];
var m20 = m[2 * 4 + 0];
var m21 = m[2 * 4 + 1];
var m22 = m[2 * 4 + 2];
var m23 = m[2 * 4 + 3];
var m30 = m[3 * 4 + 0];
var m31 = m[3 * 4 + 1];
var m32 = m[3 * 4 + 2];
var m33 = m[3 * 4 + 3];
var tmp_0 = m22 * m33;
var tmp_1 = m32 * m23;
var tmp_2 = m12 * m33;
var tmp_3 = m32 * m13;
var tmp_4 = m12 * m23;
var tmp_5 = m22 * m13;
var tmp_6 = m02 * m33;
var tmp_7 = m32 * m03;
var tmp_8 = m02 * m23;
var tmp_9 = m22 * m03;
var tmp_10 = m02 * m13;
var tmp_11 = m12 * m03;
var tmp_12 = m20 * m31;
var tmp_13 = m30 * m21;
var tmp_14 = m10 * m31;
var tmp_15 = m30 * m11;
var tmp_16 = m10 * m21;
var tmp_17 = m20 * m11;
var tmp_18 = m00 * m31;
var tmp_19 = m30 * m01;
var tmp_20 = m00 * m21;
var tmp_21 = m20 * m01;
var tmp_22 = m00 * m11;
var tmp_23 = m10 * m01;
var t0 = tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31 - (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);
var t1 = tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31 - (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);
var t2 = tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31 - (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);
var t3 = tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21 - (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);
var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);
dst[0] = d * t0;
dst[1] = d * t1;
dst[2] = d * t2;
dst[3] = d * t3;
dst[4] = d * (tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30 - (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30));
dst[5] = d * (tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30 - (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30));
dst[6] = d * (tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30 - (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30));
dst[7] = d * (tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20 - (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20));
dst[8] = d * (tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33 - (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33));
dst[9] = d * (tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33 - (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33));
dst[10] = d * (tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33 - (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33));
dst[11] = d * (tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23 - (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23));
dst[12] = d * (tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12 - (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22));
dst[13] = d * (tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22 - (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02));
dst[14] = d * (tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02 - (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12));
dst[15] = d * (tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12 - (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02));
return dst;
}
/**
* Multiplies two 4-by-4 matrices with a on the left and b on the right
* @param {module:twgl/m4.Mat4} a The matrix on the left.
* @param {module:twgl/m4.Mat4} b The matrix on the right.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The matrix product of a and b.
* @memberOf module:twgl/m4
*/
function multiply(a, b, dst) {
dst = dst || new MatType(16);
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4 + 0];
var a11 = a[4 + 1];
var a12 = a[4 + 2];
var a13 = a[4 + 3];
var a20 = a[8 + 0];
var a21 = a[8 + 1];
var a22 = a[8 + 2];
var a23 = a[8 + 3];
var a30 = a[12 + 0];
var a31 = a[12 + 1];
var a32 = a[12 + 2];
var a33 = a[12 + 3];
var b00 = b[0];
var b01 = b[1];
var b02 = b[2];
var b03 = b[3];
var b10 = b[4 + 0];
var b11 = b[4 + 1];
var b12 = b[4 + 2];
var b13 = b[4 + 3];
var b20 = b[8 + 0];
var b21 = b[8 + 1];
var b22 = b[8 + 2];
var b23 = b[8 + 3];
var b30 = b[12 + 0];
var b31 = b[12 + 1];
var b32 = b[12 + 2];
var b33 = b[12 + 3];
dst[0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03;
dst[1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03;
dst[2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03;
dst[3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03;
dst[4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13;
dst[5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13;
dst[6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13;
dst[7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13;
dst[8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23;
dst[9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23;
dst[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23;
dst[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23;
dst[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33;
dst[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33;
dst[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33;
dst[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33;
return dst;
}
/**
* Sets the translation component of a 4-by-4 matrix to the given
* vector.
* @param {module:twgl/m4.Mat4} a The matrix.
* @param {Vec3} v The vector.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} a once modified.
* @memberOf module:twgl/m4
*/
function setTranslation(a, v, dst) {
dst = dst || identity();
if (a !== dst) {
dst[0] = a[0];
dst[1] = a[1];
dst[2] = a[2];
dst[3] = a[3];
dst[4] = a[4];
dst[5] = a[5];
dst[6] = a[6];
dst[7] = a[7];
dst[8] = a[8];
dst[9] = a[9];
dst[10] = a[10];
dst[11] = a[11];
}
dst[12] = v[0];
dst[13] = v[1];
dst[14] = v[2];
dst[15] = 1;
return dst;
}
/**
* Returns the translation component of a 4-by-4 matrix as a vector with 3
* entries.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {Vec3} [dst] vector..
* @return {Vec3} The translation component of m.
* @memberOf module:twgl/m4
*/
function getTranslation(m, dst) {
dst = dst || v3.create();
dst[0] = m[12];
dst[1] = m[13];
dst[2] = m[14];
return dst;
}
/**
* Returns an axis of a 4x4 matrix as a vector with 3 entries
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {number} axis The axis 0 = x, 1 = y, 2 = z;
* @return {Vec3} [dst] vector.
* @return {Vec3} The axis component of m.
* @memberOf module:twgl/m4
*/
function getAxis(m, axis, dst) {
dst = dst || v3.create();
var off = axis * 4;
dst[0] = m[off + 0];
dst[1] = m[off + 1];
dst[2] = m[off + 2];
return dst;
}
/**
* Sets an axis of a 4x4 matrix as a vector with 3 entries
* @param {Vec3} v the axis vector
* @param {number} axis The axis 0 = x, 1 = y, 2 = z;
* @param {module:twgl/m4.Mat4} [dst] The matrix to set. If none a new one is created
* @return {module:twgl/m4.Mat4} dst
* @memberOf module:twgl/m4
*/
function setAxis(a, v, axis, dst) {
if (dst !== a) {
dst = copy(a, dst);
}
var off = axis * 4;
dst[off + 0] = v[0];
dst[off + 1] = v[1];
dst[off + 2] = v[2];
return dst;
}
/**
* Computes a 4-by-4 perspective transformation matrix given the angular height
* of the frustum, the aspect ratio, and the near and far clipping planes. The
* arguments define a frustum extending in the negative z direction. The given
* angle is the vertical angle of the frustum, and the horizontal angle is
* determined to produce the given aspect ratio. The arguments near and far are
* the distances to the near and far clipping planes. Note that near and far
* are not z coordinates, but rather they are distances along the negative
* z-axis. The matrix generated sends the viewing frustum to the unit box.
* We assume a unit box extending from -1 to 1 in the x and y dimensions and
* from 0 to 1 in the z dimension.
* @param {number} fieldOfViewYInRadians The camera angle from top to bottom (in radians).
* @param {number} aspect The aspect ratio width / height.
* @param {number} zNear The depth (negative z coordinate)
* of the near clipping plane.
* @param {number} zFar The depth (negative z coordinate)
* of the far clipping plane.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The perspective matrix.
* @memberOf module:twgl/m4
*/
function perspective(fieldOfViewYInRadians, aspect, zNear, zFar, dst) {
dst = dst || new MatType(16);
var f = Math.tan(Math.PI * 0.5 - 0.5 * fieldOfViewYInRadians);
var rangeInv = 1.0 / (zNear - zFar);
dst[0] = f / aspect;
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = f;
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = (zNear + zFar) * rangeInv;
dst[11] = -1;
dst[12] = 0;
dst[13] = 0;
dst[14] = zNear * zFar * rangeInv * 2;
dst[15] = 0;
return dst;
}
/**
* Computes a 4-by-4 othogonal transformation matrix given the left, right,
* bottom, and top dimensions of the near clipping plane as well as the
* near and far clipping plane distances.
* @param {number} left Left side of the near clipping plane viewport.
* @param {number} right Right side of the near clipping plane viewport.
* @param {number} top Top of the near clipping plane viewport.
* @param {number} bottom Bottom of the near clipping plane viewport.
* @param {number} near The depth (negative z coordinate)
* of the near clipping plane.
* @param {number} far The depth (negative z coordinate)
* of the far clipping plane.
* @param {module:twgl/m4.Mat4} [dst] Output matrix.
* @return {module:twgl/m4.Mat4} The perspective matrix.
* @memberOf module:twgl/m4
*/
function ortho(left, right, bottom, top, near, far, dst) {
dst = dst || new MatType(16);
dst[0] = 2 / (right - left);
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = 2 / (top - bottom);
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = -1 / (far - near);
dst[11] = 0;
dst[12] = (right + left) / (left - right);
dst[13] = (top + bottom) / (bottom - top);
dst[14] = -near / (near - far);
dst[15] = 1;
return dst;
}
/**
* Computes a 4-by-4 perspective transformation matrix given the left, right,
* top, bottom, near and far clipping planes. The arguments define a frustum
* extending in the negative z direction. The arguments near and far are the
* distances to the near and far clipping planes. Note that near and far are not
* z coordinates, but rather they are distances along the negative z-axis. The
* matrix generated sends the viewing frustum to the unit box. We assume a unit
* box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z
* dimension.
* @param {number} left The x coordinate of the left plane of the box.
* @param {number} right The x coordinate of the right plane of the box.
* @param {number} bottom The y coordinate of the bottom plane of the box.
* @param {number} top The y coordinate of the right plane of the box.
* @param {number} near The negative z coordinate of the near plane of the box.
* @param {number} far The negative z coordinate of the far plane of the box.
* @param {module:twgl/m4.Mat4} [dst] Output matrix.
* @return {module:twgl/m4.Mat4} The perspective projection matrix.
* @memberOf module:twgl/m4
*/
function frustum(left, right, bottom, top, near, far, dst) {
dst = dst || new MatType(16);
var dx = right - left;
var dy = top - bottom;
var dz = near - far;
dst[0] = 2 * near / dx;
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = 2 * near / dy;
dst[6] = 0;
dst[7] = 0;
dst[8] = (left + right) / dx;
dst[9] = (top + bottom) / dy;
dst[10] = far / dz;
dst[11] = -1;
dst[12] = 0;
dst[13] = 0;
dst[14] = near * far / dz;
dst[15] = 0;
return dst;
}
/**
* Computes a 4-by-4 look-at transformation.
*
* This is a matrix which positions the camera itself. If you want
* a view matrix (a matrix which moves things in front of the camera)
* take the inverse of this.
*
* @param {Vec3} eye The position of the eye.
* @param {Vec3} target The position meant to be viewed.
* @param {Vec3} up A vector pointing up.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The look-at matrix.
* @memberOf module:twgl/m4
*/
function lookAt(eye, target, up, dst) {
dst = dst || new MatType(16);
var xAxis = tempV3a;
var yAxis = tempV3b;
var zAxis = tempV3c;
v3.normalize(v3.subtract(eye, target, zAxis), zAxis);
v3.normalize(v3.cross(up, zAxis, xAxis), xAxis);
v3.normalize(v3.cross(zAxis, xAxis, yAxis), yAxis);
dst[0] = xAxis[0];
dst[1] = xAxis[1];
dst[2] = xAxis[2];
dst[3] = 0;
dst[4] = yAxis[0];
dst[5] = yAxis[1];
dst[6] = yAxis[2];
dst[7] = 0;
dst[8] = zAxis[0];
dst[9] = zAxis[1];
dst[10] = zAxis[2];
dst[11] = 0;
dst[12] = eye[0];
dst[13] = eye[1];
dst[14] = eye[2];
dst[15] = 1;
return dst;
}
/**
* Creates a 4-by-4 matrix which translates by the given vector v.
* @param {Vec3} v The vector by
* which to translate.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The translation matrix.
* @memberOf module:twgl/m4
*/
function translation(v, dst) {
dst = dst || new MatType(16);
dst[0] = 1;
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = 1;
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = 1;
dst[11] = 0;
dst[12] = v[0];
dst[13] = v[1];
dst[14] = v[2];
dst[15] = 1;
return dst;
}
/**
* Modifies the given 4-by-4 matrix by translation by the given vector v.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {Vec3} v The vector by
* which to translate.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} m once modified.
* @memberOf module:twgl/m4
*/
function translate(m, v, dst) {
dst = dst || new MatType(16);
var v0 = v[0];
var v1 = v[1];
var v2 = v[2];
var m00 = m[0];
var m01 = m[1];
var m02 = m[2];
var m03 = m[3];
var m10 = m[1 * 4 + 0];
var m11 = m[1 * 4 + 1];
var m12 = m[1 * 4 + 2];
var m13 = m[1 * 4 + 3];
var m20 = m[2 * 4 + 0];
var m21 = m[2 * 4 + 1];
var m22 = m[2 * 4 + 2];
var m23 = m[2 * 4 + 3];
var m30 = m[3 * 4 + 0];
var m31 = m[3 * 4 + 1];
var m32 = m[3 * 4 + 2];
var m33 = m[3 * 4 + 3];
if (m !== dst) {
dst[0] = m00;
dst[1] = m01;
dst[2] = m02;
dst[3] = m03;
dst[4] = m10;
dst[5] = m11;
dst[6] = m12;
dst[7] = m13;
dst[8] = m20;
dst[9] = m21;
dst[10] = m22;
dst[11] = m23;
}
dst[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30;
dst[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31;
dst[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32;
dst[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33;
return dst;
}
/**
* Creates a 4-by-4 matrix which rotates around the x-axis by the given angle.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The rotation matrix.
* @memberOf module:twgl/m4
*/
function rotationX(angleInRadians, dst) {
dst = dst || new MatType(16);
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
dst[0] = 1;
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = c;
dst[6] = s;
dst[7] = 0;
dst[8] = 0;
dst[9] = -s;
dst[10] = c;
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1;
return dst;
}
/**
* Modifies the given 4-by-4 matrix by a rotation around the x-axis by the given
* angle.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} m once modified.
* @memberOf module:twgl/m4
*/
function rotateX(m, angleInRadians, dst) {
dst = dst || new MatType(16);
var m10 = m[4];
var m11 = m[5];
var m12 = m[6];
var m13 = m[7];
var m20 = m[8];
var m21 = m[9];
var m22 = m[10];
var m23 = m[11];
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
dst[4] = c * m10 + s * m20;
dst[5] = c * m11 + s * m21;
dst[6] = c * m12 + s * m22;
dst[7] = c * m13 + s * m23;
dst[8] = c * m20 - s * m10;
dst[9] = c * m21 - s * m11;
dst[10] = c * m22 - s * m12;
dst[11] = c * m23 - s * m13;
if (m !== dst) {
dst[0] = m[0];
dst[1] = m[1];
dst[2] = m[2];
dst[3] = m[3];
dst[12] = m[12];
dst[13] = m[13];
dst[14] = m[14];
dst[15] = m[15];
}
return dst;
}
/**
* Creates a 4-by-4 matrix which rotates around the y-axis by the given angle.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The rotation matrix.
* @memberOf module:twgl/m4
*/
function rotationY(angleInRadians, dst) {
dst = dst || new MatType(16);
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
dst[0] = c;
dst[1] = 0;
dst[2] = -s;
dst[3] = 0;
dst[4] = 0;
dst[5] = 1;
dst[6] = 0;
dst[7] = 0;
dst[8] = s;
dst[9] = 0;
dst[10] = c;
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1;
return dst;
}
/**
* Modifies the given 4-by-4 matrix by a rotation around the y-axis by the given
* angle.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} m once modified.
* @memberOf module:twgl/m4
*/
function rotateY(m, angleInRadians, dst) {
dst = dst || new MatType(16);
var m00 = m[0 * 4 + 0];
var m01 = m[0 * 4 + 1];
var m02 = m[0 * 4 + 2];
var m03 = m[0 * 4 + 3];
var m20 = m[2 * 4 + 0];
var m21 = m[2 * 4 + 1];
var m22 = m[2 * 4 + 2];
var m23 = m[2 * 4 + 3];
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
dst[0] = c * m00 - s * m20;
dst[1] = c * m01 - s * m21;
dst[2] = c * m02 - s * m22;
dst[3] = c * m03 - s * m23;
dst[8] = c * m20 + s * m00;
dst[9] = c * m21 + s * m01;
dst[10] = c * m22 + s * m02;
dst[11] = c * m23 + s * m03;
if (m !== dst) {
dst[4] = m[4];
dst[5] = m[5];
dst[6] = m[6];
dst[7] = m[7];
dst[12] = m[12];
dst[13] = m[13];
dst[14] = m[14];
dst[15] = m[15];
}
return dst;
}
/**
* Creates a 4-by-4 matrix which rotates around the z-axis by the given angle.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The rotation matrix.
* @memberOf module:twgl/m4
*/
function rotationZ(angleInRadians, dst) {
dst = dst || new MatType(16);
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
dst[0] = c;
dst[1] = s;
dst[2] = 0;
dst[3] = 0;
dst[4] = -s;
dst[5] = c;
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = 1;
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1;
return dst;
}
/**
* Modifies the given 4-by-4 matrix by a rotation around the z-axis by the given
* angle.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} m once modified.
* @memberOf module:twgl/m4
*/
function rotateZ(m, angleInRadians, dst) {
dst = dst || new MatType(16);
var m00 = m[0 * 4 + 0];
var m01 = m[0 * 4 + 1];
var m02 = m[0 * 4 + 2];
var m03 = m[0 * 4 + 3];
var m10 = m[1 * 4 + 0];
var m11 = m[1 * 4 + 1];
var m12 = m[1 * 4 + 2];
var m13 = m[1 * 4 + 3];
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
dst[0] = c * m00 + s * m10;
dst[1] = c * m01 + s * m11;
dst[2] = c * m02 + s * m12;
dst[3] = c * m03 + s * m13;
dst[4] = c * m10 - s * m00;
dst[5] = c * m11 - s * m01;
dst[6] = c * m12 - s * m02;
dst[7] = c * m13 - s * m03;
if (m !== dst) {
dst[8] = m[8];
dst[9] = m[9];
dst[10] = m[10];
dst[11] = m[11];
dst[12] = m[12];
dst[13] = m[13];
dst[14] = m[14];
dst[15] = m[15];
}
return dst;
}
/**
* Creates a 4-by-4 matrix which rotates around the given axis by the given
* angle.
* @param {Vec3} axis The axis
* about which to rotate.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} A matrix which rotates angle radians
* around the axis.
* @memberOf module:twgl/m4
*/
function axisRotation(axis, angleInRadians, dst) {
dst = dst || new MatType(16);
var x = axis[0];
var y = axis[1];
var z = axis[2];
var n = Math.sqrt(x * x + y * y + z * z);
x /= n;
y /= n;
z /= n;
var xx = x * x;
var yy = y * y;
var zz = z * z;
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
var oneMinusCosine = 1 - c;
dst[0] = xx + (1 - xx) * c;
dst[1] = x * y * oneMinusCosine + z * s;
dst[2] = x * z * oneMinusCosine - y * s;
dst[3] = 0;
dst[4] = x * y * oneMinusCosine - z * s;
dst[5] = yy + (1 - yy) * c;
dst[6] = y * z * oneMinusCosine + x * s;
dst[7] = 0;
dst[8] = x * z * oneMinusCosine + y * s;
dst[9] = y * z * oneMinusCosine - x * s;
dst[10] = zz + (1 - zz) * c;
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1;
return dst;
}
/**
* Modifies the given 4-by-4 matrix by rotation around the given axis by the
* given angle.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {Vec3} axis The axis
* about which to rotate.
* @param {number} angleInRadians The angle by which to rotate (in radians).
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} m once modified.
* @memberOf module:twgl/m4
*/
function axisRotate(m, axis, angleInRadians, dst) {
dst = dst || new MatType(16);
var x = axis[0];
var y = axis[1];
var z = axis[2];
var n = Math.sqrt(x * x + y * y + z * z);
x /= n;
y /= n;
z /= n;
var xx = x * x;
var yy = y * y;
var zz = z * z;
var c = Math.cos(angleInRadians);
var s = Math.sin(angleInRadians);
var oneMinusCosine = 1 - c;
var r00 = xx + (1 - xx) * c;
var r01 = x * y * oneMinusCosine + z * s;
var r02 = x * z * oneMinusCosine - y * s;
var r10 = x * y * oneMinusCosine - z * s;
var r11 = yy + (1 - yy) * c;
var r12 = y * z * oneMinusCosine + x * s;
var r20 = x * z * oneMinusCosine + y * s;
var r21 = y * z * oneMinusCosine - x * s;
var r22 = zz + (1 - zz) * c;
var m00 = m[0];
var m01 = m[1];
var m02 = m[2];
var m03 = m[3];
var m10 = m[4];
var m11 = m[5];
var m12 = m[6];
var m13 = m[7];
var m20 = m[8];
var m21 = m[9];
var m22 = m[10];
var m23 = m[11];
dst[0] = r00 * m00 + r01 * m10 + r02 * m20;
dst[1] = r00 * m01 + r01 * m11 + r02 * m21;
dst[2] = r00 * m02 + r01 * m12 + r02 * m22;
dst[3] = r00 * m03 + r01 * m13 + r02 * m23;
dst[4] = r10 * m00 + r11 * m10 + r12 * m20;
dst[5] = r10 * m01 + r11 * m11 + r12 * m21;
dst[6] = r10 * m02 + r11 * m12 + r12 * m22;
dst[7] = r10 * m03 + r11 * m13 + r12 * m23;
dst[8] = r20 * m00 + r21 * m10 + r22 * m20;
dst[9] = r20 * m01 + r21 * m11 + r22 * m21;
dst[10] = r20 * m02 + r21 * m12 + r22 * m22;
dst[11] = r20 * m03 + r21 * m13 + r22 * m23;
if (m !== dst) {
dst[12] = m[12];
dst[13] = m[13];
dst[14] = m[14];
dst[15] = m[15];
}
return dst;
}
/**
* Creates a 4-by-4 matrix which scales in each dimension by an amount given by
* the corresponding entry in the given vector; assumes the vector has three
* entries.
* @param {Vec3} v A vector of
* three entries specifying the factor by which to scale in each dimension.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} The scaling matrix.
* @memberOf module:twgl/m4
*/
function scaling(v, dst) {
dst = dst || new MatType(16);
dst[0] = v[0];
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = v[1];
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = v[2];
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1;
return dst;
}
/**
* Modifies the given 4-by-4 matrix, scaling in each dimension by an amount
* given by the corresponding entry in the given vector; assumes the vector has
* three entries.
* @param {module:twgl/m4.Mat4} m The matrix to be modified.
* @param {Vec3} v A vector of three entries specifying the
* factor by which to scale in each dimension.
* @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If none new one is created..
* @return {module:twgl/m4.Mat4} m once modified.
* @memberOf module:twgl/m4
*/
function scale(m, v, dst) {
dst = dst || new MatType(16);
var v0 = v[0];
var v1 = v[1];
var v2 = v[2];
dst[0] = v0 * m[0 * 4 + 0];
dst[1] = v0 * m[0 * 4 + 1];
dst[2] = v0 * m[0 * 4 + 2];
dst[3] = v0 * m[0 * 4 + 3];
dst[4] = v1 * m[1 * 4 + 0];
dst[5] = v1 * m[1 * 4 + 1];
dst[6] = v1 * m[1 * 4 + 2];
dst[7] = v1 * m[1 * 4 + 3];
dst[8] = v2 * m[2 * 4 + 0];
dst[9] = v2 * m[2 * 4 + 1];
dst[10] = v2 * m[2 * 4 + 2];
dst[11] = v2 * m[2 * 4 + 3];
if (m !== dst) {
dst[12] = m[12];
dst[13] = m[13];
dst[14] = m[14];
dst[15] = m[15];
}
return dst;
}
/**
* Takes a 4-by-4 matrix and a vector with 3 entries,
* interprets the vector as a point, transforms that point by the matrix, and
* returns the result as a vector with 3 entries.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {Vec3} v The point.
* @param {Vec3} dst optional vec3 to store result
* @return {Vec3} dst or new vec3 if not provided
* @memberOf module:twgl/m4
*/
function transformPoint(m, v, dst) {
dst = dst || v3.create();
var v0 = v[0];
var v1 = v[1];
var v2 = v[2];
var d = v0 * m[0 * 4 + 3] + v1 * m[1 * 4 + 3] + v2 * m[2 * 4 + 3] + m[3 * 4 + 3];
dst[0] = (v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0] + m[3 * 4 + 0]) / d;
dst[1] = (v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1] + m[3 * 4 + 1]) / d;
dst[2] = (v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2] + m[3 * 4 + 2]) / d;
return dst;
}
/**
* Takes a 4-by-4 matrix and a vector with 3 entries, interprets the vector as a
* direction, transforms that direction by the matrix, and returns the result;
* assumes the transformation of 3-dimensional space represented by the matrix
* is parallel-preserving, i.e. any combination of rotation, scaling and
* translation, but not a perspective distortion. Returns a vector with 3
* entries.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {Vec3} v The direction.
* @param {Vec3} dst optional Vec3 to store result
* @return {Vec3} dst or new Vec3 if not provided
* @memberOf module:twgl/m4
*/
function transformDirection(m, v, dst) {
dst = dst || v3.create();
var v0 = v[0];
var v1 = v[1];
var v2 = v[2];
dst[0] = v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0];
dst[1] = v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1];
dst[2] = v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2];
return dst;
}
/**
* Takes a 4-by-4 matrix m and a vector v with 3 entries, interprets the vector
* as a normal to a surface, and computes a vector which is normal upon
* transforming that surface by the matrix. The effect of this function is the
* same as transforming v (as a direction) by the inverse-transpose of m. This
* function assumes the transformation of 3-dimensional space represented by the
* matrix is parallel-preserving, i.e. any combination of rotation, scaling and
* translation, but not a perspective distortion. Returns a vector with 3
* entries.
* @param {module:twgl/m4.Mat4} m The matrix.
* @param {Vec3} v The normal.
* @param {Vec3} [dst] The direction.
* @return {Vec3} The transformed direction.
* @memberOf module:twgl/m4
*/
function transformNormal(m, v, dst) {
dst = dst || v3.create();
var mi = inverse(m);
var v0 = v[0];
var v1 = v[1];
var v2 = v[2];
dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];
dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];
dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];
return dst;
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"axisRotate": axisRotate,
"axisRotation": axisRotation,
"create": identity,
"copy": copy,
"frustum": frustum,
"getAxis": getAxis,
"getTranslation": getTranslation,
"identity": identity,
"inverse": inverse,
"lookAt": lookAt,
"multiply": multiply,
"negate": negate,
"ortho": ortho,
"perspective": perspective,
"rotateX": rotateX,
"rotateY": rotateY,
"rotateZ": rotateZ,
"rotateAxis": axisRotate,
"rotationX": rotationX,
"rotationY": rotationY,
"rotationZ": rotationZ,
"scale": scale,
"scaling": scaling,
"setAxis": setAxis,
"setDefaultType": setDefaultType,
"setTranslation": setTranslation,
"transformDirection": transformDirection,
"transformNormal": transformNormal,
"transformPoint": transformPoint,
"translate": translate,
"translation": translation,
"transpose": transpose
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
"use strict";
/**
*
* Vec3 math math functions.
*
* Almost all functions take an optional `dst` argument. If it is not passed in the
* functions will create a new Vec3. In other words you can do this
*
* var v = v3.cross(v1, v2); // Creates a new Vec3 with the cross product of v1 x v2.
*
* or
*
* var v3 = v3.create();
* v3.cross(v1, v2, v); // Puts the cross product of v1 x v2 in v
*
* The first style is often easier but depending on where it's used it generates garbage where
* as there is almost never allocation with the second style.
*
* It is always save to pass any vector as the destination. So for example
*
* v3.cross(v1, v2, v1); // Puts the cross product of v1 x v2 in v1
*
* @module twgl/v3
*/
var VecType = Float32Array;
/**
* A JavaScript array with 3 values or a Float32Array with 3 values.
* When created by the library will create the default type which is `Float32Array`
* but can be set by calling {@link module:twgl/v3.setDefaultType}.
* @typedef {(number[]|Float32Array)} Vec3
* @memberOf module:twgl/v3
*/
/**
* Sets the type this library creates for a Vec3
* @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`
* @return {constructor} previous constructor for Vec3
*/
function setDefaultType(ctor) {
var oldType = VecType;
VecType = ctor;
return oldType;
}
/**
* Creates a vec3; may be called with x, y, z to set initial values.
* @return {Vec3} the created vector
* @memberOf module:twgl/v3
*/
function create(x, y, z) {
var dst = new VecType(3);
if (x) {
dst[0] = x;
}
if (y) {
dst[1] = y;
}
if (z) {
dst[2] = z;
}
return dst;
}
/**
* Adds two vectors; assumes a and b have the same dimension.
* @param {module:twgl/v3.Vec3} a Operand vector.
* @param {module:twgl/v3.Vec3} b Operand vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @memberOf module:twgl/v3
*/
function add(a, b, dst) {
dst = dst || new VecType(3);
dst[0] = a[0] + b[0];
dst[1] = a[1] + b[1];
dst[2] = a[2] + b[2];
return dst;
}
/**
* Subtracts two vectors.
* @param {module:twgl/v3.Vec3} a Operand vector.
* @param {module:twgl/v3.Vec3} b Operand vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @memberOf module:twgl/v3
*/
function subtract(a, b, dst) {
dst = dst || new VecType(3);
dst[0] = a[0] - b[0];
dst[1] = a[1] - b[1];
dst[2] = a[2] - b[2];
return dst;
}
/**
* Performs linear interpolation on two vectors.
* Given vectors a and b and interpolation coefficient t, returns
* (1 - t) * a + t * b.
* @param {module:twgl/v3.Vec3} a Operand vector.
* @param {module:twgl/v3.Vec3} b Operand vector.
* @param {number} t Interpolation coefficient.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @memberOf module:twgl/v3
*/
function lerp(a, b, t, dst) {
dst = dst || new VecType(3);
dst[0] = (1 - t) * a[0] + t * b[0];
dst[1] = (1 - t) * a[1] + t * b[1];
dst[2] = (1 - t) * a[2] + t * b[2];
return dst;
}
/**
* Mutiplies a vector by a scalar.
* @param {module:twgl/v3.Vec3} v The vector.
* @param {number} k The scalar.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} dst.
* @memberOf module:twgl/v3
*/
function mulScalar(v, k, dst) {
dst = dst || new VecType(3);
dst[0] = v[0] * k;
dst[1] = v[1] * k;
dst[2] = v[2] * k;
return dst;
}
/**
* Divides a vector by a scalar.
* @param {module:twgl/v3.Vec3} v The vector.
* @param {number} k The scalar.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} dst.
* @memberOf module:twgl/v3
*/
function divScalar(v, k, dst) {
dst = dst || new VecType(3);
dst[0] = v[0] / k;
dst[1] = v[1] / k;
dst[2] = v[2] / k;
return dst;
}
/**
* Computes the cross product of two vectors; assumes both vectors have
* three entries.
* @param {module:twgl/v3.Vec3} a Operand vector.
* @param {module:twgl/v3.Vec3} b Operand vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} The vector a cross b.
* @memberOf module:twgl/v3
*/
function cross(a, b, dst) {
dst = dst || new VecType(3);
dst[0] = a[1] * b[2] - a[2] * b[1];
dst[1] = a[2] * b[0] - a[0] * b[2];
dst[2] = a[0] * b[1] - a[1] * b[0];
return dst;
}
/**
* Computes the dot product of two vectors; assumes both vectors have
* three entries.
* @param {module:twgl/v3.Vec3} a Operand vector.
* @param {module:twgl/v3.Vec3} b Operand vector.
* @return {number} dot product
* @memberOf module:twgl/v3
*/
function dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
/**
* Computes the length of vector
* @param {module:twgl/v3.Vec3} v vector.
* @return {number} length of vector.
* @memberOf module:twgl/v3
*/
function length(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
}
/**
* Computes the square of the length of vector
* @param {module:twgl/v3.Vec3} v vector.
* @return {number} square of the length of vector.
* @memberOf module:twgl/v3
*/
function lengthSq(v) {
return v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
}
/**
* Divides a vector by its Euclidean length and returns the quotient.
* @param {module:twgl/v3.Vec3} a The vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} The normalized vector.
* @memberOf module:twgl/v3
*/
function normalize(a, dst) {
dst = dst || new VecType(3);
var lenSq = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];
var len = Math.sqrt(lenSq);
if (len > 0.00001) {
dst[0] = a[0] / len;
dst[1] = a[1] / len;
dst[2] = a[2] / len;
} else {
dst[0] = 0;
dst[1] = 0;
dst[2] = 0;
}
return dst;
}
/**
* Negates a vector.
* @param {module:twgl/v3.Vec3} v The vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} -v.
* @memberOf module:twgl/v3
*/
function negate(v, dst) {
dst = dst || new VecType(3);
dst[0] = -v[0];
dst[1] = -v[1];
dst[2] = -v[2];
return dst;
}
/**
* Copies a vector.
* @param {module:twgl/v3.Vec3} v The vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} A copy of v.
* @memberOf module:twgl/v3
*/
function copy(v, dst) {
dst = dst || new VecType(3);
dst[0] = v[0];
dst[1] = v[1];
dst[2] = v[2];
return dst;
}
/**
* Multiplies a vector by another vector (component-wise); assumes a and
* b have the same length.
* @param {module:twgl/v3.Vec3} a Operand vector.
* @param {module:twgl/v3.Vec3} b Operand vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} The vector of products of entries of a and
* b.
* @memberOf module:twgl/v3
*/
function multiply(a, b, dst) {
dst = dst || new VecType(3);
dst[0] = a[0] * b[0];
dst[1] = a[1] * b[1];
dst[2] = a[2] * b[2];
return dst;
}
/**
* Divides a vector by another vector (component-wise); assumes a and
* b have the same length.
* @param {module:twgl/v3.Vec3} a Operand vector.
* @param {module:twgl/v3.Vec3} b Operand vector.
* @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created..
* @return {module:twgl/v3.Vec3} The vector of quotients of entries of a and
* b.
* @memberOf module:twgl/v3
*/
function divide(a, b, dst) {
dst = dst || new VecType(3);
dst[0] = a[0] / b[0];
dst[1] = a[1] / b[1];
dst[2] = a[2] / b[2];
return dst;
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"add": add,
"copy": copy,
"create": create,
"cross": cross,
"divide": divide,
"divScalar": divScalar,
"dot": dot,
"lerp": lerp,
"length": length,
"lengthSq": lengthSq,
"mulScalar": mulScalar,
"multiply": multiply,
"negate": negate,
"normalize": normalize,
"setDefaultType": setDefaultType,
"subtract": subtract
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
/*
* Copyright 2015, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Various functions to make simple primitives
*
* note: Most primitive functions come in 3 styles
*
* * `createSomeShapeBufferInfo`
*
* These functions are almost always the functions you want to call. They
* create vertices then make WebGLBuffers and create {@link module:twgl.AttribInfo}s
* returing a {@link module:twgl.BufferInfo} you can pass to {@link module:twgl.setBuffersAndAttributes}
* and {@link module:twgl.drawBufferInfo} etc...
*
* * `createSomeShapeBuffers`
*
* These create WebGLBuffers and put your data in them but nothing else.
* It's a shortcut to doing it yourself if you don't want to use
* the higher level functions.
*
* * `createSomeShapeVertices`
*
* These just create vertices, no buffers. This allows you to manipulate the vertices
* or add more data before generating a {@link module:twgl.BufferInfo}. Once you're finished
* manipulating the vertices call {@link module:twgl.createBufferInfoFromArrays}.
*
* example:
*
* var arrays = twgl.primitives.createPlaneArrays(1);
* twgl.primitives.reorientVertices(arrays, m4.rotationX(Math.PI * 0.5));
* var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);
*
* @module twgl/primitives
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(2), __webpack_require__(4), __webpack_require__(10), __webpack_require__(11)], __WEBPACK_AMD_DEFINE_RESULT__ = function (attributes, utils, m4, v3) {
"use strict";
var getArray = attributes.getArray_; // eslint-disable-line
var getNumComponents = attributes.getNumComponents_; // eslint-disable-line
/**
* Add `push` to a typed array. It just keeps a 'cursor'
* and allows use to `push` values into the array so we
* don't have to manually compute offsets
* @param {TypedArray} typedArray TypedArray to augment
* @param {number} numComponents number of components.
*/
function augmentTypedArray(typedArray, numComponents) {
var cursor = 0;
typedArray.push = function () {
for (var ii = 0; ii < arguments.length; ++ii) {
var value = arguments[ii];
if (value instanceof Array || value.buffer && value.buffer instanceof ArrayBuffer) {
for (var jj = 0; jj < value.length; ++jj) {
typedArray[cursor++] = value[jj];
}
} else {
typedArray[cursor++] = value;
}
}
};
typedArray.reset = function (opt_index) {
cursor = opt_index || 0;
};
typedArray.numComponents = numComponents;
Object.defineProperty(typedArray, 'numElements', {
get: function get() {
return this.length / this.numComponents | 0;
}
});
return typedArray;
}
/**
* creates a typed array with a `push` function attached
* so that you can easily *push* values.
*
* `push` can take multiple arguments. If an argument is an array each element
* of the array will be added to the typed array.
*
* Example:
*
* var array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
* array.push(1, 2, 3);
* array.push([4, 5, 6]);
* // array now contains [1, 2, 3, 4, 5, 6]
*
* Also has `numComponents` and `numElements` properties.
*
* @param {number} numComponents number of components
* @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`.
* @param {constructor} opt_type A constructor for the type. Default = `Float32Array`.
* @return {ArrayBuffer} A typed array.
* @memberOf module:twgl/primitives
*/
function createAugmentedTypedArray(numComponents, numElements, opt_type) {
var Type = opt_type || Float32Array;
return augmentTypedArray(new Type(numComponents * numElements), numComponents);
}
function allButIndices(name) {
return name !== "indices";
}
/**
* Given indexed vertices creates a new set of vertices unindexed by expanding the indexed vertices.
* @param {Object.<string, TypedArray>} vertices The indexed vertices to deindex
* @return {Object.<string, TypedArray>} The deindexed vertices
* @memberOf module:twgl/primitives
*/
function deindexVertices(vertices) {
var indices = vertices.indices;
var newVertices = {};
var numElements = indices.length;
function expandToUnindexed(channel) {
var srcBuffer = vertices[channel];
var numComponents = srcBuffer.numComponents;
var dstBuffer = createAugmentedTypedArray(numComponents, numElements, srcBuffer.constructor);
for (var ii = 0; ii < numElements; ++ii) {
var ndx = indices[ii];
var offset = ndx * numComponents;
for (var jj = 0; jj < numComponents; ++jj) {
dstBuffer.push(srcBuffer[offset + jj]);
}
}
newVertices[channel] = dstBuffer;
}
Object.keys(vertices).filter(allButIndices).forEach(expandToUnindexed);
return newVertices;
}
/**
* flattens the normals of deindexed vertices in place.
* @param {Object.<string, TypedArray>} vertices The deindexed vertices who's normals to flatten
* @return {Object.<string, TypedArray>} The flattened vertices (same as was passed in)
* @memberOf module:twgl/primitives
*/
function flattenNormals(vertices) {
if (vertices.indices) {
throw "can't flatten normals of indexed vertices. deindex them first";
}
var normals = vertices.normal;
var numNormals = normals.length;
for (var ii = 0; ii < numNormals; ii += 9) {
// pull out the 3 normals for this triangle
var nax = normals[ii + 0];
var nay = normals[ii + 1];
var naz = normals[ii + 2];
var nbx = normals[ii + 3];
var nby = normals[ii + 4];
var nbz = normals[ii + 5];
var ncx = normals[ii + 6];
var ncy = normals[ii + 7];
var ncz = normals[ii + 8];
// add them
var nx = nax + nbx + ncx;
var ny = nay + nby + ncy;
var nz = naz + nbz + ncz;
// normalize them
var length = Math.sqrt(nx * nx + ny * ny + nz * nz);
nx /= length;
ny /= length;
nz /= length;
// copy them back in
normals[ii + 0] = nx;
normals[ii + 1] = ny;
normals[ii + 2] = nz;
normals[ii + 3] = nx;
normals[ii + 4] = ny;
normals[ii + 5] = nz;
normals[ii + 6] = nx;
normals[ii + 7] = ny;
normals[ii + 8] = nz;
}
return vertices;
}
function applyFuncToV3Array(array, matrix, fn) {
var len = array.length;
var tmp = new Float32Array(3);
for (var ii = 0; ii < len; ii += 3) {
fn(matrix, [array[ii], array[ii + 1], array[ii + 2]], tmp);
array[ii] = tmp[0];
array[ii + 1] = tmp[1];
array[ii + 2] = tmp[2];
}
}
function transformNormal(mi, v, dst) {
dst = dst || v3.create();
var v0 = v[0];
var v1 = v[1];
var v2 = v[2];
dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];
dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];
dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];
return dst;
}
/**
* Reorients directions by the given matrix..
* @param {number[]|TypedArray} array The array. Assumes value floats per element.
* @param {Matrix} matrix A matrix to multiply by.
* @return {number[]|TypedArray} the same array that was passed in
* @memberOf module:twgl/primitives
*/
function reorientDirections(array, matrix) {
applyFuncToV3Array(array, matrix, m4.transformDirection);
return array;
}
/**
* Reorients normals by the inverse-transpose of the given
* matrix..
* @param {number[]|TypedArray} array The array. Assumes value floats per element.
* @param {Matrix} matrix A matrix to multiply by.
* @return {number[]|TypedArray} the same array that was passed in
* @memberOf module:twgl/primitives
*/
function reorientNormals(array, matrix) {
applyFuncToV3Array(array, m4.inverse(matrix), transformNormal);
return array;
}
/**
* Reorients positions by the given matrix. In other words, it
* multiplies each vertex by the given matrix.
* @param {number[]|TypedArray} array The array. Assumes value floats per element.
* @param {Matrix} matrix A matrix to multiply by.
* @return {number[]|TypedArray} the same array that was passed in
* @memberOf module:twgl/primitives
*/
function reorientPositions(array, matrix) {
applyFuncToV3Array(array, matrix, m4.transformPoint);
return array;
}
/**
* Reorients arrays by the given matrix. Assumes arrays have
* names that contains 'pos' could be reoriented as positions,
* 'binorm' or 'tan' as directions, and 'norm' as normals.
*
* @param {Object.<string, (number[]|TypedArray)>} arrays The vertices to reorient
* @param {Matrix} matrix matrix to reorient by.
* @return {Object.<string, (number[]|TypedArray)>} same arrays that were passed in.
* @memberOf module:twgl/primitives
*/
function reorientVertices(arrays, matrix) {
Object.keys(arrays).forEach(function (name) {
var array = arrays[name];
if (name.indexOf("pos") >= 0) {
reorientPositions(array, matrix);
} else if (name.indexOf("tan") >= 0 || name.indexOf("binorm") >= 0) {
reorientDirections(array, matrix);
} else if (name.indexOf("norm") >= 0) {
reorientNormals(array, matrix);
}
});
return arrays;
}
/**
* Creates XY quad BufferInfo
*
* The default with no parameters will return a 2x2 quad with values from -1 to +1.
* If you want a unit quad with that goes from 0 to 1 you'd call it with
*
* twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);
*
* If you want a unit quad centered above 0,0 you'd call it with
*
* twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1
* @param {number} [xOffset] the amount to offset the quad in X
* @param {number} [yOffset] the amount to offset the quad in Y
* @return {Object.<string, WebGLBuffer>} the created XY Quad BufferInfo
* @memberOf module:twgl/primitives
* @function createXYQuadBufferInfo
*/
/**
* Creates XY quad Buffers
*
* The default with no parameters will return a 2x2 quad with values from -1 to +1.
* If you want a unit quad with that goes from 0 to 1 you'd call it with
*
* twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);
*
* If you want a unit quad centered above 0,0 you'd call it with
*
* twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1
* @param {number} [xOffset] the amount to offset the quad in X
* @param {number} [yOffset] the amount to offset the quad in Y
* @return {module:twgl.BufferInfo} the created XY Quad buffers
* @memberOf module:twgl/primitives
* @function createXYQuadBuffers
*/
/**
* Creates XY quad vertices
*
* The default with no parameters will return a 2x2 quad with values from -1 to +1.
* If you want a unit quad with that goes from 0 to 1 you'd call it with
*
* twgl.primitives.createXYQuadVertices(1, 0.5, 0.5);
*
* If you want a unit quad centered above 0,0 you'd call it with
*
* twgl.primitives.createXYQuadVertices(1, 0, 0.5);
*
* @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1
* @param {number} [xOffset] the amount to offset the quad in X
* @param {number} [yOffset] the amount to offset the quad in Y
* @return {Object.<string, TypedArray> the created XY Quad vertices
* @memberOf module:twgl/primitives
*/
function createXYQuadVertices(size, xOffset, yOffset) {
size = size || 2;
xOffset = xOffset || 0;
yOffset = yOffset || 0;
size *= 0.5;
return {
position: {
numComponents: 2,
data: [xOffset + -1 * size, yOffset + -1 * size, xOffset + 1 * size, yOffset + -1 * size, xOffset + -1 * size, yOffset + 1 * size, xOffset + 1 * size, yOffset + 1 * size]
},
normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
texcoord: [0, 0, 1, 0, 0, 1, 1, 1],
indices: [0, 1, 2, 2, 1, 3]
};
}
/**
* Creates XZ plane BufferInfo.
*
* The created plane has position, normal, and texcoord data
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} [width] Width of the plane. Default = 1
* @param {number} [depth] Depth of the plane. Default = 1
* @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1
* @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1
* @param {Matrix4} [matrix] A matrix by which to multiply all the vertices.
* @return {@module:twgl.BufferInfo} The created plane BufferInfo.
* @memberOf module:twgl/primitives
* @function createPlaneBufferInfo
*/
/**
* Creates XZ plane buffers.
*
* The created plane has position, normal, and texcoord data
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} [width] Width of the plane. Default = 1
* @param {number} [depth] Depth of the plane. Default = 1
* @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1
* @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1
* @param {Matrix4} [matrix] A matrix by which to multiply all the vertices.
* @return {Object.<string, WebGLBuffer>} The created plane buffers.
* @memberOf module:twgl/primitives
* @function createPlaneBuffers
*/
/**
* Creates XZ plane vertices.
*
* The created plane has position, normal, and texcoord data
*
* @param {number} [width] Width of the plane. Default = 1
* @param {number} [depth] Depth of the plane. Default = 1
* @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1
* @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1
* @param {Matrix4} [matrix] A matrix by which to multiply all the vertices.
* @return {Object.<string, TypedArray>} The created plane vertices.
* @memberOf module:twgl/primitives
*/
function createPlaneVertices(width, depth, subdivisionsWidth, subdivisionsDepth, matrix) {
width = width || 1;
depth = depth || 1;
subdivisionsWidth = subdivisionsWidth || 1;
subdivisionsDepth = subdivisionsDepth || 1;
matrix = matrix || m4.identity();
var numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1);
var positions = createAugmentedTypedArray(3, numVertices);
var normals = createAugmentedTypedArray(3, numVertices);
var texcoords = createAugmentedTypedArray(2, numVertices);
for (var z = 0; z <= subdivisionsDepth; z++) {
for (var x = 0; x <= subdivisionsWidth; x++) {
var u = x / subdivisionsWidth;
var v = z / subdivisionsDepth;
positions.push(width * u - width * 0.5, 0, depth * v - depth * 0.5);
normals.push(0, 1, 0);
texcoords.push(u, v);
}
}
var numVertsAcross = subdivisionsWidth + 1;
var indices = createAugmentedTypedArray(3, subdivisionsWidth * subdivisionsDepth * 2, Uint16Array);
for (var z = 0; z < subdivisionsDepth; z++) {
// eslint-disable-line
for (var x = 0; x < subdivisionsWidth; x++) {
// eslint-disable-line
// Make triangle 1 of quad.
indices.push((z + 0) * numVertsAcross + x, (z + 1) * numVertsAcross + x, (z + 0) * numVertsAcross + x + 1);
// Make triangle 2 of quad.
indices.push((z + 1) * numVertsAcross + x, (z + 1) * numVertsAcross + x + 1, (z + 0) * numVertsAcross + x + 1);
}
}
var arrays = reorientVertices({
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices
}, matrix);
return arrays;
}
/**
* Creates sphere BufferInfo.
*
* The created sphere has position, normal, and texcoord data
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius radius of the sphere.
* @param {number} subdivisionsAxis number of steps around the sphere.
* @param {number} subdivisionsHeight number of vertically on the sphere.
* @param {number} [opt_startLatitudeInRadians] where to start the
* top of the sphere. Default = 0.
* @param {number} [opt_endLatitudeInRadians] Where to end the
* bottom of the sphere. Default = Math.PI.
* @param {number} [opt_startLongitudeInRadians] where to start
* wrapping the sphere. Default = 0.
* @param {number} [opt_endLongitudeInRadians] where to end
* wrapping the sphere. Default = 2 * Math.PI.
* @return {module:twgl.BufferInfo} The created sphere BufferInfo.
* @memberOf module:twgl/primitives
* @function createSphereBufferInfo
*/
/**
* Creates sphere buffers.
*
* The created sphere has position, normal, and texcoord data
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius radius of the sphere.
* @param {number} subdivisionsAxis number of steps around the sphere.
* @param {number} subdivisionsHeight number of vertically on the sphere.
* @param {number} [opt_startLatitudeInRadians] where to start the
* top of the sphere. Default = 0.
* @param {number} [opt_endLatitudeInRadians] Where to end the
* bottom of the sphere. Default = Math.PI.
* @param {number} [opt_startLongitudeInRadians] where to start
* wrapping the sphere. Default = 0.
* @param {number} [opt_endLongitudeInRadians] where to end
* wrapping the sphere. Default = 2 * Math.PI.
* @return {Object.<string, WebGLBuffer>} The created sphere buffers.
* @memberOf module:twgl/primitives
* @function createSphereBuffers
*/
/**
* Creates sphere vertices.
*
* The created sphere has position, normal, and texcoord data
*
* @param {number} radius radius of the sphere.
* @param {number} subdivisionsAxis number of steps around the sphere.
* @param {number} subdivisionsHeight number of vertically on the sphere.
* @param {number} [opt_startLatitudeInRadians] where to start the
* top of the sphere. Default = 0.
* @param {number} [opt_endLatitudeInRadians] Where to end the
* bottom of the sphere. Default = Math.PI.
* @param {number} [opt_startLongitudeInRadians] where to start
* wrapping the sphere. Default = 0.
* @param {number} [opt_endLongitudeInRadians] where to end
* wrapping the sphere. Default = 2 * Math.PI.
* @return {Object.<string, TypedArray>} The created sphere vertices.
* @memberOf module:twgl/primitives
*/
function createSphereVertices(radius, subdivisionsAxis, subdivisionsHeight, opt_startLatitudeInRadians, opt_endLatitudeInRadians, opt_startLongitudeInRadians, opt_endLongitudeInRadians) {
if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {
throw Error('subdivisionAxis and subdivisionHeight must be > 0');
}
opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0;
opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI;
opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0;
opt_endLongitudeInRadians = opt_endLongitudeInRadians || Math.PI * 2;
var latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians;
var longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians;
// We are going to generate our sphere by iterating through its
// spherical coordinates and generating 2 triangles for each quad on a
// ring of the sphere.
var numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1);
var positions = createAugmentedTypedArray(3, numVertices);
var normals = createAugmentedTypedArray(3, numVertices);
var texcoords = createAugmentedTypedArray(2, numVertices);
// Generate the individual vertices in our vertex buffer.
for (var y = 0; y <= subdivisionsHeight; y++) {
for (var x = 0; x <= subdivisionsAxis; x++) {
// Generate a vertex based on its spherical coordinates
var u = x / subdivisionsAxis;
var v = y / subdivisionsHeight;
var theta = longRange * u;
var phi = latRange * v;
var sinTheta = Math.sin(theta);
var cosTheta = Math.cos(theta);
var sinPhi = Math.sin(phi);
var cosPhi = Math.cos(phi);
var ux = cosTheta * sinPhi;
var uy = cosPhi;
var uz = sinTheta * sinPhi;
positions.push(radius * ux, radius * uy, radius * uz);
normals.push(ux, uy, uz);
texcoords.push(1 - u, v);
}
}
var numVertsAround = subdivisionsAxis + 1;
var indices = createAugmentedTypedArray(3, subdivisionsAxis * subdivisionsHeight * 2, Uint16Array);
for (var x = 0; x < subdivisionsAxis; x++) {
// eslint-disable-line
for (var y = 0; y < subdivisionsHeight; y++) {
// eslint-disable-line
// Make triangle 1 of quad.
indices.push((y + 0) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x);
// Make triangle 2 of quad.
indices.push((y + 1) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x + 1);
}
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices
};
}
/**
* Array of the indices of corners of each face of a cube.
* @type {Array.<number[]>}
*/
var CUBE_FACE_INDICES = [[3, 7, 5, 1], // right
[6, 2, 0, 4], // left
[6, 7, 3, 2], // ??
[0, 1, 5, 4], // ??
[7, 6, 4, 5], // front
[2, 3, 1, 0]];
/**
* Creates a BufferInfo for a cube.
*
* The cube is created around the origin. (-size / 2, size / 2).
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} [size] width, height and depth of the cube.
* @return {module:twgl.BufferInfo} The created BufferInfo.
* @memberOf module:twgl/primitives
* @function createCubeBufferInfo
*/
/**
* Creates the buffers and indices for a cube.
*
* The cube is created around the origin. (-size / 2, size / 2).
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} [size] width, height and depth of the cube.
* @return {Object.<string, WebGLBuffer>} The created buffers.
* @memberOf module:twgl/primitives
* @function createCubeBuffers
*/
/**
* Creates the vertices and indices for a cube.
*
* The cube is created around the origin. (-size / 2, size / 2).
*
* @param {number} [size] width, height and depth of the cube.
* @return {Object.<string, TypedArray>} The created vertices.
* @memberOf module:twgl/primitives
*/
function createCubeVertices(size) {
size = size || 1;
var k = size / 2;
var cornerVertices = [[-k, -k, -k], [+k, -k, -k], [-k, +k, -k], [+k, +k, -k], [-k, -k, +k], [+k, -k, +k], [-k, +k, +k], [+k, +k, +k]];
var faceNormals = [[+1, +0, +0], [-1, +0, +0], [+0, +1, +0], [+0, -1, +0], [+0, +0, +1], [+0, +0, -1]];
var uvCoords = [[1, 0], [0, 0], [0, 1], [1, 1]];
var numVertices = 6 * 4;
var positions = createAugmentedTypedArray(3, numVertices);
var normals = createAugmentedTypedArray(3, numVertices);
var texcoords = createAugmentedTypedArray(2, numVertices);
var indices = createAugmentedTypedArray(3, 6 * 2, Uint16Array);
for (var f = 0; f < 6; ++f) {
var faceIndices = CUBE_FACE_INDICES[f];
for (var v = 0; v < 4; ++v) {
var position = cornerVertices[faceIndices[v]];
var normal = faceNormals[f];
var uv = uvCoords[v];
// Each face needs all four vertices because the normals and texture
// coordinates are not all the same.
positions.push(position);
normals.push(normal);
texcoords.push(uv);
}
// Two triangles make a square face.
var offset = 4 * f;
indices.push(offset + 0, offset + 1, offset + 2);
indices.push(offset + 0, offset + 2, offset + 3);
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices
};
}
/**
* Creates a BufferInfo for a truncated cone, which is like a cylinder
* except that it has different top and bottom radii. A truncated cone
* can also be used to create cylinders and regular cones. The
* truncated cone will be created centered about the origin, with the
* y axis as its vertical axis.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} bottomRadius Bottom radius of truncated cone.
* @param {number} topRadius Top radius of truncated cone.
* @param {number} height Height of truncated cone.
* @param {number} radialSubdivisions The number of subdivisions around the
* truncated cone.
* @param {number} verticalSubdivisions The number of subdivisions down the
* truncated cone.
* @param {boolean} [opt_topCap] Create top cap. Default = true.
* @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.
* @return {module:twgl.BufferInfo} The created cone BufferInfo.
* @memberOf module:twgl/primitives
* @function createTruncatedConeBufferInfo
*/
/**
* Creates buffers for a truncated cone, which is like a cylinder
* except that it has different top and bottom radii. A truncated cone
* can also be used to create cylinders and regular cones. The
* truncated cone will be created centered about the origin, with the
* y axis as its vertical axis.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} bottomRadius Bottom radius of truncated cone.
* @param {number} topRadius Top radius of truncated cone.
* @param {number} height Height of truncated cone.
* @param {number} radialSubdivisions The number of subdivisions around the
* truncated cone.
* @param {number} verticalSubdivisions The number of subdivisions down the
* truncated cone.
* @param {boolean} [opt_topCap] Create top cap. Default = true.
* @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.
* @return {Object.<string, WebGLBuffer>} The created cone buffers.
* @memberOf module:twgl/primitives
* @function createTruncatedConeBuffers
*/
/**
* Creates vertices for a truncated cone, which is like a cylinder
* except that it has different top and bottom radii. A truncated cone
* can also be used to create cylinders and regular cones. The
* truncated cone will be created centered about the origin, with the
* y axis as its vertical axis. .
*
* @param {number} bottomRadius Bottom radius of truncated cone.
* @param {number} topRadius Top radius of truncated cone.
* @param {number} height Height of truncated cone.
* @param {number} radialSubdivisions The number of subdivisions around the
* truncated cone.
* @param {number} verticalSubdivisions The number of subdivisions down the
* truncated cone.
* @param {boolean} [opt_topCap] Create top cap. Default = true.
* @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.
* @return {Object.<string, TypedArray>} The created cone vertices.
* @memberOf module:twgl/primitives
*/
function createTruncatedConeVertices(bottomRadius, topRadius, height, radialSubdivisions, verticalSubdivisions, opt_topCap, opt_bottomCap) {
if (radialSubdivisions < 3) {
throw Error('radialSubdivisions must be 3 or greater');
}
if (verticalSubdivisions < 1) {
throw Error('verticalSubdivisions must be 1 or greater');
}
var topCap = opt_topCap === undefined ? true : opt_topCap;
var bottomCap = opt_bottomCap === undefined ? true : opt_bottomCap;
var extra = (topCap ? 2 : 0) + (bottomCap ? 2 : 0);
var numVertices = (radialSubdivisions + 1) * (verticalSubdivisions + 1 + extra);
var positions = createAugmentedTypedArray(3, numVertices);
var normals = createAugmentedTypedArray(3, numVertices);
var texcoords = createAugmentedTypedArray(2, numVertices);
var indices = createAugmentedTypedArray(3, radialSubdivisions * (verticalSubdivisions + extra) * 2, Uint16Array);
var vertsAroundEdge = radialSubdivisions + 1;
// The slant of the cone is constant across its surface
var slant = Math.atan2(bottomRadius - topRadius, height);
var cosSlant = Math.cos(slant);
var sinSlant = Math.sin(slant);
var start = topCap ? -2 : 0;
var end = verticalSubdivisions + (bottomCap ? 2 : 0);
for (var yy = start; yy <= end; ++yy) {
var v = yy / verticalSubdivisions;
var y = height * v;
var ringRadius;
if (yy < 0) {
y = 0;
v = 1;
ringRadius = bottomRadius;
} else if (yy > verticalSubdivisions) {
y = height;
v = 1;
ringRadius = topRadius;
} else {
ringRadius = bottomRadius + (topRadius - bottomRadius) * (yy / verticalSubdivisions);
}
if (yy === -2 || yy === verticalSubdivisions + 2) {
ringRadius = 0;
v = 0;
}
y -= height / 2;
for (var ii = 0; ii < vertsAroundEdge; ++ii) {
var sin = Math.sin(ii * Math.PI * 2 / radialSubdivisions);
var cos = Math.cos(ii * Math.PI * 2 / radialSubdivisions);
positions.push(sin * ringRadius, y, cos * ringRadius);
normals.push(yy < 0 || yy > verticalSubdivisions ? 0 : sin * cosSlant, yy < 0 ? -1 : yy > verticalSubdivisions ? 1 : sinSlant, yy < 0 || yy > verticalSubdivisions ? 0 : cos * cosSlant);
texcoords.push(ii / radialSubdivisions, 1 - v);
}
}
for (var yy = 0; yy < verticalSubdivisions + extra; ++yy) {
// eslint-disable-line
for (var ii = 0; ii < radialSubdivisions; ++ii) {
// eslint-disable-line
indices.push(vertsAroundEdge * (yy + 0) + 0 + ii, vertsAroundEdge * (yy + 0) + 1 + ii, vertsAroundEdge * (yy + 1) + 1 + ii);
indices.push(vertsAroundEdge * (yy + 0) + 0 + ii, vertsAroundEdge * (yy + 1) + 1 + ii, vertsAroundEdge * (yy + 1) + 0 + ii);
}
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices
};
}
/**
* Expands RLE data
* @param {number[]} rleData data in format of run-length, x, y, z, run-length, x, y, z
* @param {number[]} [padding] value to add each entry with.
* @return {number[]} the expanded rleData
*/
function expandRLEData(rleData, padding) {
padding = padding || [];
var data = [];
for (var ii = 0; ii < rleData.length; ii += 4) {
var runLength = rleData[ii];
var element = rleData.slice(ii + 1, ii + 4);
element.push.apply(element, padding);
for (var jj = 0; jj < runLength; ++jj) {
data.push.apply(data, element);
}
}
return data;
}
/**
* Creates 3D 'F' BufferInfo.
* An 'F' is useful because you can easily tell which way it is oriented.
* The created 'F' has position, normal, texcoord, and color buffers.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @return {module:twgl.BufferInfo} The created BufferInfo.
* @memberOf module:twgl/primitives
* @function create3DFBufferInfo
*/
/**
* Creates 3D 'F' buffers.
* An 'F' is useful because you can easily tell which way it is oriented.
* The created 'F' has position, normal, texcoord, and color buffers.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @return {Object.<string, WebGLBuffer>} The created buffers.
* @memberOf module:twgl/primitives
* @function create3DFBuffers
*/
/**
* Creates 3D 'F' vertices.
* An 'F' is useful because you can easily tell which way it is oriented.
* The created 'F' has position, normal, texcoord, and color arrays.
*
* @return {Object.<string, TypedArray>} The created vertices.
* @memberOf module:twgl/primitives
*/
function create3DFVertices() {
var positions = [
// left column front
0, 0, 0, 0, 150, 0, 30, 0, 0, 0, 150, 0, 30, 150, 0, 30, 0, 0,
// top rung front
30, 0, 0, 30, 30, 0, 100, 0, 0, 30, 30, 0, 100, 30, 0, 100, 0, 0,
// middle rung front
30, 60, 0, 30, 90, 0, 67, 60, 0, 30, 90, 0, 67, 90, 0, 67, 60, 0,
// left column back
0, 0, 30, 30, 0, 30, 0, 150, 30, 0, 150, 30, 30, 0, 30, 30, 150, 30,
// top rung back
30, 0, 30, 100, 0, 30, 30, 30, 30, 30, 30, 30, 100, 0, 30, 100, 30, 30,
// middle rung back
30, 60, 30, 67, 60, 30, 30, 90, 30, 30, 90, 30, 67, 60, 30, 67, 90, 30,
// top
0, 0, 0, 100, 0, 0, 100, 0, 30, 0, 0, 0, 100, 0, 30, 0, 0, 30,
// top rung front
100, 0, 0, 100, 30, 0, 100, 30, 30, 100, 0, 0, 100, 30, 30, 100, 0, 30,
// under top rung
30, 30, 0, 30, 30, 30, 100, 30, 30, 30, 30, 0, 100, 30, 30, 100, 30, 0,
// between top rung and middle
30, 30, 0, 30, 60, 30, 30, 30, 30, 30, 30, 0, 30, 60, 0, 30, 60, 30,
// top of middle rung
30, 60, 0, 67, 60, 30, 30, 60, 30, 30, 60, 0, 67, 60, 0, 67, 60, 30,
// front of middle rung
67, 60, 0, 67, 90, 30, 67, 60, 30, 67, 60, 0, 67, 90, 0, 67, 90, 30,
// bottom of middle rung.
30, 90, 0, 30, 90, 30, 67, 90, 30, 30, 90, 0, 67, 90, 30, 67, 90, 0,
// front of bottom
30, 90, 0, 30, 150, 30, 30, 90, 30, 30, 90, 0, 30, 150, 0, 30, 150, 30,
// bottom
0, 150, 0, 0, 150, 30, 30, 150, 30, 0, 150, 0, 30, 150, 30, 30, 150, 0,
// left side
0, 0, 0, 0, 0, 30, 0, 150, 30, 0, 0, 0, 0, 150, 30, 0, 150, 0];
var texcoords = [
// left column front
0.22, 0.19, 0.22, 0.79, 0.34, 0.19, 0.22, 0.79, 0.34, 0.79, 0.34, 0.19,
// top rung front
0.34, 0.19, 0.34, 0.31, 0.62, 0.19, 0.34, 0.31, 0.62, 0.31, 0.62, 0.19,
// middle rung front
0.34, 0.43, 0.34, 0.55, 0.49, 0.43, 0.34, 0.55, 0.49, 0.55, 0.49, 0.43,
// left column back
0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1,
// top rung back
0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1,
// middle rung back
0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1,
// top
0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1,
// top rung front
0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1,
// under top rung
0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0,
// between top rung and middle
0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
// top of middle rung
0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
// front of middle rung
0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
// bottom of middle rung.
0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0,
// front of bottom
0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
// bottom
0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0,
// left side
0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0];
var normals = expandRLEData([
// left column front
// top rung front
// middle rung front
18, 0, 0, 1,
// left column back
// top rung back
// middle rung back
18, 0, 0, -1,
// top
6, 0, 1, 0,
// top rung front
6, 1, 0, 0,
// under top rung
6, 0, -1, 0,
// between top rung and middle
6, 1, 0, 0,
// top of middle rung
6, 0, 1, 0,
// front of middle rung
6, 1, 0, 0,
// bottom of middle rung.
6, 0, -1, 0,
// front of bottom
6, 1, 0, 0,
// bottom
6, 0, -1, 0,
// left side
6, -1, 0, 0]);
var colors = expandRLEData([
// left column front
// top rung front
// middle rung front
18, 200, 70, 120,
// left column back
// top rung back
// middle rung back
18, 80, 70, 200,
// top
6, 70, 200, 210,
// top rung front
6, 200, 200, 70,
// under top rung
6, 210, 100, 70,
// between top rung and middle
6, 210, 160, 70,
// top of middle rung
6, 70, 180, 210,
// front of middle rung
6, 100, 70, 210,
// bottom of middle rung.
6, 76, 210, 100,
// front of bottom
6, 140, 210, 80,
// bottom
6, 90, 130, 110,
// left side
6, 160, 160, 220], [255]);
var numVerts = positions.length / 3;
var arrays = {
position: createAugmentedTypedArray(3, numVerts),
texcoord: createAugmentedTypedArray(2, numVerts),
normal: createAugmentedTypedArray(3, numVerts),
color: createAugmentedTypedArray(4, numVerts, Uint8Array),
indices: createAugmentedTypedArray(3, numVerts / 3, Uint16Array)
};
arrays.position.push(positions);
arrays.texcoord.push(texcoords);
arrays.normal.push(normals);
arrays.color.push(colors);
for (var ii = 0; ii < numVerts; ++ii) {
arrays.indices.push(ii);
}
return arrays;
}
/**
* Creates cresent BufferInfo.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} verticalRadius The vertical radius of the cresent.
* @param {number} outerRadius The outer radius of the cresent.
* @param {number} innerRadius The inner radius of the cresent.
* @param {number} thickness The thickness of the cresent.
* @param {number} subdivisionsDown number of steps around the cresent.
* @param {number} subdivisionsThick number of vertically on the cresent.
* @param {number} [startOffset] Where to start arc. Default 0.
* @param {number} [endOffset] Where to end arg. Default 1.
* @return {module:twgl.BufferInfo} The created BufferInfo.
* @memberOf module:twgl/primitives
* @function createCresentBufferInfo
*/
/**
* Creates cresent buffers.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} verticalRadius The vertical radius of the cresent.
* @param {number} outerRadius The outer radius of the cresent.
* @param {number} innerRadius The inner radius of the cresent.
* @param {number} thickness The thickness of the cresent.
* @param {number} subdivisionsDown number of steps around the cresent.
* @param {number} subdivisionsThick number of vertically on the cresent.
* @param {number} [startOffset] Where to start arc. Default 0.
* @param {number} [endOffset] Where to end arg. Default 1.
* @return {Object.<string, WebGLBuffer>} The created buffers.
* @memberOf module:twgl/primitives
* @function createCresentBuffers
*/
/**
* Creates cresent vertices.
*
* @param {number} verticalRadius The vertical radius of the cresent.
* @param {number} outerRadius The outer radius of the cresent.
* @param {number} innerRadius The inner radius of the cresent.
* @param {number} thickness The thickness of the cresent.
* @param {number} subdivisionsDown number of steps around the cresent.
* @param {number} subdivisionsThick number of vertically on the cresent.
* @param {number} [startOffset] Where to start arc. Default 0.
* @param {number} [endOffset] Where to end arg. Default 1.
* @return {Object.<string, TypedArray>} The created vertices.
* @memberOf module:twgl/primitives
*/
function createCresentVertices(verticalRadius, outerRadius, innerRadius, thickness, subdivisionsDown, startOffset, endOffset) {
if (subdivisionsDown <= 0) {
throw Error('subdivisionDown must be > 0');
}
startOffset = startOffset || 0;
endOffset = endOffset || 1;
var subdivisionsThick = 2;
var offsetRange = endOffset - startOffset;
var numVertices = (subdivisionsDown + 1) * 2 * (2 + subdivisionsThick);
var positions = createAugmentedTypedArray(3, numVertices);
var normals = createAugmentedTypedArray(3, numVertices);
var texcoords = createAugmentedTypedArray(2, numVertices);
function lerp(a, b, s) {
return a + (b - a) * s;
}
function createArc(arcRadius, x, normalMult, normalAdd, uMult, uAdd) {
for (var z = 0; z <= subdivisionsDown; z++) {
var uBack = x / (subdivisionsThick - 1);
var v = z / subdivisionsDown;
var xBack = (uBack - 0.5) * 2;
var angle = (startOffset + v * offsetRange) * Math.PI;
var s = Math.sin(angle);
var c = Math.cos(angle);
var radius = lerp(verticalRadius, arcRadius, s);
var px = xBack * thickness;
var py = c * verticalRadius;
var pz = s * radius;
positions.push(px, py, pz);
var n = v3.add(v3.multiply([0, s, c], normalMult), normalAdd);
normals.push(n);
texcoords.push(uBack * uMult + uAdd, v);
}
}
// Generate the individual vertices in our vertex buffer.
for (var x = 0; x < subdivisionsThick; x++) {
var uBack = (x / (subdivisionsThick - 1) - 0.5) * 2;
createArc(outerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);
createArc(outerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 0);
createArc(innerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);
createArc(innerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 1);
}
// Do outer surface.
var indices = createAugmentedTypedArray(3, subdivisionsDown * 2 * (2 + subdivisionsThick), Uint16Array);
function createSurface(leftArcOffset, rightArcOffset) {
for (var z = 0; z < subdivisionsDown; ++z) {
// Make triangle 1 of quad.
indices.push(leftArcOffset + z + 0, leftArcOffset + z + 1, rightArcOffset + z + 0);
// Make triangle 2 of quad.
indices.push(leftArcOffset + z + 1, rightArcOffset + z + 1, rightArcOffset + z + 0);
}
}
var numVerticesDown = subdivisionsDown + 1;
// front
createSurface(numVerticesDown * 0, numVerticesDown * 4);
// right
createSurface(numVerticesDown * 5, numVerticesDown * 7);
// back
createSurface(numVerticesDown * 6, numVerticesDown * 2);
// left
createSurface(numVerticesDown * 3, numVerticesDown * 1);
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices
};
}
/**
* Creates cylinder BufferInfo. The cylinder will be created around the origin
* along the y-axis.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius Radius of cylinder.
* @param {number} height Height of cylinder.
* @param {number} radialSubdivisions The number of subdivisions around the cylinder.
* @param {number} verticalSubdivisions The number of subdivisions down the cylinder.
* @param {boolean} [topCap] Create top cap. Default = true.
* @param {boolean} [bottomCap] Create bottom cap. Default = true.
* @return {module:twgl.BufferInfo} The created BufferInfo.
* @memberOf module:twgl/primitives
* @function createCylinderBufferInfo
*/
/**
* Creates cylinder buffers. The cylinder will be created around the origin
* along the y-axis.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius Radius of cylinder.
* @param {number} height Height of cylinder.
* @param {number} radialSubdivisions The number of subdivisions around the cylinder.
* @param {number} verticalSubdivisions The number of subdivisions down the cylinder.
* @param {boolean} [topCap] Create top cap. Default = true.
* @param {boolean} [bottomCap] Create bottom cap. Default = true.
* @return {Object.<string, WebGLBuffer>} The created buffers.
* @memberOf module:twgl/primitives
* @function createCylinderBuffers
*/
/**
* Creates cylinder vertices. The cylinder will be created around the origin
* along the y-axis.
*
* @param {number} radius Radius of cylinder.
* @param {number} height Height of cylinder.
* @param {number} radialSubdivisions The number of subdivisions around the cylinder.
* @param {number} verticalSubdivisions The number of subdivisions down the cylinder.
* @param {boolean} [topCap] Create top cap. Default = true.
* @param {boolean} [bottomCap] Create bottom cap. Default = true.
* @return {Object.<string, TypedArray>} The created vertices.
* @memberOf module:twgl/primitives
*/
function createCylinderVertices(radius, height, radialSubdivisions, verticalSubdivisions, topCap, bottomCap) {
return createTruncatedConeVertices(radius, radius, height, radialSubdivisions, verticalSubdivisions, topCap, bottomCap);
}
/**
* Creates BufferInfo for a torus
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius radius of center of torus circle.
* @param {number} thickness radius of torus ring.
* @param {number} radialSubdivisions The number of subdivisions around the torus.
* @param {number} bodySubdivisions The number of subdivisions around the body torus.
* @param {boolean} [startAngle] start angle in radians. Default = 0.
* @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.
* @return {module:twgl.BufferInfo} The created BufferInfo.
* @memberOf module:twgl/primitives
* @function createTorusBufferInfo
*/
/**
* Creates buffers for a torus
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius radius of center of torus circle.
* @param {number} thickness radius of torus ring.
* @param {number} radialSubdivisions The number of subdivisions around the torus.
* @param {number} bodySubdivisions The number of subdivisions around the body torus.
* @param {boolean} [startAngle] start angle in radians. Default = 0.
* @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.
* @return {Object.<string, WebGLBuffer>} The created buffers.
* @memberOf module:twgl/primitives
* @function createTorusBuffers
*/
/**
* Creates vertices for a torus
*
* @param {number} radius radius of center of torus circle.
* @param {number} thickness radius of torus ring.
* @param {number} radialSubdivisions The number of subdivisions around the torus.
* @param {number} bodySubdivisions The number of subdivisions around the body torus.
* @param {boolean} [startAngle] start angle in radians. Default = 0.
* @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.
* @return {Object.<string, TypedArray>} The created vertices.
* @memberOf module:twgl/primitives
*/
function createTorusVertices(radius, thickness, radialSubdivisions, bodySubdivisions, startAngle, endAngle) {
if (radialSubdivisions < 3) {
throw Error('radialSubdivisions must be 3 or greater');
}
if (bodySubdivisions < 3) {
throw Error('verticalSubdivisions must be 3 or greater');
}
startAngle = startAngle || 0;
endAngle = endAngle || Math.PI * 2;
var range = endAngle - startAngle;
var radialParts = radialSubdivisions + 1;
var bodyParts = bodySubdivisions + 1;
var numVertices = radialParts * bodyParts;
var positions = createAugmentedTypedArray(3, numVertices);
var normals = createAugmentedTypedArray(3, numVertices);
var texcoords = createAugmentedTypedArray(2, numVertices);
var indices = createAugmentedTypedArray(3, radialSubdivisions * bodySubdivisions * 2, Uint16Array);
for (var slice = 0; slice < bodyParts; ++slice) {
var v = slice / bodySubdivisions;
var sliceAngle = v * Math.PI * 2;
var sliceSin = Math.sin(sliceAngle);
var ringRadius = radius + sliceSin * thickness;
var ny = Math.cos(sliceAngle);
var y = ny * thickness;
for (var ring = 0; ring < radialParts; ++ring) {
var u = ring / radialSubdivisions;
var ringAngle = startAngle + u * range;
var xSin = Math.sin(ringAngle);
var zCos = Math.cos(ringAngle);
var x = xSin * ringRadius;
var z = zCos * ringRadius;
var nx = xSin * sliceSin;
var nz = zCos * sliceSin;
positions.push(x, y, z);
normals.push(nx, ny, nz);
texcoords.push(u, 1 - v);
}
}
for (var slice = 0; slice < bodySubdivisions; ++slice) {
// eslint-disable-line
for (var ring = 0; ring < radialSubdivisions; ++ring) {
// eslint-disable-line
var nextRingIndex = 1 + ring;
var nextSliceIndex = 1 + slice;
indices.push(radialParts * slice + ring, radialParts * nextSliceIndex + ring, radialParts * slice + nextRingIndex);
indices.push(radialParts * nextSliceIndex + ring, radialParts * nextSliceIndex + nextRingIndex, radialParts * slice + nextRingIndex);
}
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices
};
}
/**
* Creates a disc BufferInfo. The disc will be in the xz plane, centered at
* the origin. When creating, at least 3 divisions, or pie
* pieces, need to be specified, otherwise the triangles making
* up the disc will be degenerate. You can also specify the
* number of radial pieces `stacks`. A value of 1 for
* stacks will give you a simple disc of pie pieces. If you
* want to create an annulus you can set `innerRadius` to a
* value > 0. Finally, `stackPower` allows you to have the widths
* increase or decrease as you move away from the center. This
* is particularly useful when using the disc as a ground plane
* with a fixed camera such that you don't need the resolution
* of small triangles near the perimeter. For example, a value
* of 2 will produce stacks whose ouside radius increases with
* the square of the stack index. A value of 1 will give uniform
* stacks.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius Radius of the ground plane.
* @param {number} divisions Number of triangles in the ground plane (at least 3).
* @param {number} [stacks] Number of radial divisions (default=1).
* @param {number} [innerRadius] Default 0.
* @param {number} [stackPower] Power to raise stack size to for decreasing width.
* @return {module:twgl.BufferInfo} The created BufferInfo.
* @memberOf module:twgl/primitives
* @function createDiscBufferInfo
*/
/**
* Creates disc buffers. The disc will be in the xz plane, centered at
* the origin. When creating, at least 3 divisions, or pie
* pieces, need to be specified, otherwise the triangles making
* up the disc will be degenerate. You can also specify the
* number of radial pieces `stacks`. A value of 1 for
* stacks will give you a simple disc of pie pieces. If you
* want to create an annulus you can set `innerRadius` to a
* value > 0. Finally, `stackPower` allows you to have the widths
* increase or decrease as you move away from the center. This
* is particularly useful when using the disc as a ground plane
* with a fixed camera such that you don't need the resolution
* of small triangles near the perimeter. For example, a value
* of 2 will produce stacks whose ouside radius increases with
* the square of the stack index. A value of 1 will give uniform
* stacks.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext.
* @param {number} radius Radius of the ground plane.
* @param {number} divisions Number of triangles in the ground plane (at least 3).
* @param {number} [stacks] Number of radial divisions (default=1).
* @param {number} [innerRadius] Default 0.
* @param {number} [stackPower] Power to raise stack size to for decreasing width.
* @return {Object.<string, WebGLBuffer>} The created buffers.
* @memberOf module:twgl/primitives
* @function createDiscBuffers
*/
/**
* Creates disc vertices. The disc will be in the xz plane, centered at
* the origin. When creating, at least 3 divisions, or pie
* pieces, need to be specified, otherwise the triangles making
* up the disc will be degenerate. You can also specify the
* number of radial pieces `stacks`. A value of 1 for
* stacks will give you a simple disc of pie pieces. If you
* want to create an annulus you can set `innerRadius` to a
* value > 0. Finally, `stackPower` allows you to have the widths
* increase or decrease as you move away from the center. This
* is particularly useful when using the disc as a ground plane
* with a fixed camera such that you don't need the resolution
* of small triangles near the perimeter. For example, a value
* of 2 will produce stacks whose ouside radius increases with
* the square of the stack index. A value of 1 will give uniform
* stacks.
*
* @param {number} radius Radius of the ground plane.
* @param {number} divisions Number of triangles in the ground plane (at least 3).
* @param {number} [stacks] Number of radial divisions (default=1).
* @param {number} [innerRadius] Default 0.
* @param {number} [stackPower] Power to raise stack size to for decreasing width.
* @return {Object.<string, TypedArray>} The created vertices.
* @memberOf module:twgl/primitives
*/
function createDiscVertices(radius, divisions, stacks, innerRadius, stackPower) {
if (divisions < 3) {
throw Error('divisions must be at least 3');
}
stacks = stacks ? stacks : 1;
stackPower = stackPower ? stackPower : 1;
innerRadius = innerRadius ? innerRadius : 0;
// Note: We don't share the center vertex because that would
// mess up texture coordinates.
var numVertices = (divisions + 1) * (stacks + 1);
var positions = createAugmentedTypedArray(3, numVertices);
var normals = createAugmentedTypedArray(3, numVertices);
var texcoords = createAugmentedTypedArray(2, numVertices);
var indices = createAugmentedTypedArray(3, stacks * divisions * 2, Uint16Array);
var firstIndex = 0;
var radiusSpan = radius - innerRadius;
var pointsPerStack = divisions + 1;
// Build the disk one stack at a time.
for (var stack = 0; stack <= stacks; ++stack) {
var stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower);
for (var i = 0; i <= divisions; ++i) {
var theta = 2.0 * Math.PI * i / divisions;
var x = stackRadius * Math.cos(theta);
var z = stackRadius * Math.sin(theta);
positions.push(x, 0, z);
normals.push(0, 1, 0);
texcoords.push(1 - i / divisions, stack / stacks);
if (stack > 0 && i !== divisions) {
// a, b, c and d are the indices of the vertices of a quad. unless
// the current stack is the one closest to the center, in which case
// the vertices a and b connect to the center vertex.
var a = firstIndex + (i + 1);
var b = firstIndex + i;
var c = firstIndex + i - pointsPerStack;
var d = firstIndex + (i + 1) - pointsPerStack;
// Make a quad of the vertices a, b, c, d.
indices.push(a, b, c);
indices.push(a, c, d);
}
}
firstIndex += divisions + 1;
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices
};
}
/**
* creates a random integer between 0 and range - 1 inclusive.
* @param {number} range
* @return {number} random value between 0 and range - 1 inclusive.
*/
function randInt(range) {
return Math.random() * range | 0;
}
/**
* Used to supply random colors
* @callback RandomColorFunc
* @param {number} ndx index of triangle/quad if unindexed or index of vertex if indexed
* @param {number} channel 0 = red, 1 = green, 2 = blue, 3 = alpha
* @return {number} a number from 0 to 255
* @memberOf module:twgl/primitives
*/
/**
* @typedef {Object} RandomVerticesOptions
* @property {number} [vertsPerColor] Defaults to 3 for non-indexed vertices
* @property {module:twgl/primitives.RandomColorFunc} [rand] A function to generate random numbers
* @memberOf module:twgl/primitives
*/
/**
* Creates an augmentedTypedArray of random vertex colors.
* If the vertices are indexed (have an indices array) then will
* just make random colors. Otherwise assumes they are triangles
* and makes one random color for every 3 vertices.
* @param {Object.<string, augmentedTypedArray>} vertices Vertices as returned from one of the createXXXVertices functions.
* @param {module:twgl/primitives.RandomVerticesOptions} [options] options.
* @return {Object.<string, augmentedTypedArray>} same vertices as passed in with `color` added.
* @memberOf module:twgl/primitives
*/
function makeRandomVertexColors(vertices, options) {
options = options || {};
var numElements = vertices.position.numElements;
var vcolors = createAugmentedTypedArray(4, numElements, Uint8Array);
var rand = options.rand || function (ndx, channel) {
return channel < 3 ? randInt(256) : 255;
};
vertices.color = vcolors;
if (vertices.indices) {
// just make random colors if index
for (var ii = 0; ii < numElements; ++ii) {
vcolors.push(rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3));
}
} else {
// make random colors per triangle
var numVertsPerColor = options.vertsPerColor || 3;
var numSets = numElements / numVertsPerColor;
for (var ii = 0; ii < numSets; ++ii) {
// eslint-disable-line
var color = [rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3)];
for (var jj = 0; jj < numVertsPerColor; ++jj) {
vcolors.push(color);
}
}
}
return vertices;
}
/**
* creates a function that calls fn to create vertices and then
* creates a buffers for them
*/
function createBufferFunc(fn) {
return function (gl) {
var arrays = fn.apply(this, Array.prototype.slice.call(arguments, 1));
return attributes.createBuffersFromArrays(gl, arrays);
};
}
/**
* creates a function that calls fn to create vertices and then
* creates a bufferInfo object for them
*/
function createBufferInfoFunc(fn) {
return function (gl) {
var arrays = fn.apply(null, Array.prototype.slice.call(arguments, 1));
return attributes.createBufferInfoFromArrays(gl, arrays);
};
}
var arraySpecPropertyNames = ["numComponents", "size", "type", "normalize", "stride", "offset", "attrib", "name", "attribName"];
/**
* Copy elements from one array to another
*
* @param {Array|TypedArray} src source array
* @param {Array|TypedArray} dst dest array
* @param {number} dstNdx index in dest to copy src
* @param {number} [offset] offset to add to copied values
*/
function copyElements(src, dst, dstNdx, offset) {
offset = offset || 0;
var length = src.length;
for (var ii = 0; ii < length; ++ii) {
dst[dstNdx + ii] = src[ii] + offset;
}
}
/**
* Creates an array of the same time
*
* @param {(number[]|ArrayBuffer|module:twgl.FullArraySpec)} srcArray array who's type to copy
* @param {number} length size of new array
* @return {(number[]|ArrayBuffer|module:twgl.FullArraySpec)} array with same type as srcArray
*/
function createArrayOfSameType(srcArray, length) {
var arraySrc = getArray(srcArray);
var newArray = new arraySrc.constructor(length);
var newArraySpec = newArray;
// If it appears to have been augmented make new one augemented
if (arraySrc.numComponents && arraySrc.numElements) {
augmentTypedArray(newArray, arraySrc.numComponents);
}
// If it was a fullspec make new one a fullspec
if (srcArray.data) {
newArraySpec = {
data: newArray
};
utils.copyNamedProperties(arraySpecPropertyNames, srcArray, newArraySpec);
}
return newArraySpec;
}
/**
* Concatinates sets of vertices
*
* Assumes the vertices match in composition. For example
* if one set of vertices has positions, normals, and indices
* all sets of vertices must have positions, normals, and indices
* and of the same type.
*
* Example:
*
* var cubeVertices = twgl.primtiives.createCubeVertices(2);
* var sphereVertices = twgl.primitives.createSphereVertices(1, 10, 10);
* // move the sphere 2 units up
* twgl.primitives.reorientVertices(
* sphereVertices, twgl.m4.translation([0, 2, 0]));
* // merge the sphere with the cube
* var cubeSphereVertices = twgl.primitives.concatVertices(
* [cubeVertices, sphereVertices]);
* // turn them into WebGL buffers and attrib data
* var bufferInfo = twgl.createBufferInfoFromArrays(gl, cubeSphereVertices);
*
* @param {module:twgl.Arrays[]} arrays Array of arrays of vertices
* @return {module:twgl.Arrays} The concatinated vertices.
* @memberOf module:twgl/primitives
*/
function concatVertices(arrayOfArrays) {
var names = {};
var baseName;
// get names of all arrays.
// and numElements for each set of vertices
for (var ii = 0; ii < arrayOfArrays.length; ++ii) {
var arrays = arrayOfArrays[ii];
Object.keys(arrays).forEach(function (name) {
// eslint-disable-line
if (!names[name]) {
names[name] = [];
}
if (!baseName && name !== 'indices') {
baseName = name;
}
var arrayInfo = arrays[name];
var numComponents = getNumComponents(arrayInfo, name);
var array = getArray(arrayInfo);
var numElements = array.length / numComponents;
names[name].push(numElements);
});
}
// compute length of combined array
// and return one for reference
function getLengthOfCombinedArrays(name) {
var length = 0;
var arraySpec;
for (var ii = 0; ii < arrayOfArrays.length; ++ii) {
var arrays = arrayOfArrays[ii];
var arrayInfo = arrays[name];
var array = getArray(arrayInfo);
length += array.length;
if (!arraySpec || arrayInfo.data) {
arraySpec = arrayInfo;
}
}
return {
length: length,
spec: arraySpec
};
}
function copyArraysToNewArray(name, base, newArray) {
var baseIndex = 0;
var offset = 0;
for (var ii = 0; ii < arrayOfArrays.length; ++ii) {
var arrays = arrayOfArrays[ii];
var arrayInfo = arrays[name];
var array = getArray(arrayInfo);
if (name === 'indices') {
copyElements(array, newArray, offset, baseIndex);
baseIndex += base[ii];
} else {
copyElements(array, newArray, offset);
}
offset += array.length;
}
}
var base = names[baseName];
var newArrays = {};
Object.keys(names).forEach(function (name) {
var info = getLengthOfCombinedArrays(name);
var newArraySpec = createArrayOfSameType(info.spec, info.length);
copyArraysToNewArray(name, base, getArray(newArraySpec));
newArrays[name] = newArraySpec;
});
return newArrays;
}
/**
* Creates a duplicate set of vertices
*
* This is useful for calling reorientVertices when you
* also want to keep the original available
*
* @param {module:twgl.Arrays} arrays of vertices
* @return {module:twgl.Arrays} The dupilicated vertices.
* @memberOf module:twgl/primitives
*/
function duplicateVertices(arrays) {
var newArrays = {};
Object.keys(arrays).forEach(function (name) {
var arraySpec = arrays[name];
var srcArray = getArray(arraySpec);
var newArraySpec = createArrayOfSameType(arraySpec, srcArray.length);
copyElements(srcArray, getArray(newArraySpec), 0);
newArrays[name] = newArraySpec;
});
return newArrays;
}
// Using quotes prevents Uglify from changing the names.
// No speed diff AFAICT.
return {
"create3DFBufferInfo": createBufferInfoFunc(create3DFVertices),
"create3DFBuffers": createBufferFunc(create3DFVertices),
"create3DFVertices": create3DFVertices,
"createAugmentedTypedArray": createAugmentedTypedArray,
"createCubeBufferInfo": createBufferInfoFunc(createCubeVertices),
"createCubeBuffers": createBufferFunc(createCubeVertices),
"createCubeVertices": createCubeVertices,
"createPlaneBufferInfo": createBufferInfoFunc(createPlaneVertices),
"createPlaneBuffers": createBufferFunc(createPlaneVertices),
"createPlaneVertices": createPlaneVertices,
"createSphereBufferInfo": createBufferInfoFunc(createSphereVertices),
"createSphereBuffers": createBufferFunc(createSphereVertices),
"createSphereVertices": createSphereVertices,
"createTruncatedConeBufferInfo": createBufferInfoFunc(createTruncatedConeVertices),
"createTruncatedConeBuffers": createBufferFunc(createTruncatedConeVertices),
"createTruncatedConeVertices": createTruncatedConeVertices,
"createXYQuadBufferInfo": createBufferInfoFunc(createXYQuadVertices),
"createXYQuadBuffers": createBufferFunc(createXYQuadVertices),
"createXYQuadVertices": createXYQuadVertices,
"createCresentBufferInfo": createBufferInfoFunc(createCresentVertices),
"createCresentBuffers": createBufferFunc(createCresentVertices),
"createCresentVertices": createCresentVertices,
"createCylinderBufferInfo": createBufferInfoFunc(createCylinderVertices),
"createCylinderBuffers": createBufferFunc(createCylinderVertices),
"createCylinderVertices": createCylinderVertices,
"createTorusBufferInfo": createBufferInfoFunc(createTorusVertices),
"createTorusBuffers": createBufferFunc(createTorusVertices),
"createTorusVertices": createTorusVertices,
"createDiscBufferInfo": createBufferInfoFunc(createDiscVertices),
"createDiscBuffers": createBufferFunc(createDiscVertices),
"createDiscVertices": createDiscVertices,
"deindexVertices": deindexVertices,
"flattenNormals": flattenNormals,
"makeRandomVertexColors": makeRandomVertexColors,
"reorientDirections": reorientDirections,
"reorientNormals": reorientNormals,
"reorientPositions": reorientPositions,
"reorientVertices": reorientVertices,
"concatVertices": concatVertices,
"duplicateVertices": duplicateVertices
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }
/******/ ])
});
; |
'use strict';
function enumerate(values, prefix) {
prefix = prefix == null ? '' : prefix;
return values.reduce(function (enumeration, value) {
enumeration[value] = prefix + value;
return enumeration;
}, {});
}
module.exports = enumerate;
|
'use strict'
/**
* Internal event constructor
*/
var ConnexionEvent = function (origin) {
this.emitter = origin && origin.emitter || ''
this.scope = origin && origin.scope || ''
this.type = (origin && origin.type) || '*'
this.timeStamp = (origin && ('timeStamp' in origin)) ? origin.timeStamp : new Date().getTime()
this.detail = origin && origin.detail
this.detail = (this.detail && typeof this.detail === 'object') ? this.detail : {}
}
//export
module.exports = ConnexionEvent |
'use strict';
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var Promise = require('rsvp').Promise;
var Plugin = require('broccoli-plugin');
var walkSync = require('walk-sync');
var mapSeries = require('promise-map-series');
var symlinkOrCopySync = require('symlink-or-copy').sync;
var debugGenerator = require('heimdalljs-logger');
var md5Hex = require('md5-hex');
var Processor = require('./lib/processor');
var defaultProccessor = require('./lib/strategies/default');
var hashForDep = require('hash-for-dep');
var BlankObject = require('blank-object');
var FSTree = require('fs-tree-diff');
var heimdall = require('heimdalljs');
function ApplyPatchesSchema() {
this.mkdir = 0;
this.rmdir = 0;
this.unlink = 0;
this.change = 0;
this.create = 0;
this.other = 0;
this.processed = 0;
this.linked = 0;
this.processString = 0;
this.processStringTime = 0;
this.persistentCacheHit = 0;
this.persistentCachePrime = 0;
}
function DerivePatchesSchema() {
this.patches = 0;
this.entries = 0;
}
module.exports = Filter;
Filter.prototype = Object.create(Plugin.prototype);
Filter.prototype.constructor = Filter;
function Filter(inputTree, options) {
if (!this || !(this instanceof Filter) ||
Object.getPrototypeOf(this) === Filter.prototype) {
throw new TypeError('Filter is an abstract class and must be sub-classed');
}
var loggerName = 'broccoli-persistent-filter:' + (this.constructor.name);
var annotation = (options && options.annotation) || this.annotation || this.description;
if (annotation) {
loggerName += ' > [' + annotation + ']';
}
this._logger = debugGenerator(loggerName);
Plugin.call(this, [inputTree], {
name: (options && options.name) || this.name || loggerName,
annotation: (options && options.annotation) || this.annotation || annotation,
persistentOutput: true
});
this.processor = new Processor(options);
this.processor.setStrategy(defaultProccessor);
this.currentTree = new FSTree();
/* Destructuring assignment in node 0.12.2 would be really handy for this! */
if (options) {
if (options.extensions != null) this.extensions = options.extensions;
if (options.targetExtension != null) this.targetExtension = options.targetExtension;
if (options.inputEncoding != null) this.inputEncoding = options.inputEncoding;
if (options.outputEncoding != null) this.outputEncoding = options.outputEncoding;
if (options.persist) {
this.processor.setStrategy(require('./lib/strategies/persistent'));
}
}
this.processor.init(this);
this._canProcessCache = new BlankObject();
this._destFilePathCache = new BlankObject();
}
function nanosecondsSince(time) {
var delta = process.hrtime(time);
return delta[0] * 1e9 + delta[1];
}
function timeSince(time) {
var deltaNS = nanosecondsSince(time);
return (deltaNS / 1e6).toFixed(2) +' ms';
}
Filter.prototype.build = function() {
var srcDir = this.inputPaths[0];
var destDir = this.outputPath;
var prevTime = process.hrtime();
var instrumentation = heimdall.start('derivePatches', DerivePatchesSchema);
var walkStart = process.hrtime();
var entries = walkSync.entries(srcDir);
var walkDuration = timeSince(walkStart);
var nextTree = new FSTree.fromEntries(entries);
var currentTree = this.currentTree;
this.currentTree = nextTree;
var patches = currentTree.calculatePatch(nextTree);
instrumentation.stats.patches = patches.length;
instrumentation.stats.entries = entries.length;
instrumentation.stats.walk = {
entries: entries.length,
duration: walkDuration
};
this._logger.info('derivePatches', 'duration:', timeSince(prevTime), JSON.stringify(instrumentation.stats));
instrumentation.stop();
return heimdall.node('applyPatches', ApplyPatchesSchema, function(instrumentation) {
var prevTime = process.hrtime();
var result = mapSeries(patches, function(patch) {
var operation = patch[0];
var relativePath = patch[1];
var entry = patch[2];
var outputPath = destDir + '/' + (this.getDestFilePath(relativePath) || relativePath);
var outputFilePath = outputPath;
this._logger.debug('[operation:%s] %s', operation, relativePath);
switch (operation) {
case 'mkdir': {
instrumentation.mkdir++;
return fs.mkdirSync(outputPath);
} case 'rmdir': {
instrumentation.rmdir++;
return fs.rmdirSync(outputPath);
} case 'unlink': {
instrumentation.unlink++;
return fs.unlinkSync(outputPath);
} case 'change': {
instrumentation.change++;
return this._handleFile(relativePath, srcDir, destDir, entry, outputFilePath, true, instrumentation);
} case 'create': {
instrumentation.create++;
return this._handleFile(relativePath, srcDir, destDir, entry, outputFilePath, false, instrumentation);
} default: {
instrumentation.other++;
}
}
}, this);
this._logger.info('applyPatches', 'duration:', timeSince(prevTime), JSON.stringify(instrumentation));
return result;
}, this);
};
Filter.prototype._handleFile = function(relativePath, srcDir, destDir, entry, outputPath, isChange, instrumentation) {
if (this.canProcessFile(relativePath)) {
instrumentation.processed++;
return this.processAndCacheFile(srcDir, destDir, entry, isChange, instrumentation);
} else {
instrumentation.linked++;
if (isChange) {
fs.unlinkSync(outputPath);
}
var srcPath = srcDir + '/' + relativePath;
return symlinkOrCopySync(srcPath, outputPath);
}
};
/*
The cache key to be used for this plugins set of dependencies. By default
a hash is created based on `package.json` and nested dependencies.
Implement this to customize the cache key (for example if you need to
account for non-NPM dependencies).
@public
@method cacheKey
@returns {String}
*/
Filter.prototype.cacheKey = function() {
return hashForDep(this.baseDir());
};
/* @public
*
* @method baseDir
* @returns {String} absolute path to the root of the filter...
*/
Filter.prototype.baseDir = function() {
throw Error('Filter must implement prototype.baseDir');
};
/**
* @public
*
* optionally override this to build a more rhobust cache key
* @param {String} string The contents of a file that is being processed
* @return {String} A cache key
*/
Filter.prototype.cacheKeyProcessString = function(string, relativePath) {
return md5Hex(string + 0x00 + relativePath);
};
Filter.prototype.canProcessFile =
function canProcessFile(relativePath) {
return !!this.getDestFilePath(relativePath);
};
Filter.prototype.getDestFilePath = function(relativePath) {
if (this.extensions == null) {
return relativePath;
}
for (var i = 0, ii = this.extensions.length; i < ii; ++i) {
var ext = this.extensions[i];
if (relativePath.slice(-ext.length - 1) === '.' + ext) {
if (this.targetExtension != null) {
relativePath = relativePath.slice(0, -ext.length) + this.targetExtension;
}
return relativePath;
}
}
return null;
};
Filter.prototype.processAndCacheFile = function(srcDir, destDir, entry, isChange, instrumentation) {
var filter = this;
var relativePath = entry.relativePath;
return Promise.resolve().
then(function asyncProcessFile() {
return filter.processFile(srcDir, destDir, relativePath, isChange, instrumentation);
}).
then(undefined,
// TODO(@caitp): error wrapper is for API compat, but is not particularly
// useful.
// istanbul ignore next
function asyncProcessFileErrorWrapper(e) {
if (typeof e !== 'object') e = new Error('' + e);
e.file = relativePath;
e.treeDir = srcDir;
throw e;
});
};
function invoke(context, fn, args) {
return new Promise(function(resolve) {
resolve(fn.apply(context, args));
});
}
Filter.prototype.processFile = function(srcDir, destDir, relativePath, isChange, instrumentation) {
var filter = this;
var inputEncoding = this.inputEncoding;
var outputEncoding = this.outputEncoding;
if (inputEncoding === undefined) inputEncoding = 'utf8';
if (outputEncoding === undefined) outputEncoding = 'utf8';
var contents = fs.readFileSync(srcDir + '/' + relativePath, {
encoding: inputEncoding
});
instrumentation.processString++;
var processStringStart = process.hrtime();
var string = invoke(this.processor, this.processor.processString, [this, contents, relativePath, instrumentation]);
return string.then(function asyncOutputFilteredFile(outputString) {
instrumentation.processStringTime += nanosecondsSince(processStringStart);
var outputPath = filter.getDestFilePath(relativePath);
if (outputPath == null) {
throw new Error('canProcessFile("' + relativePath +
'") is true, but getDestFilePath("' +
relativePath + '") is null');
}
outputPath = destDir + '/' + outputPath;
if (isChange) {
var isSame = fs.readFileSync(outputPath, 'UTF-8') === outputString;
if (isSame) {
this._logger.debug('[change:%s] but was the same, skipping', relativePath, isSame);
return;
} else {
this._logger.debug('[change:%s] but was NOT the same, writing new file', relativePath);
}
}
try {
fs.writeFileSync(outputPath, outputString, {
encoding: outputEncoding
});
} catch(e) {
// optimistically assume the DIR was patched correctly
mkdirp.sync(path.dirname(outputPath));
fs.writeFileSync(outputPath, outputString, {
encoding: outputEncoding
});
}
return outputString;
}.bind(this));
};
Filter.prototype.processString = function(/* contents, relativePath */) {
throw new Error(
'When subclassing broccoli-persistent-filter you must implement the ' +
'`processString()` method.');
};
Filter.prototype.postProcess = function(result /*, relativePath */) {
return result;
};
|
module.exports = SoftSetHook;
function SoftSetHook(value) {
if (!(this instanceof SoftSetHook)) {
return new SoftSetHook(value);
}
this.value = value;
}
SoftSetHook.prototype.hook = function (node, propertyName) {
if (node[propertyName] !== this.value) {
node[propertyName] = this.value;
}
};
|
//= require jquery-ui
(function($) {
$(document).ready(function() {
$('.handle').closest('tbody').activeAdminSortable();
});
$.fn.activeAdminSortable = function() {
this.sortable({
update: function(event, ui) {
var url = ui.item.find('[data-sort-url]').data('sort-url');
$.ajax({
url: url,
type: 'post',
data: { position: ui.item.index() + 1 },
success: function() { window.location.reload() }
});
}
});
this.disableSelection();
}
})(jQuery);
|
/*------------------------------------------------------------------------------------
MSF Dashboard - dev-defined.js
(c) 2015-2017, MSF-Dashboard contributors for MSF
List of contributors: https://github.com/MSF-UK/MSF-Dashboard/graphs/contributors
Please refer to the LICENSE.md and LICENSES-DEP.md for complete licenses.
------------------------------------------------------------------------------------*/
/**
* This module contains the parameters of the dashboard that have to be defined by the developer in order to tailor the tool to the specific needs of the future users. In the following we will look at the parameters needed to:
* <ul>
* <li> design aspects of the dashboard layout</li>
* <li> get the medical and geometry data</li>
* <li> check the medical and geometry data</li>
* <li> define the charts and maps, feed them with the correct data and define specific interaction</li>
* </ul>
* All these parameters are defined in <code>dev/dev-defined.js</code> and are stored in the global variable <code>g</code>.
* <br><br>
* <code>g</code> stores other Objects as well that are not defined by the developer but that are the results of the processing and interactions. <code>g</code> can be accessed through your developer browser interface.
* <br><br>
* Along with <code>dev/dev-defined.js</code>, there are two other files that the developer must configure to create a new instance of the Dashboard. These are:
* <ul>
* <li> 'index.html' - this defines the divs and the positions of the charts and maps </li>
* <li> {@link module:module-lang} ('lang/module-lang.js') - this contains all the text displayed in the dashboard, including translations</li>
* </ul>
* @module g
* @since v0.9.0
* @requires lang/lang.js
* @todo Limit list of parameters in g.
* @todo Implement 'module_list' check to run or not the modules.
*/
/**
* @module dev_defined
*/
g.dev_defined = {};
/*------------------------------------------------------------------------------------
Components:
0) Design/layout parameters
1) Data parameters
2) Data check parameters
3) Charts parameters
------------------------------------------------------------------------------------*/
// 0) Design/layout parameters
//------------------------------------------------------------------------------------
/**
Defines whether or not the new layout structure is applied in the dashboard. This affects... <br>
<br>
* @constant
* @type {Boolean}
* @alias module:g.new_layout
*/
g.new_layout = true;
g.new_layout_params = {filterWindowAlwaysOn: true};
/**
* Stores the id of the div (as specified in index.html) that contains the buttons to toggle between charts (e.g. between Age Group and Year charts).
* <br> Used for {g.new_layout}.
* @type {String}
* @constant
* @alias module:module_chartwarper.container_btns_id
*/
if(!g.module_chartwarper){
g.module_chartwarper = {};
}
g.module_chartwarper.container_btns_id = 'container_ser_lin_btns';
/**
* Stores the id of the div (as specified in index.html) that contains all the charts to be toggled between (e.g. including Age Group and Year charts).
* <br> Used for {g.new_layout}.
* @type {String}
* @constant
* @alias module:module_chartwarper.container_allcharts_id
*/
g.module_chartwarper.container_allcharts_id = 'container_ser_lin';
/**
* Lists the divs (as specified in index.html) of the individual charts to be toggled between (e.g. Age Group and Year charts), and their corresponding heights.
* <br> Defined in {@link module:module_chartwarper}, used for {g.new_layout}.
* @type {Array<String>}
* @constant
* @alias module:module_chartwarper.container_chartlist
*/
g.module_chartwarper.container_chartlist = [{
container: 'container_ser_outer',
height: '600px'
},
{
container: 'container_lin_outer',
height: '400px'
}];
/**
* Defines the order of all intro (Help) windows. These can either be defined as the name of a chart or the name of a div (defined in index.html).
* For intro windows defined by a div, then its position must be defined in g.module_intro.intro_position.
* <br> Defined in {@link module:module_intro}, used for {g.new_layout}.
* @type {Array<String>}
* @constant
* @alias module:module_intro.intro_order
*/
if(!g.module_intro){
g.module_intro = {};
}
g.module_intro.intro_order = ['intro', 'menu', 'multiadm', 'disease', 'container_ser_lin', 'case_ser', 'case_lin', 'ser_range', 'fyo', 'year', 'table'];
/**
* Defines a list of div names used as intro (Help) windows, along with their position relative to the chart.
* <br> Defined in {@link module:module_intro}, used for {g.new_layout}.
* @type {Array<Object>}
* @constant
* @alias module:module_intro.intro_position
*/
g.module_intro.intro_position = [{container: 'container_ser_lin',
position: 'top'
}];
/**
* Defines a list of chart or div names used as intro (Help) windows, that require turning 'on' before its Help is opened to force it into view in case it was previously 'hidden'. Turning 'on' a chart of div requires a pre-specified button to be 'clicked', as defined by the click attribute.
* <br> Defined in {@link module:module_intro}, used for {g.new_layout}.
* <br> The buttons are defined in {@link module:module_chartwarper}.
* @type {Array<Object>}
* @constant
* @alias module:module_intro.intro_beforechange
*/
g.module_intro.intro_beforechange = [{
element: 'container_ser',
click: '#container_ser_outer-btn'
}, {
element: 'container_rangechart',
click: '#container_ser_outer-btn'
},{
element: 'container_ser_lin',
click: '#container_ser_outer-btn'
},{
element: 'chart-fyo',
click: '#container_ser_outer-btn'
},{
element: 'container_lin',
click: '#container_lin_outer-btn'
}]
/**
Defines the time (milliseconds) between each time increment when in 'Play' mode. Only required when a range_chart is implemented.
* @constant
* @type {Number}
* @alias module:g.dev_defined.autoplay_delay
*/
g.dev_defined.autoplay_delay = 2000;
/**
Defines whether at the end of the timeline, 'Play' mode continues to play from the beginning automatically. Only required when a range_chart is implemented.
* @constant
* @type {Boolean}
* @alias module:g.dev_defined.autoplay_rewind
*/
g.dev_defined.autoplay_rewind = false;
// 1) Data parameters
//------------------------------------------------------------------------------------
/**
Defines the type of medical data parsed in the dashboard. <br>
<br>
Currently accepted values are:
<ul>
<li><code>surveillance</code> (aggregated)</li>
<li><code>outbreak</code> (linelist)</li>
</ul>
* @constant
* @type {String}
* @alias module:g.medical_datatype
*/
g.medical_datatype = 'surveillance';
/**
Defines your incidence (and mortality) computation.
* @constant
* @type {Function}
* @param periode Number of epiweeks
* @alias module:dev_defined.definition_incidence
*/
g.dev_defined.definition_incidence = function(value,pop,periode) {
return value * 100000 / (pop * periode); //Note: periode = number of epiweeks
};
/**
Defines your completeness computation.
* @constant
* @type {Boolean}
* @alias module:dev_defined.ignore_empty
*/
g.dev_defined.ignore_empty = true;
/**
* Contains the list of implemented map units.
* <br> Defined in {@link module:module_colorscale}.
Currently accepted values are:
<ul>
<li><code>Cases</code></li>
<li><code>Deaths</code></li>
<li><code>IncidenceProp</code></li>
<li><code>MortalityProp</code></li>
<li><code>Completeness</code></li>
</ul>
* @type {Array.<String>}
* @constant
* @alias module:module_colorscale.mapunitlist
*/
if(!g.module_colorscale){
g.module_colorscale = {};
}
g.module_colorscale.mapunitlist = ['Cases', 'Deaths','IncidenceProp','MortalityProp','Completeness'];
/**
Defines a list of qualitative colors to be optionally used in charts.
* @constant
* @type {Array.<String>}
* @alias module:module_colorscale.userdefined_colors
*/
g.module_colorscale.userdefined_colors = ['#333333', '#17becf', '#bcbd22', '#428bca', '#f69318','#9467bd', '#1b9e77', '#bd1d02', '#66a61e'];
//grey, turquoise, lime green, blue, orange, purple, green, red, green
/**
Defines combinations of geometry buttons (defined by @link g.geometry_keylist) and map unit buttons (defined by @link module:module_colorscale.mapunitlist) that are not compatible.
For example, hospitals normally do not have incidence or mortality rates because they do not have an associated population number.
* @constant
* @type {Array.<Object>}
* @alias module:dev_defined.incompatible_buttons
*/
/*g.dev_defined.incompatible_buttons = [{unit: 'IncidenceProp',
geo: 'hosp'},
{unit: 'MortalityProp',
geo: 'hosp'
}]*/
//g.dev_defined.incompatible_buttons = [];
/**
Defines whether or not the new population format is used. The new format allows for the definition of multiple years of population numbers.
* @constant
* @type {Boolean}
* @alias module:module_population.pop_new_format
*/
if(!g.module_population){
g.module_population = {};
}
g.module_population.pop_new_format = true;
/**
Lists the keys used to refer to specific {@link module:g.population_data} fields. It makes the link between headers in the data files and unambiguous keys used in the code.<br>
* @constant
* @type {Object}
* @alias module:module_population.pop_headerlist
* @property {String} <code>admNx</code> - The administrative or medical division name, format: <code>Adm1_name, Adm2_name...</code>
* @property {Object} <code>pop</code> - The population numbers for each given year
* @property {Number} pop.header_in_datafile - The column header for a specified year in the data file, defining the associated year number
*/
g.module_population.pop_headerlist = {
admNx: 'name',
pop: {yr_2016: 2016,
yr_2017: 2017}
};
/**
Defines the percentage of the population that is assumed to be under 5yrs old.
* @constant
* @type {Number}
* @alias module:module_population.pop_new_format
*/
g.module_population.pop_perc_u5 = 18.9;
/**
Defines the percentage annual growth of the population for years for which no population data is available.
* @constant
* @type {Number}
* @alias module:module_population.pop_annual_growth
*/
g.module_population.pop_annual_growth = 3.0;
//**************************************************************************************
/**
* Defines the data parsed in the dashboard (urls and sources type). Order matters.<br>
* <br>
* Currently accepted methods are:
* <ul>
* <li><code>arcgis_api</code> (not published yet)</li>
* <li><code>kobo_api</code> (not published yet)</li>
* <li><code>d3</code></li>
* <li><code>medicald3server</code></li>
* <li><code>medicald3noserver</code></li>
* <li><code>geometryd3</code></li>
* <li><code>populationd3</code></li>
* <li><code>medicalxlsx</code></li>
* </ul>
* @constant
* @type {Object}
* @alias module:g.module_getdata
*/
g.module_getdata = {
geometry: { //these layers are displayed explicitly in the map
admN1: {
method: 'geometryd3',
options: { url: './data/geo_cod_adm1.geojson',
type: 'json'}
},
admN2: {
method: 'geometryd3',
options: { url: './data/geo_cod_adm2.geojson',
type: 'json'}
}
},
extralay:{ //these layer don't contain data so are only implicitly used for other purposes, e.g. masks, backgrounds, drawing
mask:{
method: 'd3',
options: { url: './data/geo_cod_adm1.geojson',
type: 'json'}
},
admN1:{
method: 'd3',
options: { url: './data/geo_cod_adm1.geojson',
type: 'json'}
},
},
geometry_altnames:{
alt: {
method: 'geonamescsv',
options: { url: './data/geo_altnames.csv',
type: 'csv'}
}
},
medical:{
/*medical: {
method: 'medicalxlsx',
options: { url: './input/',
type: 'xlsx'
}
}*/
medical: {
method: 'medicald3noserver',
options: { url: 'input/kere_demo_data.csv',
type: 'csv'
}
}
},
population:{
pop: {
method: 'populationd3',
options: { url: './data/kere_pop.csv',
type: 'csv'}
}
}
};
/**
Lists the keys used to refer to specific {@link module:g.medical_data} fields. It makes the link between headers in the data files and unambiguous keys used in the code.
Note that where two keys refer to the same header in the datafile, they are considered to 'share' the attribute between two different geometry layers. Both geometries must be defined and there <i>must</i> be an array defined in {@link module:g} that specifies the individual feature names to be used in one of them.
The extraction of some feature names from a shared attribute is defined in {@link module:module_datacheck.dataprocessing}
<br>
Each element in the object is coded in the following way:
<pre>*key_in_dashboard*: '*header_in_datafile*',</pre>
* @constant
* @type {Object}
* @alias module:g.medical_headerlist
**/
g.medical_headerlist = {
epiwk: 'epiweek', // Epidemiological week: format YYYY-WW
admN1: 'province', // Name of administrative/health division level N1
admN2: 'zone',
disease: 'disease',
fyo: 'fyo',
case: 'cas',
death: 'dec',
};
//If data comes from spreadsheet, not from data manager, then give column letter and optional parameter for each field
g.medical_headers_xlsx = {
epiwk: ['D', 'req'],
admN1: ['B', 'req'],
admN2: ['C', 'req'],
disease: ['F', 'req'],
case_u5: ['G', 'not_req'],
case_o5: ['I', 'not_req'],
death_u5: ['H', 'not_req'],
death_o5: ['J', 'not_req'],
}
/**
Defines individual feature names from a single geometry file (e.g. admN2) that should be applied to a different geometry (e.g. hosp). The array should be named 'g.data_spec.name' where 'name' is the name of the new layer as defined in g.medical_headerlist (e.g. hosp).
* @constant
* @type {Array.<{String}>}
* @alias module:g.data_spec.combine_data
*/
g.data_spec = {};
//g.data_spec.hosp = ["Masanga Leprosy Hospital", "Lion Heart Medical Hospital", "Magburaka Government Hospital"];
/**
Defines individual data records that should be added into a geometry with a different name. The admin level, or 'geo-level' must also be specified.
This allows for multiple named records to be summed into a single geometry.
* @constant
* @type {Array.<{geo_level: String, geo_name: String, add_into: String}>}
* @alias module:g.data_spec.combine_data
*/
/*g.data_spec.combine_data = [{
geo_level: 'admN2',
geo_name: 'Magburaka Under Five Clinic',
add_into: 'Magburaka MCHP'
},{
geo_level: 'admN2',
geo_name: 'Magboki Road Mile 91 CHP',
add_into: 'Esthers/Magboki Road Mile 91 CHP'
}];*/
/**
Defines the relationship between each map layer using a tree-structured numbering system. Top layers are defined as integers, while child layers are defined by their parental 'branch' followed by their own unique integer. Distinction between levels are made by '.'. If multiple layers have the same parent, then they are siblings.
* @constant
* @type {Object}
* @alias module:g.viz_layer_pos
*/
g.viz_layer_pos = {admN1: '0', // 0 = top layer
admN2: '0.1', // 0.1 = child of 0, sibling to 0.2
//hosp: '0.2' // 0.2 = child of 0, sibling to 0.1
};
function main_loadfiles_readvar(){ //re-loads variables that require g.module_lang.current - in case user changes language from default
/**
Lists the keys from {@link module:g.medical_headerlist} that require custom parsing (eg. translate numbers into words).<br>
Each element in the object is coded in the following way:
<pre>*key_in_dashboard*: {*category1_in_medicaldata*: '*user-readable_output1*', *category2_in_medicaldata*: '*user-readable_output2*', ...},</pre>
* @constant
* @type {Object.<String, Object>}
* @alias module:g.medical_read
* @todo Why is it in a function?
*/
g.medical_read = {
fyo: {
u:g.module_lang.text[g.module_lang.current].chart_fyo_labelu,
o:g.module_lang.text[g.module_lang.current].chart_fyo_labelo,
a:g.module_lang.text[g.module_lang.current].chart_fyo_labela}
};
}
// 2) Data check parameters
//------------------------------------------------------------------------------------
/**
Associates keys from {@link module:g.medical_headerlist} with datacheck tests performed in {@link module:module_datacheck~dataprocessing} and defined in {@link module:module_datacheck~testvalue}.<br>
The elements are coded in the following way:
<pre>*key*: {test_type: '*test_name*', setup:'*additional_elements*'},</pre>
<br>
Currently implemented test_types are:
<ul>
<li><code>none</code> which does not check anything,</li>
<li><code>epiwk</code> which checks format is 'YYYY-WW',</li>
<li><code>ingeometry</code> which checks whether the location name in the {@link g.medical_data} matches any location name in the {@link g.geometry_data} of the same divisional level,</li>
<li><code>integer</code> which checks if the value is an integer,</li>
<li><code>inlist</code> which checks if the value is in a list (parsed in <code>setup</code>),</li>
<li><code>integer</code> which checks if the value is an integer.</li>
</ul>
* @constant
* @type {Object.<String, Object>}
* @alias module:module_datacheck.definition_value
* @todo Should maybe merged with merged with {@link module:g.medical_read}.
*/
if(!g.module_datacheck){
g.module_datacheck = {};
}
g.module_datacheck.definition_value = {
epiwk: {test_type: 'epiwk', setup: 'none'}, // Epidemiological week: format YYYY-WW
admN1: {test_type: 'ingeometry', setup: 'normalize'}, // Name of division level N1
admN2: {test_type: 'ingeometry', setup: 'normalize'}, // Name of division level
fyo:{test_type: 'inlist', setup: ["u","o"]}, // Depends on data source
/*case_u5: {test_type: 'integer', setup: 'none'},
case_o5: {test_type: 'integer', setup: 'none'},
death_u5: {test_type: 'integer', setup: 'none'},
death_o5: {test_type: 'integer', setup: 'none'}, */
case: {test_type: 'integer', setup: 'none'},
death:{test_type: 'integer', setup: 'none'},
};
/**
* Defines an array of Disease to be used as an <code>inlist</code> check in {@link module:module_datacheck~dataprocessing}. In case the list of disease to follow is not predefined, an empty array must be parsed and the list of diseases will be created in {@link module:module_datacheck~dataprocessing}.
* @constant
* @type {Array.<String>}
* @alias module:g.medical_diseaseslist
*/
g.medical_diseaseslist = []; // Complete list of disease surveilled or left empty to build the list from data
/* g.medical_diseaselist_trans = {"Morsure de Serpent": 'Snake Bite', "Piqure de Scorpion": 'Scorpion Bite', "Suspicion de Paludisme": 'Suspected Malaria', "Paludisme Testes": 'Tested Malaria', "Paludisme Confirmé":'Confirmed Malaria', "PFA": 'Acute Flaccid Paralysis',
"Meningite": 'Meningitis', "TNN": 'Neonatal Tetanus', "Décès Maternels": 'Maternal Death', "Rougeole": 'Measles', "Fièvre Jaune": 'Yellow Fever',
"Malnutrition Sévère": 'Severe Malnutrition', "Malnutrition Modérée": 'Moderate Malnutrition', "Suspicions Hepatite E": 'Suspected Hepatitis E',
"Ver de Guinée": 'Guinea Worm', "Choléra": 'Cholera'};*/
// Define here the list of fields that are expected to constitute a unique identifier of a record
/**
Defines the list of fields that are expected to constitute a unique identifier of a record to be used in the errors log in {@link module:module_datacheck}.
The elements are coded in the following way:
<pre>{key: '*header_in_datafile*', isnumber: *boolean*},</pre>
* @constant
* @type {Array.<{key: String, isnumber: Boolean}>}
* @alias module:module_datacheck.definition_record
*/
g.module_datacheck.definition_record = [
{key: g.medical_headerlist.epiwk, isnumber: false}, // 'true' key as in data file
{key: g.medical_headerlist.disease, isnumber: false}, // 'true' key as in data file
{key: g.medical_headerlist.admN1, isnumber: false}, // 'true' key as in data file
{key: g.medical_headerlist.admN2, isnumber: false}, // 'true' key as in data file
{key: g.medical_headerlist.fyo, isnumber: false}, // 'true' key as in data file
];
//Define here list of adm name differences to be displayed on dashboard (e.g. if a district name has changed can keep a ref to old name)
/*g.geometry_altnames = [
{
data_name: 'Ennedi Ouest, Mourtcha',
display_name: 'Ennedi Ouest, Mourtcha (Kalaït)'
}, {
data_name: 'Logone Oriental, Baibokoum',
display_name: 'Logone Oriental, Baibokoum (Béssao)'
}
];*/
// 3) Chart parameters
//------------------------------------------------------------------------------------
/**
Lists the charts and maps to be produced by {@link module:main-core} as well as defines their main characteristics.<br>
Each element in the object contains the following sub-elements:
* ```
chart_id: {
// Defined by the developer:
domain_builder: {String}, // builds the domain for the chart - options include:'epiweek', 'date', 'date_extent', 'readcat', 'integer_ordinal', 'integer_linear', 'week', 'year', 'none',
domain_parameter: {String}, // domain parameter used to customize x axis scale types - options include: 'custom_ordinal' or 'custom_epitime_all' or 'custom_epitime_range' or 'custom_epitime_annual' or 'custom_log' or 'custom_date' or 'none'
instance_builder: {String}, // defines the dc chart type - 'bar' or 'multiadm' or 'row' or 'stackedbar' or 'pie' or 'composite' or 'series' or 'table',
dimension_builder: {String}, // builds the dimension for the chart - 'multiadm' or 'integer' or 'normalize' or 'year' or 'week' or 'week_num' or 'date' or 'epidate' or 'readcat' or 'auto' or 'readcat' or 'readncombcat'
dimension_parameter: {Object}, // defines the column to be used for building the dimension - if it is shared with other charts then a common 'namespace' is assigned
// @property {String} chart_id.dimension_parameter.column - Defines the column heading that is used for the dimension
// @property {Boolean} chart_id.dimension_parameter.shared - Defines whether or not there is a namespace shared with other charts
// @property {String} chart_id.dimension_parameter.namespace - If dimension_parameter.shared==true, a unique namespace for all charts that share this dimension must be given.
group_builder: {String}, // builds the group for the chart - 'multiadm' or 'stackedbar' or count' or 'auto' or 'series_age' or 'series_all' or 'series_yr' or 'none',
group_parameter: {Array}, // defines the columns to be used for building the group
range_chart: {Boolean}, // determines the chart used to filter by time using range handles; there should be no more than one range chart per dashboard
buttons_filt_range: {Array.<Object>}, // lists and defines the buttons to be used as quick filters for the epiweek range
// @property {String} buttons_filt_range[].btn_type - options include: 'lastXepiweeks', 'lastXepimonths', 'lastXepiyears'
// @property {Number} buttons_filt_range[].btn_param - defines the number of 'X' in the btn_type
// @property {String} buttons_filt_range[].btn_text - the text to be displayed on the butons
// @property {Boolean} buttons_filt_range[].btn_default - defines which button will be the default on loading
display_title: {Boolean}, // Defines whether or not to display individual chart titles (only for g.new_layout)
display_filter: {Boolean}, // Defines whether or not to display individual chart filters (not for g.new_layout)
display_axis: {Object}, // Defines the text to be used for x and y labels on x/y-type charts; y_imr is the y-label when looking at Incidence & Mortality rates; y_comp is the y-label when looking at Completeness
userdefined_colors: {Boolean}, // Defines whether to use the pre-specifieduser-defined colors for the chart (define by g.module_colorscale.userdefined_colors in module:dev_defined)
display_colors: {Array.<Integer>}, // Refers to colors in g.color_domain, or g.module_colorscale.userdefined_colors if userdefined_colors is 'true',
display_intro_position: {String}, // Determines the position of the Help window with respect to the chart or div it is describing - 'top' or 'bottom' or 'right' or 'left' or 'none',
display_intro_container: {String}, // Only required for referencing Help window to a div other than its own (e.g. an outer div to encompass buttons)
buttons_list: {Array.<String>}, // List of optional buttons to be included for each chart - ['reset','help']; 'multiadm' maps can additionally include 'expand','lockcolor' and 'parameters'
sync_to: {Array.<String>}, // ['chart_id's] - sync filtering with other charts; this is only used for stackedbar charts
// Processed by the dashboard:
chart: {Object}, // {@link module:main_core~instancBuilder} & {@link module:main_core~chartBuilder}
dimension: {Object}, // {@link module:main_core~dimensionBuilder}
domain: {Array}, // {@link module:main_core~domainBuilder}
group: {Object}, // {@link module:main_core~groupBuilder}
}
*```
<br>
Each element is detailed in the following.
* <ul>
<li><code>chart_id</code>, 'chart-'<code>chart_id</code> must match a <code>div id</code> in the *index.html* file (the dashboard layout).</li>
<li><code>domain_builder</code> Definitions in: {@link module:main_core~domainBuilder}.
<br>This selects the domain building method. Custom domains are built for all cases where code>domain_builder =/= 'none'</code>.</li>
<br>
<li><code>domain_parameter</code>
<br>This parameter is used to customize x axis scale types.</li>
<br>
<li><code>instance_builder</code> Definitions in: {@link module:main_core~instanceBuilder} and {@link module:main_core~chartBuilder}.</li>
<br>
<li><code>dimension_builder</code> Definitions in {@link module:main_core~dimensionBuilder}.</li>
<br>
<li><code>dimension_parameter</code>
<br>This parameter defines the column to be used for building the dimension.
<ul>
@property {String} dimension_parameter.column - Defines the column heading that is used for the dimension
@property {Boolean} dimension_parameter.shared - Defines whether or not there is a namespace shared with other charts
@property {String} dimension_parameter.namespace - If dimension_parameter.shared==true, a unique namespace for all charts that share this dimension must be given.
<li>If == <code>'auto'</code> - the dimension is assumed not to be shared - that means that <code>'auto'</code> is the dimension building method and <code>chart_id</code> is used to select the field to filter in {@link module:g.medical_data}.</li>
<li>If == <code>'custom'</code> - the dimension is assumed not to be shared - that means that <code>'chart_id'</code> is the dimension building method and it is used as well to select the field to filter in {@link module:g.medical_data} (when not overridden by the dimension builder definition).</li>
<li>If == <code>'shared'</code> - <code>dimension_setup</code> parameter is compulsory.
<ul>
<li><code>dimension_setup[0]</code> is the <code>chart_id</code> of the chart with which the dimension is shared or the common identifier for the dimension</li>
<li><code>dimension_setup[1]</code> can be <code>'auto'</code> or <code>'custom'</code> (just like a non-'shared' dimension...)
<ul>
<li>If == <code>'auto'</code> that means that <code>'auto'</code> is the dimension building method and <code>dimension_setup[0]</code> is used to select the field to filter in {@link module:g.medical_data}.</li>
<li>If == <code>'custom'</code> that means that <code>dimension_setup[0]</code> is the dimension building method and it is used as well to select the field to filter in {@link module:g.medical_data} (when not overridden by the dimension builder definition).</li>
</li>
</ul>
</li>
</ul>
Classical dimensions are stored under <code>[chart_id].dimension</code> in the {@link module:g.viz_definition} object. Whereas shared dimensions are stored under <code>[dimension_setup[0]].dimension</code>.
</li>
<br>
<li><code>group_type</code> Can be: 'auto' or 'custom' or 'shared' (or 'none' for the data table) - Definitions in {@link module:main_core~groupBuilder}.
<br>
<ul>
<li>If == <code>'auto'</code>, that means that <code>'auto'</code> is the group building method.</li>
<li>If == <code>'custom'</code>, that means that <code>'chart_type'</code> is the group building method.</li>
</ul>
Groups building instruction are specific to each {@link module:g.medical_datatype}.
If {@link module:g.medical_datatype} == <code>'surveillance'</code> - <code>group_setup</code> parameter is compulsory. It is an Array where:
<ul>
<li><code>group_setup[0]</code> is used to select the field to count or sum in {@link module:g.medical_data}. NB: In a <code>'outbreak'</code> setting, records are counted from the patient list without a reference to a field.</li>
<li><code>group_setup[1]</code> is used to select the field to create categories for stacked charts (<code>chart_type == stackedbar</code>. NB: Stacked chart have not been used yet in a <code>'outbreak'</code> setting.</li>
</ul>
</li>
* </ul>
* @constant
* @type {Object.<Object>}
* @alias module:g.viz_definition
**/
function main_loadfiles_readcharts(){ //re-loads variables that may require g.module_lang.current - in case user changes language from default
g.viz_definition = {
multiadm: { domain_builder: 'none',
domain_parameter: 'none',
instance_builder: 'multiadm',
dimension_builder: 'multiadm',
dimension_parameter: { column: 'none',
shared: false,
namespace: 'none'},
group_builder: 'multiadm',
group_parameter: { column: ['case','death']},
display_title: true,
display_colors: [0,1,2,3,4,5],
display_intro_position: 'bottom',
buttons_list: ['reset','help','expand','lockcolor','parameters'],
},
disease: { domain_builder: 'none',
domain_parameter: 'none',
instance_builder: 'row',
dimension_builder: 'normalize',
dimension_parameter: { column: 'disease',
shared: false,
namespace: 'none'},
group_builder: 'count',
group_parameter: { column: 'none'},
display_title: true,
display_axis: {x:g.module_lang.text[g.module_lang.current].chart_disease_labelx,
y:g.module_lang.text[g.module_lang.current].chart_disease_labely},
display_colors: [2],
display_focusrows: ['Cholera', 'Fievre Jaune', 'Fievre Hemmorragique Ebola', 'Meningite', 'Paludisme', 'Rougeole'], //these appear at top of row chart
display_intro_position: 'left',
buttons_list: ['help'],
},
case_ser: { domain_builder: 'date_extent',
domain_parameter: 'custom_epitime_range',
instance_builder: 'composite',
dimension_builder: 'epidate',
dimension_parameter: { column: 'epiwk',
shared: true,
namespace: 'epirange'},
group_builder: 'series_age',
group_parameter: { column: ['case','fyo']},
/*group_builder: 'series_all',
group_parameter: {column: ['case']},*/
display_title: false,
display_axis: {x:'',
y: g.module_lang.text[g.module_lang.current].chart_case_labely,
y_imr: g.module_lang.text[g.module_lang.current].chart_ir_labely,
y_comp: g.module_lang.text[g.module_lang.current].chart_comp_labely},
userdefined_colors: true,
display_colors: [0,1,2],
display_intro_position: 'top',
display_intro_container: 'container_ser',
buttons_list: ['help'],
},
death_ser: {domain_builder: 'date_extent',
domain_parameter: 'custom_epitime_range',
instance_builder: 'composite',
dimension_builder: 'epidate',
dimension_parameter: { column: 'epiwk',
shared: true,
namespace: 'epirange'},
group_builder: 'series_age',
group_parameter: { column: ['death','fyo']},
/*group_builder: 'series_all',
group_parameter: {column: ['death']},*/
display_title: false,
display_axis: {x:g.module_lang.text[g.module_lang.current].chart_death_labelx,
y:g.module_lang.text[g.module_lang.current].chart_death_labely,
y_imr: g.module_lang.text[g.module_lang.current].chart_mr_labely,
y_comp: g.module_lang.text[g.module_lang.current].chart_comp_labely},
userdefined_colors: true,
display_colors: [0,1,2],
display_intro_position: 'none',
buttons_list: ['help'],
},
ser_range: {domain_builder: 'date_extent',
domain_parameter: 'custom_epitime_all',
instance_builder: 'bar',
dimension_builder: 'epidate',
dimension_parameter: { column: 'epiwk',
shared: true,
namespace: 'epirange'},
group_builder: 'auto',
group_parameter: {column: ['case']},
range_chart: true,
buttons_filt_range: [{btn_type:'lastXepiweeks', btn_param: 1, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last1epiweeks}, //note all buttons are 'relative' time
{btn_type: 'lastXepiweeks', btn_param: 4, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last4epiweeks},
{btn_type: 'lastXepiweeks', btn_param: 52, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last52epiweeks, btn_default: true},
{btn_type: 'lastXepimonths', btn_param: 0, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last0epimonths}, //0 for current (possibly incomplete) epimonth
{btn_type: 'lastXepimonths', btn_param: 1, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last1epimonths},
{btn_type: 'lastXepimonths', btn_param: 3, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last3epimonths},
{btn_type: 'lastXepiyears', btn_param: 0, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last0epiyears}, //0 for current (possibly incomplete) epiyear
{btn_type: 'lastXepiyears', btn_param: 1, btn_text: g.module_lang.text[g.module_lang.current].qf_btns_last1epiyears}],
display_title: true,
display_axis: {x:'',
y:'',
y_imr: '',
y_comp: ''},
display_colors: [1],
display_intro_position: 'bottom',
display_intro_container: 'container_rangechart',
buttons_list: ['help'],
},
case_lin: {domain_builder: 'week',
domain_parameter: 'custom_epitime_annual',
instance_builder: 'composite',
dimension_builder: 'week_num',
dimension_parameter: { column: 'epiwk',
shared: true,
namespace: 'week'},
group_builder: 'series_yr',
group_parameter: { column: ['case','epiwk']},
display_title: false,
display_axis: {x:'',
y: g.module_lang.text[g.module_lang.current].chart_case_labely,
y_imr: g.module_lang.text[g.module_lang.current].chart_ir_labely,
y_comp: g.module_lang.text[g.module_lang.current].chart_comp_labely},
userdefined_colors: true,
display_colors: [3,4,5,6,7],
display_intro_position: 'top',
display_intro_container: 'container_lin',
buttons_list: ['help'],
},
death_lin: {domain_builder: 'week',
domain_parameter: 'custom_epitime_annual',
instance_builder: 'composite',
dimension_builder: 'week_num',
dimension_parameter: { column: 'epiwk',
shared: true,
namespace: 'week'},
group_builder: 'series_yr',
group_parameter: { column: ['death', 'epiwk']},
display_title: false,
display_axis: {x:g.module_lang.text[g.module_lang.current].chart_death_labelx,
y:g.module_lang.text[g.module_lang.current].chart_death_labely,
y_imr: g.module_lang.text[g.module_lang.current].chart_mr_labely,
y_comp: g.module_lang.text[g.module_lang.current].chart_comp_labely},
userdefined_colors: true,
display_colors: [3,4,5,6,7],
display_intro_position: 'none',
buttons_list: ['help'],
},
fyo: { domain_builder: 'none',
domain_parameter: 'none',
instance_builder: 'pie',
dimension_builder: 'readcat',
dimension_parameter: { column: 'fyo',
shared: false,
namespace: 'none'},
group_builder: 'auto',
group_parameter: { column: ['case']},
display_title: true,
userdefined_colors: true,
display_colors: [1,2],
display_intro_position: 'left',
buttons_list: ['reset','help'],
},
year: { domain_builder: 'year',
domain_parameter: 'none',
instance_builder: 'pie',
dimension_builder: 'year',
dimension_parameter: { column: 'epiwk',
shared: false,
namespace: 'none'},
group_builder: 'auto',
group_parameter: { column: ['case']},
display_title: true,
userdefined_colors: true,
display_colors: [3,4,5,6,7],
display_intro_position: 'left',
buttons_list: ['reset','help'],
},
table: { domain_builder: 'none',
domain_parameter: 'none',
instance_builder: 'table',
dimension_builder: 'auto',
dimension_parameter: { column: 'epiwk',
shared: false,
namespace: 'none'},
group_builder: 'none',
group_parameter: { column: 'none'},
sums_in_footer: ['case','death'], //column names from g.medical_headerlist
display_intro_position: 'top',
display_intro_container: 'container_table',
buttons_list: ['help'],
},
};
};
/**
Defines the chart used as a reference for time-related interactions.
* @constant
* @type {String}
* @alias module:g.viz_timeline
*/
g.viz_timeline = 'ser_range';
/**
Defines the time (milliseconds) between each time increment when in 'Play' mode. Only required when a range_chart is implemented.
* @constant
* @type {Number}
* @alias module:g.dev_defined.autoplay_delay
*/
//g.dev_defined.autoplay_delay = 2000;
/**
Defines whether at the end of the timeline, 'Play' mode continues to play from the beginning automatically. Only required when a range_chart is implemented.
* @constant
* @type {Boolean}
* @alias module:g.dev_defined.autoplay_rewind
*/
//g.dev_defined.autoplay_rewind = false;
/**
Defines the charts that are using time dimensions and that should be synchronized with the reference defined with {@link module:g.viz_timeline}.
* @constant
* @type {Array.<String>}
* @alias module:g.viz_timeshare
* @todo Automate
*/
g.viz_timeshare = ['case_ser', 'death_ser'];
/**
Defines the chart used as a reference for location-related interactions (e.g. incidence rates).
* @constant
* @type {String}
* @alias module:g.viz_locations
*/
g.viz_locations = 'multiadm';
/*if(!g.module_intro){
g.module_intro = {};
}
//g.dev_defined.intro_order = [];
//Define order of all intro topics, can either be charts (defined by name given above) or divs (defined in index.html)
//For and div intros, need to also define intro_position
g.module_intro.intro_order = ['intro', 'menu', 'multiadm', 'disease', 'container_ser_lin', 'case_ser', 'case_lin', 'ser_range', 'fyo', 'year', 'table'];
g.module_intro.intro_position = [{container: 'container_ser_lin',
position: 'top'
}];
//Here define which buttons (defined by div id) to click on before an intro element is called (to ensure appropriate chart/div is 'open' or not 'hidden' at the time it is called)
//Buttons defined in module_chartwarper.js
g.module_intro.intro_beforechange = [{
element: 'container_ser',
click: '#container_ser_outer-btn'
}, {
element: 'container_rangechart',
click: '#container_ser_outer-btn'
},{
element: 'container_ser_lin',
click: '#container_ser_outer-btn'
},{
element: 'chart-fyo',
click: '#container_ser_outer-btn'
},{
element: 'container_lin',
click: '#container_lin_outer-btn'
}]
*/ |
/**
* This file contains the variables used in other gulp files
* which defines tasks
* By design, we only put there very generic config values
* which are used in several places to keep good readability
* of the tasks
*/
var gutil = require('gulp-util');
/**
* The main paths of your project handle these with care
*/
exports.paths = {
src: 'src',
dist: 'docs',
tmp: '.tmp',
e2e: 'e2e',
template: '/app/**/*.html',
index: '/app/index.module.js',
templateRoot: 'app/',
cssRoot: 'app/',
bowerJson: '../bowerDocs.json',
};
exports.names = {
module: 'AngularjsDropdownMultiselectExample',
}
/**
* Wiredep is the lib which inject bower dependencies in your project
* Mainly used to inject script tags in the index.html but also used
* to inject css preprocessor deps and js files in karma
*/
exports.wiredep = {
exclude: [/\/bootstrap\.js$/, /\/bootstrap-sass\/.*\.js/, /\/bootstrap\.css/],
directory: 'bower_components',
bowerJson: require('../bowerDocs.json'),
};
/**
* Common implementation for an error handler of a Gulp plugin
*/
exports.errorHandler = function(title) {
'use strict';
return function(err) {
gutil.log(gutil.colors.red('[' + title + ']'), err.toString());
this.emit('end');
};
};
|
/*jshint esnext: true*/
/*global require, module, fetch*/
'use strict';
import React, { PropTypes } from 'react'
import {
StyleSheet,
View,
WebView
} from 'react-native'
class MnmWebviewEntry extends React.Component {
static propTypes = {
uri: PropTypes.string.isRequired
};
render() {
return (
<View style={styles.container}>
<WebView
scalesPageToFit={true}
source={{uri: this.props.uri}}
automaticallyAdjustContentInsets={false}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
webView: {
flex: 1,
},
})
module.exports = MnmWebviewEntry;
|
"use strict";
exports.logs = require('./facets/logs');
exports.kvstore = require('./facets/kvstore');
exports.musher = require('./facets/musher');
exports.metrics = require('./facets/metrics');
exports.jsonrpc = require('./facets/jsonrpc');
exports.mq = require('./facets/mq');
|
System.register(['./headers'], function(exports_1) {
var headers_1;
var HttpResponseMessage, mimeTypes;
return {
setters:[
function (_headers_1) {
headers_1 = _headers_1;
}],
execute: function() {
HttpResponseMessage = (function () {
function HttpResponseMessage(requestMessage, xhr, responseType, reviver) {
this.requestMessage = requestMessage;
this.statusCode = xhr.status;
this.response = xhr.response || xhr.responseText;
this.isSuccess = xhr.status >= 200 && xhr.status < 400;
this.statusText = xhr.statusText;
this.reviver = reviver;
this.mimeType = null;
if (xhr.getAllResponseHeaders) {
try {
this.headers = headers_1.Headers.parse(xhr.getAllResponseHeaders());
}
catch (err) {
//if this fails it means the xhr was a mock object so the `requestHeaders` property should be used
if (xhr.requestHeaders)
this.headers = { headers: xhr.requestHeaders };
}
}
else {
this.headers = new headers_1.Headers();
}
var contentType;
if (this.headers && this.headers.headers)
contentType = this.headers.headers["Content-Type"];
if (contentType) {
this.mimeType = responseType = contentType.split(";")[0].trim();
if (mimeTypes.hasOwnProperty(this.mimeType))
responseType = mimeTypes[this.mimeType];
}
this.responseType = responseType;
}
Object.defineProperty(HttpResponseMessage.prototype, "content", {
get: function () {
try {
if (this._content !== undefined) {
return this._content;
}
if (this.response === undefined || this.response === null) {
return this._content = this.response;
}
if (this.responseType === 'json') {
return this._content = JSON.parse(this.response, this.reviver);
}
if (this.reviver) {
return this._content = this.reviver(this.response);
}
return this._content = this.response;
}
catch (e) {
if (this.isSuccess) {
throw e;
}
return this._content = null;
}
},
enumerable: true,
configurable: true
});
return HttpResponseMessage;
})();
exports_1("HttpResponseMessage", HttpResponseMessage);
/**
* MimeTypes mapped to responseTypes
*
* @type {Object}
*/
exports_1("mimeTypes", mimeTypes = {
"text/html": "html",
"text/javascript": "js",
"application/javascript": "js",
"text/json": "json",
"application/json": "json",
"application/rss+xml": "rss",
"application/atom+xml": "atom",
"application/xhtml+xml": "xhtml",
"text/markdown": "md",
"text/xml": "xml",
"text/mathml": "mml",
"application/xml": "xml",
"text/yml": "yml",
"text/csv": "csv",
"text/css": "css",
"text/less": "less",
"text/stylus": "styl",
"text/scss": "scss",
"text/sass": "sass",
"text/plain": "txt"
});
}
}
});
|
/**
* ajax.js
* https://github.com/twiforce/fukuro/blob/master/js/ajax.js
*
* Send posts via AJAX
*
* Released under the MIT license
* Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org>
* 2013-2015 Simon Twiforce <twiforce@syn-ch.ru>
* 2014-2015 GhostPerson <https://github.com/GhostPerson>
*
* Usage:
* $config['additional_javascript'][] = 'js/jquery.min.js';
* $config['additional_javascript'][] = 'js/settings.js';
* $config['additional_javascript'][] = 'js/ajax.js';
* $config['additional_javascript'][] = 'js/postcount.js';
*
*/
var messageGrowl;
$(window).ready(function() {
if (settings.ajax) {
var do_not_ajax = false;
//kinda cache these
var postctrl = $('form[name=postcontrols]');
function receive(data){
var lastPost = postctrl.find('.post').last(),
lastID = lastPost.attr('id').replace(/reply_/, '');
lastID = Number(lastID);
var posts = $(data).find('.post.reply')
.filter(function(index, elem){
var id = Number($(elem).attr('id').replace(/reply_/, ''));
return (id > lastID)
})
.each(function (index, element) {
$(element).after('<br class="clear">');
});
if (settings.useAnimateCSS){
posts.addClass('animated fadeIn');
}
$(document).trigger('new_post', [posts]);
lastPost.after(posts);
}
var setup_form = function($form) {
$form.submit(function() {
if (settings.growlEnabled) {
messageGrowl = $.growl({
message: _('Отправка...')
}, {
delay: 0
});
}
if (do_not_ajax)
return true;
var form = $(this);
var submitBtn = form.find('input[type="submit"]');
var submit_txt = submitBtn.val();
if (window.FormData === undefined)
return true;
var formData = new FormData(this);
formData.append('json_response', '1');
formData.append('post', submit_txt);
var updateProgress = function(e) {
var percentage;
if (e.position === undefined) { // Firefox
percentage = Math.round(e.loaded * 100 / e.total);
}
else { // Chrome?
percentage = Math.round(e.position * 100 / e.total);
}
if (settings.growlEnabled)
messageGrowl.update('message', _('Posting... (#%)').replace('#', percentage));
else
$(form).find('input[type="submit"]').val(_('Posting... (#%)').replace('#', percentage));
};
$.ajax({
url: this.action,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload) {
xhr.upload.addEventListener('progress', updateProgress, false);
}
return xhr;
},
success: function(post_response) {
if (typeof Recaptcha != 'undefined') {
Recaptcha.reload();
}
if ($('#captchaimg')) {
$('#captchaimg').click();
}
if (typeof grecaptcha === "object") {
grecaptcha.reset();
}
if (post_response.error) {
if (post_response.banned) {
if (settings.growlEnabled) {
messageGrowl.update('message', post_response.banned);
}
// You are banned. Must post the form normally so the user can see the ban message.
do_not_ajax = true;
submitBtn.each(function() {
var $replacement = $('<input type="hidden">');
$replacement.attr('name', $(this).attr('name'));
$replacement.val(submit_txt);
$(this)
.after($replacement)
.replaceWith($('<input type="button">').val(submit_txt));
});
form.submit();
} else {
if (settings.growlEnabled)
messageGrowl.update('message', post_response.error);
else
alert(post_response.error);
submitBtn.val(submit_txt);
submitBtn.removeAttr('disabled');
}
} else if (post_response.redirect && post_response.id) {
if (!$(form).find('input[name="thread"]').length) {
document.location = post_response.redirect;
stats.threads.created++;
saveAndUpdateStats();
} else {
$.ajax({
url: document.location,
cache: false,
contentType: false,
processData: false
}, 'html')
.done(receive)
.done(function(){
stats.posts.sent++;
saveAndUpdateStats();
highlightReply(post_response.id);
window.location.hash = post_response.id;
$(window).scrollTop($('#reply_' + post_response.id).offset().top);
})
.always(function(){
if (settings.growlEnabled)
messageGrowl.close();
$(form).find('input[type="submit"]').val(submit_txt);
$(form).find('input[type="submit"]').removeAttr('disabled');
$(form).find('input[name="subject"],input[name="file_url"],\
textarea[name="body"],input[type="file"],input[name="embed"]').val('').change();
})
}
submitBtn.val(_('Posted...'));
} else {
if (settings.growlEnabled)
messageGrowl.update('message', _('An unknown error occured when posting!'));
else
alert(_('An unknown error occured when posting!'));
submitBtn.val(submit_txt);
submitBtn.removeAttr('disabled');
}
},
error: function() {
// An error occured
do_not_ajax = true;
submitBtn.each(function() {
var $replacement = $('<input type="hidden">');
$replacement.attr('name', $(this).attr('name'));
$replacement.val(submit_txt);
$(this)
.after($replacement)
.replaceWith($('<input type="button">').val(submit_txt));
});
$(form).submit();
},
data: formData,
cache: false,
contentType: false,
processData: false
}, 'json');
submitBtn.val(_('Posting...'));
submitBtn.attr('disabled', true);
return false;
});
};
setup_form($('form[name="post"]'));
$(window).on('quick-reply', function() {
setup_form($('form#quick-reply'));
});
}
});
|
/**
* HTTP method override Interceptor.
*/
export default function (request) {
if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) {
request.headers.set('X-HTTP-Method-Override', request.method);
request.method = 'POST';
}
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm4.59-12.42L10 14.17l-2.59-2.58L6 13l4 4 8-8z"
}), 'CheckCircleOutlineOutlined'); |
/**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
module.exports = function() {
this.Before("@sts", function (callback) {
this.client = new this.AWS.STS.Client();
callback();
});
this.Given(/^I get an STS session token with a duration of (\d+) seconds$/, function(duration, callback) {
this.request(null, 'getSessionToken', {DurationSeconds:parseInt(duration)}, callback, false);
});
this.Then(/^the result should contain an access key ID and secret access key$/, function(callback) {
this.assert.compare(this.data.Credentials.AccessKeyId.length, '>', 0);
this.assert.compare(this.data.Credentials.SecretAccessKey.length, '>', 0);
callback();
});
this.Then(/^the TTL on the session token credentials should be less than (\d+)$/, function(duration, callback) {
var ttl = this.data.Credentials.Expiration.getTime();
ttl = (ttl - new Date().getTime()) / 1000;
this.assert.compare(ttl, '<', duration);
callback();
});
};
|
/**
* @author Geert Fokke [geert@sector22.com]
* @www sector22.com
* @module sector22/utils
*/
/**
* @namespace
*/
var colorUtils = {};
/**
* Calculates the rgb value between 2 colors given a percentage.
* @param rgb1
* @param rgb2
* @param percentage
* @returns {string} - the new rgb value as string
*/
colorUtils.getGradientValue = function (rgb1, rgb2, percentage) {
var rgb = rgb1.split(',');
var red = parseInt(rgb[0]);
var green = parseInt(rgb[1]);
var blue = parseInt(rgb[2]);
rgb = rgb2.split(',');
red += (parseInt(rgb[0]) - red) * percentage;
green += (parseInt(rgb[1]) - green) * percentage;
blue += (parseInt(rgb[2]) - blue) * percentage;
return ((red << 0) + ',' + (green << 0) + ',' + (blue << 0));
}
if( typeof Object.freeze === 'function') Object.freeze(colorUtils) // lock the object to minimize accidental changes
module.exports = colorUtils; |
export default function position(x = 0, y = 0) {
return { x, y };
}
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Takes an array of objects and passes each of them to the given callback.
*
* @function Phaser.Actions.Call
* @since 3.0.0
*
* @generic {Phaser.GameObjects.GameObject[]} G - [items,$return]
*
* @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be updated by this action.
* @param {Phaser.Types.Actions.CallCallback} callback - The callback to be invoked. It will be passed just one argument: the item from the array.
* @param {*} context - The scope in which the callback will be invoked.
*
* @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that was passed to this Action.
*/
var Call = function (items, callback, context)
{
for (var i = 0; i < items.length; i++)
{
var item = items[i];
callback.call(context, item);
}
return items;
};
module.exports = Call;
|
"use strict";
var child_process = require('child_process');
var fork = child_process.fork;
var exec = child_process.exec;
var database = require('../../database');
var MAXIMUM_NICENESS = 19;
var ONE_HOUR = 60*60*1000;
var CACHE_ENTRY_NO_ACCESS_MAX_TIME = 24*ONE_HOUR;
/*
territoireId => mutable{
graph: aGraph
lastAccessTime?: timestamp
builtTime: timestamp
}
*/
var cache = new Map();
setTimeout(function cleanupCache(){
setTimeout(cleanupCache, CACHE_ENTRY_NO_ACCESS_MAX_TIME/4);
cache.forEach(function(entry, key){
if(Date.now() - entry.lastAccessTime < CACHE_ENTRY_NO_ACCESS_MAX_TIME){
// entry hasn't been accessed in a long time
cache.delete(key);
}
});
}, CACHE_ENTRY_NO_ACCESS_MAX_TIME/4);
var scheduledRefreshes = new Map/*<territoireId, Process>*/()
function refreshCacheEntry(territoireId){
//console.log('refreshCacheEntry', territoireId);
if(scheduledRefreshes.has(territoireId))
return; // already scheduled
var w = fork(require.resolve('./territoireGraphBuilder-worker'), [territoireId]);
scheduledRefreshes.set(territoireId, w);
w.on('message', function(graph){
// it's the graph,
cache.set(territoireId, {
graph: graph,
buildTime: Date.now(),
lastAccessTime: Date.now()
});
w.kill();
});
w.on('exit', function(){
scheduledRefreshes.delete(territoireId);
})
exec( ['renice', '-n', MAXIMUM_NICENESS, w.pid].join(' ') );
}
module.exports = function(territoireId){
var entry = cache.get(territoireId);
console.log('territoireGraphCache entry', !!entry);
if(entry){
entry.lastAccessTime = Date.now();
// schedule a refresh of the entry
refreshCacheEntry(territoireId)
return Promise.resolve({
graph: entry.graph,
complete: true,
buildTime: entry.buildTime
});
}
else{
// schedule getting the full graph
refreshCacheEntry(territoireId)
// Get the territoire query results and make a graph out of that to be returned ASAP
return database.complexQueries.getValidTerritoireQueryResultResources(territoireId)
.then(function(resources){
var nodes = [];
resources.forEach(function(res){
if(res.alias_of !== null)
return;
nodes.push(Object.assign(
{ depth: 0 },
res
));
});
return {
nodes: nodes,
edges: []
};
})
.then(function(graph){
return {
graph: graph,
complete: false
};
})
}
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.10.2.12_A4_T4;
* @section: 15.10.2.12;
* @assertion: The production CharacterClassEscape :: W evaluates by returning the set of all characters not
* included in the set returned by CharacterClassEscape :: w;
* @description: RUSSIAN ALPHABET;
*/
var regexp_W = /\W/;
//CHECK#0410-042F
var result = true;
for (alpha = 0x0410; alpha <= 0x042F; alpha++) {
str = String.fromCharCode(alpha);
arr = regexp_W.exec(str);
if ((arr === null) || (arr[0] !== str)) {
result = false;
}
}
if (result !== true) {
$ERROR('#1: RUSSIAN CAPITAL ALPHABET');
}
//CHECK#0430-044F
var result = true;
for (alpha = 0x0430; alpha <= 0x044F; alpha++) {
str = String.fromCharCode(alpha);
arr = regexp_W.exec(str);
if ((arr === null) || (arr[0] !== str)) {
result = false;
}
}
if (result !== true) {
$ERROR('#2: russian small alphabet');
}
|
"use strict";
const ServiceBroker = require("../src/service-broker");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
// Create broker
const broker = new ServiceBroker({
nodeID: "streaming-receiver-" + process.pid,
transporter: "TCP",
serializer: "ProtoBuf",
logger: console,
logLevel: "info"
});
broker.createService({
name: "file2",
actions: {
save(ctx) {
const stream = ctx.params;
const fileName = "d:/received-src.zip";
broker.logger.info("Open file");
const s = fs.createWriteStream(fileName);
stream.pipe(s);
const startTime = Date.now();
stream.on("data", chunk => {
this.uploadedSize += chunk.length;
broker.logger.info("RECV: ", Number(this.uploadedSize / this.stat.size * 100).toFixed(0) + `% (${chunk.length})`);
});
s.on("close", () => {
getSHA(fileName).then(hash => {
broker.logger.info("File received.");
broker.logger.info("Size:", this.uploadedSize);
broker.logger.info("SHA:", hash);
broker.logger.info("Time:", Date.now() - startTime + "ms");
});
});
s.on("error", err => {
broker.logger.info("Stream error!", err);
});
}
},
created() {
this.fileName = "d:/src.zip";
this.stat = fs.statSync(this.fileName);
this.uploadedSize = 0;
}
});
broker.start().then(() => {
broker.repl();
return broker.waitForServices("file");
}).delay(1000).then(() => {
const fileName = "d:/src.zip";
const stat = fs.statSync(fileName);
let uploadedSize = 0;
broker.call("file.get")
.then(stream => {
const fileName = "d:/received-src.zip";
broker.logger.info("Open file");
const s = fs.createWriteStream(fileName);
stream.pipe(s);
const startTime = Date.now();
stream.on("data", chunk => {
uploadedSize += chunk.length;
broker.logger.info("RECV: ", Number(uploadedSize / stat.size * 100).toFixed(0) + `% (${chunk.length})`);
});
s.on("close", () => {
getSHA(fileName).then(hash => {
broker.logger.info("File received.");
broker.logger.info("Size:", uploadedSize);
broker.logger.info("SHA:", hash);
broker.logger.info("Time:", Date.now() - startTime + "ms");
});
});
s.on("error", err => {
broker.logger.info("Stream error!", err);
});
});
});
function getSHA(fileName) {
return new Promise((resolve, reject) => {
let hash = crypto.createHash("sha1");
let stream = fs.createReadStream(fileName);
stream.on("error", err => reject(err));
stream.on("data", chunk => hash.update(chunk));
stream.on("end", () => resolve(hash.digest("hex")));
});
}
|
var sys = require('sys');
// starts a new TestCase with the given description.
//
// var assert = require('assert')
// describe("An array")
// it("tracks length", function() {
// var a = [1]
// assert.equal(1, a.length)
// })
//
exports.describe = function(desc) {
var test = new TestCase(desc);
exports.testSuite.testCases.push(test);
exports.testSuite.currentTestCase = test;
return test;
}
// Adds a new test to the current TestCase.
exports.test = function(desc, callback) {
if(!exports.testSuite.currentTestCase)
this.describe();
return exports.testSuite.currentTestCase.test(desc, callback);
}
// adds a callback to the current TestCase that is fired before each test.
// Each test gets its own context to deal with.
//
// describe("a number")
// before(function() {
// this.a = 1
// })
//
// test("+ 1", function () {
// assert.equal(2, this.a + 1)
// })
//
exports.before = function(callback) {
if(!exports.testSuite.currentTestCase)
this.describe();
return exports.testSuite.currentTestCase.before(callback);
}
// adds a callback that is fired after each test.
exports.after = function(callback) {
if(!exports.testSuite.currentTestCase)
this.describe();
return exports.testSuite.currentTestCase.after(callback);
}
exports.it = exports.test;
exports.setup = exports.before;
exports.teardown = exports.after;
// stores info on the current suite of tests.
// exports.testSuite.runTests() is runs all tests. If exports.testSuite.runOnExit
// is true (default), then tests are run when the process exits.
//
// This also functions as a test runner (something that reports the status of
// the tests as they are running.)
exports.testSuite = {
runOnExit: true,
runOnCreation: true,
passed: 0,
failed: [],
testCases: [],
currentTestCase: null,
runTests: function() {
var len = this.testCases.length;
for(var i = 0; i < this.testCases.length; ++i) {
var testCase = this.testCases[i],
tests = testCase.run(this),
testsLen = tests.length;
for(var j = 0; j < testsLen; ++j) {
var test = tests[j];
if(test.passed) {
++this.passed;
} else {
this.failed.push(test);
}
}
}
sys.puts("\n")
this.displayResults()
},
displayResults: function() {
var fail = this.failed.length
sys.puts((this.passed + fail) + " tests. " + this.passed + " passed, " + fail + " failed.\n");
for(var f = 0; f < fail; ++f) {
var test = this.failed[f];
sys.puts('TEST: ' + test.description)
sys.puts(this.red(test.error.stack))
sys.puts("")
}
},
runAutomatically: function() {
if(this.runOnCreation || this.runOnExit)
this.runTests();
},
greenDot: function(s) {
sys.print(this.green(s || '.'))
},
redDot: function(s) {
sys.print(this.red(s || 'F'))
},
color: function(color, message) { return "\033[" + color + "m" + message + "\033[0m"; },
red: function(message) { return this.color("0;31", message) },
green: function(message) { return this.color("0;32", message) }
}
// represents a group of tests for a common subject. These tests share the same
// before/after callbacks (callbacks are unimplemented...)
var TestCase = function(desc) {
this.description = (desc) ? desc : "";
this.tests = [];
this.beforeCallbacks = [];
this.afterCallbacks = [];
this.test = function(summary, callback) {
var t = new Test(this, summary, callback)
this.tests.push(t)
if(exports.testSuite.runOnCreation)
t.run(exports.testSuite);
return t;
}
this.before = function(callback) {
this.beforeCallbacks.push(callback)
}
this.after = function(callback) {
this.afterCallbacks.push(callback)
}
this.run = function(runner) {
if(!this.runOnCreation)
this.tests.forEach(function(test) { test.run(runner) })
return this.tests;
}
this.runTest = function(callback) {
var context = {} // each test has a clean slate
this.beforeCallbacks.forEach(function(c) { c.apply(context) })
callback.apply(context)
this.afterCallbacks.forEach(function(c) { c.apply(context) })
}
}
// represents a single test, which is just an executable function and a description.
var Test = function(testCase, summary, callback) {
this.testCase = testCase;
this.summary = summary;
this.description = (testCase.description + " " + summary).replace(/^\s+/i, '');
this.callback = callback
this.passed = false;
this.error = null;
this.run = function(runner) {
if(this.passed || this.error) return;
try {
this.testCase.runTest(this.callback)
this.passed = true;
this.error = null;
runner.greenDot()
} catch(err) {
this.error = err;
this.passed = false;
runner.redDot()
}
}
}
process.addListener('exit', function() {
exports.testSuite.runAutomatically();
}) |
(function() {
'use strict';
angular.module('words').controller('MainCtrl', ['mainService', 'categoryManager', 'userService',
function(mainService, categoryManager, userService) {
var vm = this;
vm.categories = [];
vm.currentCategory = mainService.selectedCategory();
vm.switch = {
on: 'Learn',
off: 'Review'
};
vm.mode = userService.mode() || vm.switch.on;
vm.initialState = vm.mode !== vm.switch.on ? true : false;
vm.modeChanged = function(state) {
vm.mode = state ? vm.switch.off : vm.switch.on;
userService.changeMode(vm.mode);
};
categoryManager.init(function(categories) {
categories.$promise.then(function(data) {
vm.categories = data;
var selected = Array.prototype.find.call(vm.categories, function(elem, idx) {
return elem.name === vm.currentCategory.name;
});
vm.currentCategory = selected ? selected : vm.categories[0];
});
});
vm.selectCategory = function() {
mainService.newCategory(vm.currentCategory);
};
}]);
}());
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.smash = {
setUp: function(done) {
// setup here if necessary
done();
},
target1: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/target1.js');
var expected = grunt.file.read('test/expected/target1.js');
test.equal(actual, expected, 'should contain the contents of foo.js and bar.js');
test.done();
},
target2: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/target2.js');
var expected = grunt.file.read('test/expected/target2.js');
test.equal(actual, expected, 'should contain the contents of foo.js and baz.js');
test.done();
},
};
|
const dec = () => {};
class Foo {
static #A;
static get a() {
return this.#A;
}
static set a(v) {
this.#A = v;
}
static #B = 123;
static get b() {
return this.#B;
}
static set b(v) {
this.#B = v;
}
static #C = 456;
static get 'c'() {
return this.#C;
}
static set 'c'(v) {
this.#C = v;
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:f8d46d531f29d111c23f9ea8906b1c1fab8e85162e4d6b52c8d21724774f6b98
size 135453
|
'use strict';
var mongoose = require('mongoose');
var device = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true
},
ip: {
type: String,
required: true
},
triggers: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Trigger',
required: false
}]
});
module.exports = mongoose.model('Device', device);
|
var app = require('koa')();
var router = (new require('koa-router'))();
var koaBody = require('koa-better-body');
require('koa-qs')(app, 'extended');
var validate = require('../../lib/validate');
app.use(koaBody({
'multipart': true
}));
app.use(validate());
require('./query_routes')(app, router);
require('./header_routes')(app, router);
require('./param_routes')(app, router);
require('./post_routes')(app, router);
require('./file_routes')(app, router);
module.exports = app;
|
/**
* QUnit v1.3.0pre - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2012 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL (GPL-LICENSE.txt) licenses.
*/
(function(window) {
var defined = {
setTimeout: typeof window.setTimeout !== "undefined",
sessionStorage: (function() {
var x = "qunit-test-string";
try {
sessionStorage.setItem(x, x);
sessionStorage.removeItem(x);
return true;
} catch(e) {
return false;
}
})()
};
var testId = 0,
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
var Test = function(name, testName, expected, async, callback) {
this.name = name;
this.testName = testName;
this.expected = expected;
this.async = async;
this.callback = callback;
this.assertions = [];
};
Test.prototype = {
init: function() {
var tests = id("qunit-tests");
if (tests) {
var b = document.createElement("strong");
b.innerHTML = "Running " + this.name;
var li = document.createElement("li");
li.appendChild( b );
li.className = "running";
li.id = this.id = "test-output" + testId++;
tests.appendChild( li );
}
},
setup: function() {
if (this.module != config.previousModule) {
if ( config.previousModule ) {
runLoggingCallbacks('moduleDone', QUnit, {
name: config.previousModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
config.previousModule = this.module;
config.moduleStats = { all: 0, bad: 0 };
runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module
} );
} else if (config.autorun) {
runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module
} );
}
config.current = this;
this.testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, this.moduleTestEnvironment);
runLoggingCallbacks( 'testStart', QUnit, {
name: this.testName,
module: this.module
});
// allow utility functions to access the current test environment
// TODO why??
QUnit.current_testEnvironment = this.testEnvironment;
try {
if ( !config.pollution ) {
saveGlobal();
}
this.testEnvironment.setup.call(this.testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
}
},
run: function() {
config.current = this;
if ( this.async ) {
QUnit.stop();
}
if ( config.notrycatch ) {
this.callback.call(this.testEnvironment);
return;
}
try {
this.callback.call(this.testEnvironment);
} catch(e) {
fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
QUnit.start();
}
}
},
teardown: function() {
config.current = this;
try {
this.testEnvironment.teardown.call(this.testEnvironment);
checkPollution();
} catch(e) {
QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
}
},
finish: function() {
config.current = this;
if ( this.expected != null && this.expected != this.assertions.length ) {
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
for ( var i = 0; i < this.assertions.length; i++ ) {
var assertion = this.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
// store result when possible
if ( QUnit.config.reorder && defined.sessionStorage ) {
if (bad) {
sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
} else {
sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
}
}
if (bad == 0) {
ol.style.display = "none";
}
var b = document.createElement("strong");
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
var a = document.createElement("a");
a.innerHTML = "Rerun";
a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
addEvent(b, "click", function() {
var next = b.nextSibling.nextSibling,
display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = e && e.target ? e.target : window.event.srcElement;
if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
target = target.parentNode;
}
if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
}
});
var li = id(this.id);
li.className = bad ? "fail" : "pass";
li.removeChild( li.firstChild );
li.appendChild( b );
li.appendChild( a );
li.appendChild( ol );
} else {
for ( var i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
try {
QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
}
runLoggingCallbacks( 'testDone', QUnit, {
name: this.testName,
module: this.module,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length
} );
},
queue: function() {
var test = this;
synchronize(function() {
test.init();
});
function run() {
// each of these can by async
synchronize(function() {
test.setup();
});
synchronize(function() {
test.run();
});
synchronize(function() {
test.teardown();
});
synchronize(function() {
test.finish();
});
}
// defer when previous test run passed, if storage is available
var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
if (bad) {
run();
} else {
synchronize(run, true);
};
}
};
var QUnit = {
// call on start of module test to prepend name to all tests
module: function(name, testEnvironment) {
config.currentModule = name;
config.currentModuleTestEnviroment = testEnvironment;
},
asyncTest: function(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
QUnit.test(testName, expected, callback, true);
},
test: function(testName, expected, callback, async) {
var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>';
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
if ( config.currentModule ) {
name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
}
if ( !validTest(config.currentModule + ": " + testName) ) {
return;
}
var test = new Test(name, testName, expected, async, callback);
test.module = config.currentModule;
test.moduleTestEnvironment = config.currentModuleTestEnviroment;
test.queue();
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function(asserts) {
config.current.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function(a, msg) {
if (!config.current) {
throw new Error("ok() assertion outside test context, was " + sourceFromStacktrace(2));
}
a = !!a;
var details = {
result: a,
message: msg
};
msg = escapeInnerText(msg);
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equal: function(actual, expected, message) {
QUnit.push(expected == actual, actual, expected, message);
},
notEqual: function(actual, expected, message) {
QUnit.push(expected != actual, actual, expected, message);
},
deepEqual: function(actual, expected, message) {
QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
},
notDeepEqual: function(actual, expected, message) {
QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
},
strictEqual: function(actual, expected, message) {
QUnit.push(expected === actual, actual, expected, message);
},
notStrictEqual: function(actual, expected, message) {
QUnit.push(expected !== actual, actual, expected, message);
},
raises: function(block, expected, message) {
var actual, ok = false;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
if (actual) {
// we don't want to validate thrown error
if (!expected) {
ok = true;
// expected is a regexp
} else if (QUnit.objectType(expected) === "regexp") {
ok = expected.test(actual);
// expected is a constructor
} else if (actual instanceof expected) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if (expected.call({}, actual) === true) {
ok = true;
}
}
QUnit.ok(ok, message);
},
start: function(count) {
config.semaphore -= count || 1;
if (config.semaphore > 0) {
// don't start until equal number of stop-calls
return;
}
if (config.semaphore < 0) {
// ignore if start is called more often then stop
config.semaphore = 0;
}
// A slight delay, to avoid any current callbacks
if ( defined.setTimeout ) {
window.setTimeout(function() {
if (config.semaphore > 0) {
return;
}
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process(true);
}, 13);
} else {
config.blocking = false;
process(true);
}
},
stop: function(count) {
config.semaphore += count || 1;
config.blocking = true;
if ( config.testTimeout && defined.setTimeout ) {
clearTimeout(config.timeout);
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
config.semaphore = 1;
QUnit.start();
}, config.testTimeout);
}
}
};
//We want access to the constructor's prototype
(function() {
function F(){};
F.prototype = QUnit;
QUnit = new F();
//Make F QUnit's constructor so that we can add to the prototype later
QUnit.constructor = F;
})();
// deprecated; still export them to window to provide clear error messages
// next step: remove entirely
QUnit.equals = function() {
throw new Error("QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead");
};
QUnit.same = function() {
throw new Error("QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead");
};
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true,
// when enabled, show only failing tests
// gets persisted through sessionStorage and can be changed in UI via checkbox
hidepassed: false,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
urlConfig: ['noglobals', 'notrycatch'],
//logging callback queues
begin: [],
done: [],
log: [],
testStart: [],
testDone: [],
moduleStart: [],
moduleDone: []
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
params = location.search.slice( 1 ).split( "&" ),
length = params.length,
urlParams = {},
current;
if ( params[ 0 ] ) {
for ( var i = 0; i < length; i++ ) {
current = params[ i ].split( "=" );
current[ 0 ] = decodeURIComponent( current[ 0 ] );
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
urlParams[ current[ 0 ] ] = current[ 1 ];
}
}
QUnit.urlParams = urlParams;
config.filter = urlParams.filter;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
module.exports = QUnit;
}
// define these after exposing globals to keep them in these QUnit namespace only
extend(QUnit, {
config: config,
// Initialize the configuration options
init: function() {
extend(config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
filter: "",
queue: [],
semaphore: 0
});
var qunit = id( "qunit" );
if ( qunit ) {
qunit.innerHTML =
'<h1 id="qunit-header">' + document.title + '</h1>' +
'<h2 id="qunit-banner"></h2>' +
'<div id="qunit-testrunner-toolbar"></div>' +
'<h2 id="qunit-userAgent"></h2>' +
'<ol id="qunit-tests"></ol>';
}
var tests = id( "qunit-tests" ),
banner = id( "qunit-banner" ),
result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = 'Running...<br/> ';
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*
* If jQuery is available, uses jQuery's replaceWith(), otherwise use replaceChild
*/
reset: function() {
if ( window.jQuery ) {
jQuery( "#qunit-fixture" ).replaceWith( config.fixture.cloneNode(true) );
} else {
var main = id( 'qunit-fixture' );
if ( main ) {
main.parentNode.replaceChild(config.fixture.cloneNode(true), main);
}
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Safe object type checking
is: function( type, obj ) {
return QUnit.objectType( obj ) == type;
},
objectType: function( obj ) {
if (typeof obj === "undefined") {
return "undefined";
// consider: typeof null === object
}
if (obj === null) {
return "null";
}
var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
switch (type) {
case 'Number':
if (isNaN(obj)) {
return "nan";
} else {
return "number";
}
case 'String':
case 'Boolean':
case 'Array':
case 'Date':
case 'RegExp':
case 'Function':
return type.toLowerCase();
}
if (typeof obj === "object") {
return "object";
}
return undefined;
},
push: function(result, actual, expected, message) {
if (!config.current) {
throw new Error("assertion outside test context, was " + sourceFromStacktrace());
}
var details = {
result: result,
message: message,
actual: actual,
expected: expected
};
message = escapeInnerText(message) || (result ? "okay" : "failed");
message = '<span class="test-message">' + message + "</span>";
var output = message;
if (!result) {
expected = escapeInnerText(QUnit.jsDump.parse(expected));
actual = escapeInnerText(QUnit.jsDump.parse(actual));
output += '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
if (actual != expected) {
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
}
var source = sourceFromStacktrace();
if (source) {
details.source = source;
output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
}
output += "</table>";
}
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: !!result,
message: output
});
},
url: function( params ) {
params = extend( extend( {}, QUnit.urlParams ), params );
var querystring = "?",
key;
for ( key in params ) {
if ( !hasOwn.call( params, key ) ) {
continue;
}
querystring += encodeURIComponent( key ) + "=" +
encodeURIComponent( params[ key ] ) + "&";
}
return window.location.pathname + querystring.slice( 0, -1 );
},
extend: extend,
id: id,
addEvent: addEvent
});
//QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
//Doing this allows us to tell if the following methods have been overwritten on the actual
//QUnit object, which is a deprecated way of using the callbacks.
extend(QUnit.constructor.prototype, {
// Logging callbacks; all receive a single argument with the listed properties
// run test/logs.html for any related changes
begin: registerLoggingCallback('begin'),
// done: { failed, passed, total, runtime }
done: registerLoggingCallback('done'),
// log: { result, actual, expected, message }
log: registerLoggingCallback('log'),
// testStart: { name }
testStart: registerLoggingCallback('testStart'),
// testDone: { name, failed, passed, total }
testDone: registerLoggingCallback('testDone'),
// moduleStart: { name }
moduleStart: registerLoggingCallback('moduleStart'),
// moduleDone: { name, failed, passed, total }
moduleDone: registerLoggingCallback('moduleDone')
});
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
QUnit.load = function() {
runLoggingCallbacks( 'begin', QUnit, {} );
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var urlConfigHtml = '', len = config.urlConfig.length;
for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
config[val] = QUnit.urlParams[val];
urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
}
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var banner = id("qunit-header");
if ( banner ) {
banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
addEvent( banner, "change", function( event ) {
var params = {};
params[ event.target.name ] = event.target.checked ? true : undefined;
window.location = QUnit.url( params );
});
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
addEvent( filter, "click", function() {
var ol = document.getElementById("qunit-tests");
if ( filter.checked ) {
ol.className = ol.className + " hidepass";
} else {
var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
ol.className = tmp.replace(/ hidepass /, " ");
}
if ( defined.sessionStorage ) {
if (filter.checked) {
sessionStorage.setItem("qunit-filter-passed-tests", "true");
} else {
sessionStorage.removeItem("qunit-filter-passed-tests");
}
}
});
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
filter.checked = true;
var ol = document.getElementById("qunit-tests");
ol.className = ol.className + " hidepass";
}
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "qunit-filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
}
var main = id('qunit-fixture');
if ( main ) {
config.fixture = main.cloneNode(true);
}
if (config.autostart) {
QUnit.start();
}
};
addEvent(window, "load", QUnit.load);
// addEvent(window, "error") gives us a useless event object
window.onerror = function( message, file, line ) {
if ( QUnit.config.current ) {
ok( false, message + ", " + file + ":" + line );
} else {
test( "global failure", function() {
ok( false, message + ", " + file + ":" + line );
});
}
};
function done() {
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
runLoggingCallbacks( 'moduleDone', QUnit, {
name: config.currentModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
runtime = +new Date - config.started,
passed = config.stats.all - config.stats.bad,
html = [
'Tests completed in ',
runtime,
' milliseconds.<br/>',
'<span class="passed">',
passed,
'</span> tests of <span class="total">',
config.stats.all,
'</span> passed, <span class="failed">',
config.stats.bad,
'</span> failed.'
].join('');
if ( banner ) {
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
}
if ( tests ) {
id( "qunit-testresult" ).innerHTML = html;
}
if ( config.altertitle && typeof document !== "undefined" && document.title ) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
(config.stats.bad ? "\u2716" : "\u2714"),
document.title.replace(/^[\u2714\u2716] /i, "")
].join(" ");
}
// clear own sessionStorage items if all tests passed
if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) {
for (var key in sessionStorage) {
if (sessionStorage.hasOwnProperty(key) && key.indexOf("qunit-") === 0 ) {
sessionStorage.removeItem(key);
}
}
}
runLoggingCallbacks( 'done', QUnit, {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
} );
}
function validTest( name ) {
var filter = config.filter,
run = false;
if ( !filter ) {
return true;
}
var not = filter.charAt( 0 ) === "!";
if ( not ) {
filter = filter.slice( 1 );
}
if ( name.indexOf( filter ) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
return run;
}
// so far supports only Firefox, Chrome and Opera (buggy)
// could be extended in the future to use something like https://github.com/csnover/TraceKit
function sourceFromStacktrace(offset) {
offset = offset || 3;
try {
throw new Error();
} catch ( e ) {
if (e.stacktrace) {
// Opera
return e.stacktrace.split("\n")[offset + 3];
} else if (e.stack) {
// Firefox, Chrome
var stack = e.stack.split("\n");
if (/^error$/i.test(stack[0])) {
stack.shift();
}
return stack[offset];
} else if (e.sourceURL) {
// Safari, PhantomJS
// TODO sourceURL points at the 'throw new Error' line above, useless
//return e.sourceURL + ":" + e.line;
}
}
}
function escapeInnerText(s) {
if (!s) {
return "";
}
s = s + "";
return s.replace(/[\&<>]/g, function(s) {
switch(s) {
case "&": return "&";
case "<": return "<";
case ">": return ">";
default: return s;
}
});
}
function synchronize( callback, last ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process(last);
}
}
function process( last ) {
var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()();
} else {
window.setTimeout( function(){
process( last );
}, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
if ( !hasOwn.call( window, key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
}
var deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.error(exception.stack);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
if ( b[prop] === undefined ) {
delete a[prop];
// Avoid "Member not found" error in IE8 caused by setting window.constructor
} else if ( prop !== "constructor" || a !== window ) {
a[prop] = b[prop];
}
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
function registerLoggingCallback(key){
return function(callback){
config[key].push( callback );
};
}
// Supports deprecated method of completely overwriting logging callbacks
function runLoggingCallbacks(key, scope, args) {
//debugger;
var callbacks;
if ( QUnit.hasOwnProperty(key) ) {
QUnit[key].call(scope, args);
} else {
callbacks = config[key];
for( var i = 0; i < callbacks.length; i++ ) {
callbacks[i].call( scope, args );
}
}
}
// Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
var parents = []; // stack to avoiding loops from circular referencing
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = QUnit.objectType(o);
if (prop) {
if (QUnit.objectType(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var getProto = Object.getPrototypeOf || function (obj) {
return obj.__proto__;
};
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a
// declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string" : useStrictEquality,
"boolean" : useStrictEquality,
"number" : useStrictEquality,
"null" : useStrictEquality,
"undefined" : useStrictEquality,
"nan" : function(b) {
return isNaN(b);
},
"date" : function(b, a) {
return QUnit.objectType(b) === "date"
&& a.valueOf() === b.valueOf();
},
"regexp" : function(b, a) {
return QUnit.objectType(b) === "regexp"
&& a.source === b.source && // the regex itself
a.global === b.global && // and its modifers
// (gmi) ...
a.ignoreCase === b.ignoreCase
&& a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function" : function() {
var caller = callers[callers.length - 1];
return caller !== Object && typeof caller !== "undefined";
},
"array" : function(b, a) {
var i, j, loop;
var len;
// b could be an object literal here
if (!(QUnit.objectType(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
// track reference to avoid circular references
parents.push(a);
for (i = 0; i < len; i++) {
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i]) {
loop = true;// dont rewalk array
}
}
if (!loop && !innerEquiv(a[i], b[i])) {
parents.pop();
return false;
}
}
parents.pop();
return true;
},
"object" : function(b, a) {
var i, j, loop;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of
// strings
// comparing constructors is more strict than using
// instanceof
if (a.constructor !== b.constructor) {
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
(getProto(b) === null && getProto(a) === Object.prototype)))
{
return false;
}
}
// stack constructor before traversing properties
callers.push(a.constructor);
// track reference to avoid circular references
parents.push(a);
for (i in a) { // be strict: don't ensures hasOwnProperty
// and go deep
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i])
loop = true; // don't go down the same path
// twice
}
aProperties.push(i); // collect a's properties
if (!loop && !innerEquiv(a[i], b[i])) {
eq = false;
break;
}
}
callers.pop(); // unstack, we are done
parents.pop();
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq
&& innerEquiv(aProperties.sort(), bProperties
.sort());
}
};
}();
innerEquiv = function() { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function(a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined"
|| typeof b === "undefined"
|| QUnit.objectType(a) !== QUnit.objectType(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [ b, a ]);
}
// apply transition with (1..n) arguments
})(args[0], args[1])
&& arguments.callee.apply(this, args.splice(1,
args.length - 1));
};
return innerEquiv;
}();
/**
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
* http://flesler.blogspot.com Licensed under BSD
* (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
*
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr, stack ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] , undefined , stack);
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
stack = stack || [ ];
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
var inStack = inArray(obj, stack);
if (inStack != -1) {
return 'recursion('+(inStack - stack.length)+')';
}
//else
if (type == 'function') {
stack.push(obj);
var res = parser.call( this, obj, stack );
stack.pop();
return res;
}
// else
return (type == 'string') ? parser : this.parsers.error;
},
typeOf:function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (QUnit.is("RegExp", obj)) {
type = "regexp";
} else if (QUnit.is("Date", obj)) {
type = "date";
} else if (QUnit.is("Function", obj)) {
type = "function";
} else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (
// native arrays
toString.call( obj ) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
) {
type = "array";
} else {
type = typeof obj;
}
return type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
'undefined':'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map, stack ) {
var ret = [ ];
QUnit.jsDump.up();
for ( var key in map ) {
var val = map[key];
ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
}
QUnit.jsDump.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = QUnit.jsDump.HTML ? '<' : '<',
close = QUnit.jsDump.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in QUnit.jsDump.DOMAttrs ) {
var val = node[QUnit.jsDump.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
// from Sizzle.js
function getText( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += getText( elem.childNodes );
}
}
return ret;
};
//from jquery.js
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
/*
* Javascript Diff Algorithm
* By John Resig (http://ejohn.org/)
* Modified by Chu Alan "sprite"
*
* Released under the MIT license.
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
*
* Usage: QUnit.diff(expected, actual)
*
* QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
*/
QUnit.diff = (function() {
function diff(o, n) {
var ns = {};
var os = {};
for (var i = 0; i < n.length; i++) {
if (ns[n[i]] == null)
ns[n[i]] = {
rows: [],
o: null
};
ns[n[i]].rows.push(i);
}
for (var i = 0; i < o.length; i++) {
if (os[o[i]] == null)
os[o[i]] = {
rows: [],
n: null
};
os[o[i]].rows.push(i);
}
for (var i in ns) {
if ( !hasOwn.call( ns, i ) ) {
continue;
}
if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
n[ns[i].rows[0]] = {
text: n[ns[i].rows[0]],
row: os[i].rows[0]
};
o[os[i].rows[0]] = {
text: o[os[i].rows[0]],
row: ns[i].rows[0]
};
}
}
for (var i = 0; i < n.length - 1; i++) {
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
n[i + 1] == o[n[i].row + 1]) {
n[i + 1] = {
text: n[i + 1],
row: n[i].row + 1
};
o[n[i].row + 1] = {
text: o[n[i].row + 1],
row: i + 1
};
}
}
for (var i = n.length - 1; i > 0; i--) {
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
n[i - 1] == o[n[i].row - 1]) {
n[i - 1] = {
text: n[i - 1],
row: n[i].row - 1
};
o[n[i].row - 1] = {
text: o[n[i].row - 1],
row: i - 1
};
}
}
return {
o: o,
n: n
};
}
return function(o, n) {
o = o.replace(/\s+$/, '');
n = n.replace(/\s+$/, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = [" "];
}
else {
oSpace.push(" ");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = [" "];
}
else {
nSpace.push(" ");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<del>' + out.o[i] + oSpace[i] + "</del>";
}
}
else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
}
else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
};
})();
// get at whatever the global object is, like window in browsers
})( (function() {return this}).call() ); |
/**
* Created with JetBrains PhpStorm.
* User: helder
* Date: 10/05/13
* Time: 14:53
* To change this template use File | Settings | File Templates.
*/
$(document).ready(function() {
$("div.accordi").accordion({
autoHeight: false,
collapsible: true,
active: false
});
}); |
module.exports = function ({ $lookup }) {
return {
object: function () {
const crypto = require('crypto')
const assert = require('assert')
return function (object, {
hash = (() => crypto.createHash('md5'))()
} = {}, $step = 0, $i = [], $$ = [], $accumulator = {}, $starts = []) {
let $_, $bite, $restart = false
return function $serialize ($buffer, $start, $end) {
if ($restart) {
for (let $j = 0; $j < $starts.length; $j++) {
$starts[$j] = $start
}
}
$restart = true
for (;;) {
switch ($step) {
case 0:
$accumulator['hash'] = hash
case 1:
$starts[0] = $start
case 2:
$bite = 3
$_ = object.body.number
case 3:
while ($bite != -1) {
if ($start == $end) {
$step = 3
; (({ $buffer, $start, $end, hash }) => hash.update($buffer.slice($start, $end)))({
$buffer: $buffer,
$start: $starts[0],
$end: $start,
hash: $accumulator['hash']
})
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = $_ >>> $bite * 8 & 0xff
$bite--
}
case 4:
$i[0] = 0
$step = 5
case 5:
$bite = 0
$_ = object.body.data[$i[0]]
case 6:
while ($bite != -1) {
if ($start == $end) {
$step = 6
; (({ $buffer, $start, $end, hash }) => hash.update($buffer.slice($start, $end)))({
$buffer: $buffer,
$start: $starts[0],
$end: $start,
hash: $accumulator['hash']
})
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = $_ >>> $bite * 8 & 0xff
$bite--
}
if (++$i[0] != object.body.data.length) {
$step = 5
continue
}
$step = 7
case 7:
if ($start == $end) {
$step = 7
; (({ $buffer, $start, $end, hash }) => hash.update($buffer.slice($start, $end)))({
$buffer: $buffer,
$start: $starts[0],
$end: $start,
hash: $accumulator['hash']
})
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = 0x0
case 8:
; (({ $buffer, $start, $end, hash }) => hash.update($buffer.slice($start, $end)))({
$buffer: $buffer,
$start: $starts[0],
$end: $start,
hash: $accumulator['hash']
})
case 9:
$$[0] = (({ $_, hash }) => $_ = hash.digest())({
$_: object.checksum,
hash: $accumulator['hash']
})
case 10:
$_ = 0
case 11: {
const length = Math.min($end - $start, $$[0].length - $_)
$$[0].copy($buffer, $start, $_, $_ + length)
$start += length
$_ += length
if ($_ != $$[0].length) {
$step = 11
return { start: $start, serialize: $serialize }
}
}
}
break
}
return { start: $start, serialize: null }
}
}
} ()
}
}
|
module.exports = {
Photos: require("./photos")
}; |
import React from 'react';
import expect from 'expect';
import { mount } from 'enzyme';
import Checkbox from '../Checkbox';
function setup(props = {text: 'GSoC', checked: false}) {
let actions = {
onChange: expect.createSpy()
};
let component = mount(
<Checkbox {...props} {...actions} />
);
return {
component,
checkbox: component.find('input'),
label: component.find('.checkbox-container'),
props,
actions
};
}
describe('Components::Checkbox', () => {
it('should render correctly', () => {
const { label, props } = setup();
expect(label.text()).toBe(props.text);
});
it('should call onChange', () => {
const { component, checkbox, actions } = setup();
checkbox.simulate('change');
expect(actions.onChange).toHaveBeenCalled();
});
});
|
var assert = require('assert'),
_ = require('lodash');
describe('Semantic Interface', function() {
describe('Integer Type', function() {
describe('with valid data', function() {
/////////////////////////////////////////////////////
// TEST METHODS
////////////////////////////////////////////////////
it('should store proper integer', function(done) {
Semantic.User.create({ age: 27 }, function (err, createdRecord) {
assert(!err);
assert.strictEqual(createdRecord.age, 27);
Semantic.User.findOne({id: createdRecord.id}, function (err, record) {
assert(!err);
assert.strictEqual(record.age, 27);
done();
});
});
});
});
});
});
|
(function(){
'use strict';
angular
.module('app')
.directive('pictureUpload', pictureUpload);
function pictureUpload () {
return {
templateUrl: 'widgets/picture-upload/picture-upload.tpl.html',
restrict: 'EA',
scope: {
callback: '=',
targetUrl: '=',
targetTags: '=',
imageUploaded: '='
},
controller: PictureUploadCtrl,
controllerAs: 'pictureUpload',
bindToController: true
};
}
PictureUploadCtrl.$inject = ['$scope','Upload'];
function PictureUploadCtrl ($scope,Upload) {
var vm = this;
vm.uploadFile = uploadFile;
$scope.$watch(function(){
return vm.files;
}, function(){
uploadFile(vm.files);
});
function uploadFile (files){
if (files && files.length && vm.targetUrl) {
var data = {};
if(vm.targetTags){
data.tags = vm.targetTags;
}
Upload.upload({
url: vm.targetUrl,
method: 'POST',
file: files,
data:data
}).progress(onProgress)
.success(onSuccess);
}
}
function onProgress(evt) {
vm.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}
function onSuccess(data, status, headers, config) {
console.log(data);
if(vm.callback){
vm.callback(data);
}
vm.uploadProgress = undefined;
}
}
})();
|
'use strict';
import Parse from './_parse_mongo.js';
let MongoSocket = think.adapter('socket', 'mongo');
/**
* mongo db class
*/
export default class extends Parse {
/**
* init
* @param {Object} config []
* @return {} []
*/
init(config){
super.init();
this.config = config;
this.lastInsertId = 0;
this._socket = null; //Mongo socket instance
}
/**
* connect mongo socket
* @return {Promise} []
*/
socket(){
if(this._socket){
return this._socket;
}
this._socket = MongoSocket.getInstance(this.config, thinkCache.DB);
return this._socket;
}
/**
* get connection
* @return {Promise} []
*/
collection(table){
let instance = this.socket();
return instance.getConnection().then(db => db.collection(table));
}
/**
* get last insert id
* @return {String} []
*/
getLastInsertId(){
return this.lastInsertId;
}
/**
* add data
* @param {Objec} data []
* @param {Object} options []
*/
async add(data, options){
let collection = await this.collection(options.table);
let result = await collection.insert(data);
this.lastInsertId = data._id.toString();
return result;
}
/**
* add multi data
* @param {Array} dataList []
* @param {Object} options [ {ordered: true}. If false, perform an unordered insert, and if an error occurs with one of documents, continue processing the remaining documents in the array.}]
* @param {Object} options []
*/
async addMany(dataList, options){
let collection = await this.collection(options.table);
let result = await collection.insert(dataList, options);
let insertedIds = dataList.map(item => {
return item._id.toString();
});
this.lastInsertId = insertedIds;
return result;
}
/**
* set collection limit
* @param {Object} collection []
* @param {String} limit []
* @return {Object} []
*/
limit(collection, limit){
limit = this.parseLimit(limit);
if(limit[0]){
collection.skip(limit[0]);
}
if(limit[1]){
collection.limit(limit[1]);
}
return collection;
}
/**
* parse group
* @param {String} group []
* @return {Object} []
*/
group(group){
group = this.parseGroup(group);
let length = group.length;
if(length === 0){
return {_id: null};
}else if(length === 1){
return {_id: `$${group[0]}`};
}else {
let result = {};
group.forEach(item => {
result[item] = `$${item}`;
});
return result;
}
}
/**
* select data
* @param {Object} options []
* @return {Promise} []
*/
async select(options){
let collection = await this.collection(options.table);
let where = this.parseWhere(options.where);
//get distinct field data
let distinct = this.parseDistinct(options.distinct);
if(distinct){
return collection.distinct(distinct, where);
}
collection = collection.find(where, this.parseField(options.field));
collection = this.limit(collection, options.limit);
collection = collection.sort(this.parseOrder(options.order));
return collection.toArray();
}
/**
* update data
* @param {Object} data []
* @param {Object} options []
* @return {Promise} []
*/
async update(data, options){
let collection = await this.collection(options.table);
let where = this.parseWhere(options.where);
let limit = this.parseLimit(options.limit);
// updates multiple documents that meet the query criteria.
// default only updates one document
if(limit[1] !== 1){
options.multi = true;
}
// If set to true, creates a new document when no document matches the query criteria.
// The default value is false, which does not insert a new document when no match is found.
if(!options.upsert){
options.upsert = false;
}
//add $set for data
let flag = true;
for(let key in data){
if(key[0] !== '$'){
flag = false;
break;
}
}
if(!flag){
data = {$set: data};
}
// update operator
// http://docs.mongodb.org/manual/reference/operator/update/#id1
return collection.update(where, data, options);
}
/**
* delete data
* @param {Object} options []
* @return {Promise} []
*/
async delete(options){
let collection = await this.collection(options.table);
let where = this.parseWhere(options.where);
let limit = this.parseLimit(options.limit);
//delete one row
let removeOpt = {};
if(limit[1] === 1){
removeOpt.justOne = true;
}
return collection.remove(where, removeOpt);
}
/**
* get count
* @param {Object} options []
* @return {Promise} []
*/
async count(options){
let collection = await this.collection(options.table);
let where = this.parseWhere(options.where);
let group = this.group(options.group);
group.total = {$sum: 1};
let order = this.parseOrder(options.order);
let aggregate = [];
if(!think.isEmpty(where)){
aggregate.push({$match: where});
}
aggregate.push({$group: group});
if(!think.isEmpty(order)){
aggregate.push({$sort: order});
}
//make aggregate method to be a promise
let fn = think.promisify(collection.aggregate, collection);
return fn(aggregate).then(data => {
return data[0] && data[0].total || 0;
});
}
/**
* get sum
* @param {Object} options []
* @return {Promise} []
*/
async sum(options){
let collection = await this.collection(options.table);
let where = this.parseWhere(options.where);
let group = this.group(options.group);
group.total = {$sum: `$${options.field}`};
let order = this.parseOrder(options.order);
let aggregate = [];
if(!think.isEmpty(where)){
aggregate.push({$match: where});
}
aggregate.push({$group: group});
if(!think.isEmpty(order)){
aggregate.push({$sort: order});
}
//make aggregate method to be a promise
let fn = think.promisify(collection.aggregate, collection);
return fn(aggregate).then(data => {
return data[0] && data[0].total || 0;
});
}
/**
* create collection indexes
* @param {String} table []
* @param {Object} indexes []
* @return {Promise} []
*/
ensureIndex(table, indexes, options = {}){
if(options === true){
options = {unique: true};
}
if(think.isString(indexes)){
indexes = indexes.split(/\s*,\s*/);
}
if(think.isArray(indexes)){
let result = {};
indexes.forEach(item => {
result[item] = 1;
});
indexes = result;
}
return this.collection(table).then(collection => {
return collection.ensureIndex(indexes, options);
});
}
/**
* aggregate
* @param {String} table []
* @param {Object} options []
* @return {Promise} []
*/
aggregate(table, options){
return this.collection(table).then(collection => {
let fn = think.promisify(collection.aggregate, collection);
return fn(options);
});
}
/**
* close socket
* @return {} []
*/
close(){
if(this._socket){
this._socket.close();
this._socket = null;
}
}
} |
// Generated by LiveScript 1.5.0
/**
* @package CleverStyle Widgets
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @license 0BSD
*/
(function(){
csw.behaviors.csIcon = [
csw.behaviors.tooltip, {
observers: ['_icon_changed(icon, flipX, flipY, mono, rotate, spin, spinStep)'],
properties: {
icon: {
reflectToAttribute: true,
type: String
},
flipX: {
reflectToAttribute: true,
type: Boolean,
value: false
},
flipY: {
reflectToAttribute: true,
type: Boolean,
value: false
},
mono: {
reflectToAttribute: true,
type: Boolean,
value: false
},
rotate: {
reflectToAttribute: true,
type: Number,
value: false
},
spin: {
reflectToAttribute: true,
type: Boolean,
value: false
},
spinStep: {
reflectToAttribute: true,
type: Boolean,
value: false
},
multiple: {
type: Boolean,
value: false
},
stacked1: String,
stacked2: String,
regular: String
},
_icon_changed: function(icon, flipX, flipY, mono, rotate, spin, spinStep){
var class_prefix, icons;
if (!icon) {
this.hidden = true;
return;
} else if (this.hidden) {
this.hidden = false;
}
class_prefix = '';
if (flipX) {
class_prefix += 'fa-flip-horizontal ';
}
if (flipY) {
class_prefix += 'fa-flip-vertical ';
}
if (mono) {
class_prefix += 'fa-fw ';
}
if (rotate) {
class_prefix += "fa-rotate-" + rotate + " ";
}
if (spin) {
class_prefix += 'fa-spin ';
}
if (spinStep) {
class_prefix += 'fa-pulse ';
}
class_prefix += 'fa ';
icons = icon.split(' ');
this.multiple = icons.length > 1;
if (this.multiple) {
this.stacked1 = class_prefix + this._full_icon_name(icons[0]) + 'fa-stack-2x';
this.stacked2 = class_prefix + this._full_icon_name(icons[1]) + 'fa-stack-1x fa-inverse';
} else {
this.regular = class_prefix + this._full_icon_name(icons[0]);
}
},
_full_icon_name: function(name){
var ref$;
if ((ref$ = name.split('-')[0]) === 'fab' || ref$ === 'fa' || ref$ === 'fas' || ref$ === 'far') {
return name;
} else {
return 'fab-' + name + ' fa-' + name;
}
}
}
];
}).call(this);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
fillOpacity: ".3",
d: "M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"
})]
}), 'Battery50TwoTone');
exports.default = _default; |
const web3 = require('web3');
const Example = artifacts.require("Example");
const IsLibrary = artifacts.require("IsLibrary");
const UsesExample = artifacts.require("UsesExample");
const UsesLibrary = artifacts.require("UsesLibrary");
const PayableExample = artifacts.require("PayableExample");
module.exports = async function(deployer) {
await deployer.deploy(Example);
await deployer.deploy(Example, {overwrite: false});
await deployer.deploy(IsLibrary);
await deployer.link(IsLibrary, UsesLibrary);
await deployer.deploy(UsesExample, IsLibrary.address);
await deployer.deploy(UsesLibrary);
await deployer.deploy(PayableExample, {value: web3.utils.toWei('1', 'ether')});
};
|
const _ = require(`lodash`)
const slash = require(`slash`)
const fs = require(`fs`)
const path = require(`path`)
const crypto = require(`crypto`)
const glob = require(`glob`)
const { store } = require(`../redux`)
const nodeAPIs = require(`../utils/api-node-docs`)
const testRequireError = require(`../utils/test-require-error`)
const report = require(`gatsby-cli/lib/reporter`)
function createFileContentHash(root, globPattern) {
const hash = crypto.createHash(`md5`)
const files = glob.sync(`${root}/${globPattern}`, { nodir: true })
files.forEach(filepath => {
hash.update(fs.readFileSync(filepath))
})
return hash.digest(`hex`)
}
/**
* @typedef {Object} PluginInfo
* @property {string} resolve The absolute path to the plugin
* @property {string} name The plugin name
* @property {string} version The plugin version (can be content hash)
*/
/**
* resolvePlugin
* @param {string} pluginName
* This can be a name of a local plugin, the name of a plugin located in
* node_modules, or a Gatsby internal plugin. In the last case the pluginName
* will be an absolute path.
* @return {PluginInfo}
*/
function resolvePlugin(pluginName) {
// Only find plugins when we're not given an absolute path
if (!fs.existsSync(pluginName)) {
// Find the plugin in the local plugins folder
const resolvedPath = slash(path.resolve(`./plugins/${pluginName}`))
if (fs.existsSync(resolvedPath)) {
if (fs.existsSync(`${resolvedPath}/package.json`)) {
const packageJSON = JSON.parse(
fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`)
)
return {
resolve: resolvedPath,
name: packageJSON.name || pluginName,
id: `Plugin ${packageJSON.name || pluginName}`,
version:
packageJSON.version || createFileContentHash(resolvedPath, `**`),
}
} else {
// Make package.json a requirement for local plugins too
throw new Error(`Plugin ${pluginName} requires a package.json file`)
}
}
}
/**
* Here we have an absolute path to an internal plugin, or a name of a module
* which should be located in node_modules.
*/
try {
const resolvedPath = slash(path.dirname(require.resolve(pluginName)))
const packageJSON = JSON.parse(
fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`)
)
return {
resolve: resolvedPath,
id: `Plugin ${packageJSON.name}`,
name: packageJSON.name,
version: packageJSON.version,
}
} catch (err) {
throw new Error(`Unable to find plugin "${pluginName}"`)
}
}
module.exports = async (config = {}) => {
// Instantiate plugins.
const plugins = []
// Create fake little site with a plugin for testing this
// w/ snapshots. Move plugin processing to its own module.
// Also test adding to redux store.
const processPlugin = plugin => {
if (_.isString(plugin)) {
const info = resolvePlugin(plugin)
return {
...info,
pluginOptions: {
plugins: [],
},
}
} else {
// Plugins can have plugins.
const subplugins = []
if (plugin.options && plugin.options.plugins) {
plugin.options.plugins.forEach(p => {
subplugins.push(processPlugin(p))
})
plugin.options.plugins = subplugins
}
// Add some default values for tests as we don't actually
// want to try to load anything during tests.
if (plugin.resolve === `___TEST___`) {
return {
name: `TEST`,
pluginOptions: {
plugins: [],
},
}
}
const info = resolvePlugin(plugin.resolve)
return {
...info,
pluginOptions: _.merge({ plugins: [] }, plugin.options),
}
}
}
// Add internal plugins
plugins.push(
processPlugin(path.join(__dirname, `../internal-plugins/dev-404-page`))
)
plugins.push(
processPlugin(
path.join(__dirname, `../internal-plugins/component-page-creator`)
)
)
plugins.push(
processPlugin(
path.join(__dirname, `../internal-plugins/component-layout-creator`)
)
)
plugins.push(
processPlugin(
path.join(__dirname, `../internal-plugins/internal-data-bridge`)
)
)
plugins.push(
processPlugin(path.join(__dirname, `../internal-plugins/prod-404`))
)
plugins.push(
processPlugin(path.join(__dirname, `../internal-plugins/query-runner`))
)
// Add plugins from the site config.
if (config.plugins) {
config.plugins.forEach(plugin => {
plugins.push(processPlugin(plugin))
})
}
// Add the site's default "plugin" i.e. gatsby-x files in root of site.
plugins.push({
resolve: slash(process.cwd()),
id: `Plugin default-site-plugin`,
name: `default-site-plugin`,
version: createFileContentHash(process.cwd(), `gatsby-*`),
pluginOptions: {
plugins: [],
},
})
// Create a "flattened" array of plugins with all subplugins
// brought to the top-level. This simplifies running gatsby-* files
// for subplugins.
const flattenedPlugins = []
const extractPlugins = plugin => {
plugin.pluginOptions.plugins.forEach(subPlugin => {
flattenedPlugins.push(subPlugin)
extractPlugins(subPlugin)
})
}
plugins.forEach(plugin => {
flattenedPlugins.push(plugin)
extractPlugins(plugin)
})
// Validate plugins before saving. Plugins can only export known APIs. The known
// APIs that a plugin supports are saved along with the plugin in the store for
// easier filtering later. If there are bad exports (either typos, outdated, or
// plain incorrect), then we output a readable error & quit.
const apis = _.keys(nodeAPIs)
const apiToPlugins = apis.reduce((acc, value) => {
acc[value] = []
return acc
}, {})
let badExports = []
flattenedPlugins.forEach(plugin => {
let gatsbyNode
plugin.nodeAPIs = []
try {
gatsbyNode = require(`${plugin.resolve}/gatsby-node`)
} catch (err) {
if (!testRequireError(`gatsby-node`, err)) {
// ignore
} else {
report.panic(`Error requiring ${plugin.resolve}/gatsby-node.js`, err)
}
}
if (gatsbyNode) {
const gatsbyNodeKeys = _.keys(gatsbyNode)
// Discover which nodeAPIs this plugin implements and store
// an array against the plugin node itself *and* in a node
// API to plugins map for faster lookups later.
plugin.nodeAPIs = _.intersection(gatsbyNodeKeys, apis)
plugin.nodeAPIs.map(nodeAPI => apiToPlugins[nodeAPI].push(plugin.name))
// Discover any exports from plugins which are not "known"
badExports = badExports.concat(
_.difference(gatsbyNodeKeys, apis).map(e => {
return {
exportName: e,
pluginName: plugin.name,
pluginVersion: plugin.version,
}
})
)
}
})
if (badExports.length > 0) {
const stringSimiliarity = require(`string-similarity`)
const { stripIndent } = require(`common-tags`)
console.log(`\n`)
console.log(
stripIndent`
Your plugins must export known APIs from their gatsby-node.js.
The following exports aren't APIs. Perhaps you made a typo or
your plugin is outdated?
See https://www.gatsbyjs.org/docs/node-apis/ for the list of Gatsby Node APIs`
)
badExports.forEach(bady => {
const similarities = stringSimiliarity.findBestMatch(
bady.exportName,
apis
)
let message = `\n — `
if (bady.pluginName == `default-site-plugin`) {
message += `Your site's gatsby-node.js is exporting a variable named "${
bady.exportName
}" which isn't an API.`
} else {
message += `The plugin "${bady.pluginName}@${
bady.pluginVersion
}" is exporting a variable named "${
bady.exportName
}" which isn't an API.`
}
if (similarities.bestMatch.rating > 0.5) {
message += ` Perhaps you meant to export "${
similarities.bestMatch.target
}"?`
}
console.log(message)
})
process.exit()
}
store.dispatch({
type: `SET_SITE_PLUGINS`,
payload: plugins,
})
store.dispatch({
type: `SET_SITE_FLATTENED_PLUGINS`,
payload: flattenedPlugins,
})
store.dispatch({
type: `SET_SITE_API_TO_PLUGINS`,
payload: apiToPlugins,
})
return flattenedPlugins
}
|
// Shim & native-safe ownerDocument lookup
var owner = (document._currentScript || document.currentScript).ownerDocument;
class MetaTableController extends MRM.MetaComponentController{
constructor(dom){
super(dom);
this.dom = dom;
this.setupComponent();
this.parent = dom.parentElement.controller;
this.metaObject = this.createMetaObject();
this.computedProperties = {};
this.computedPropertiesKey.forEach((key) => {
var settings = this.computedPropertiesSettings[key];
var value = settings.type(this.properties[key] || settings.default)
Object.defineProperty(this.computedProperties, key, {
get: function(){
return value
},
set: (inputValue) => {
value = settings.type(inputValue)
}
})
});
this.updateMetaObject();
}
get computedPropertiesKey(){
return Object.keys(this.computedPropertiesSettings);
}
createMetaObject(){
var group = new THREE.Group();
// need to have table geometry, set all visible none
var height = this.properties.height || 1;
var width = this.properties.width || 1;
var depth = this.properties.length || 1;
var geometry = new THREE.TableGeometry(width, height, depth, 0.03, 0.01, 0.01, 0.01);
var materials = [new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
new THREE.MeshPhongMaterial( { visible: false } ),
];
var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial( materials ));
mesh.rotation.x = 90 * (Math.PI/180);
mesh.castShadow = true;
mesh.receiveShadow = true;
var group = new THREE.Group();
group.add( mesh );
return {
group: group,
mesh: mesh
}
}
get metaAttachedActions(){
return {
"attachMetaObject": true,
"updateChildrenDisplayInline": true
}
}
get eventActionSettings(){
return {
"width": ["updateChildrenDisplayInline"],
"length": ["updateChildrenDisplayInline"],
"meta-style": ['propagateMetaStyle'],
"class": ["propagateMetaStyle"],
"id": ["propagateMetaStyle"]
}
}
get computedPropertiesSettings(){
return {
width: {
type: Number,
default: null,
},
length: {
type: Number,
default: null,
},
height: {
type: Number,
default: null
}
};
}
get propertiesSettings() {
return {
width: {
type: Number,
default: null,
attrName: 'width',
onChange: (value)=>{
this.computedProperties.width = value;
this.forEachMetaChildren((child)=>{
child.controller.properties.tableWidth = value
})
}
},
height: {
type: Number,
default: null,
attrName: 'height',
onChange: (value)=>{
this.computedProperties.height = value;
this.forEachMetaChildren((child)=>{
child.controller.properties.tableHeight = value
})
}
},
length: {
type: Number,
default: null,
attrName: 'length',
onChange: (value)=>{
this.computedProperties.length = value;
this.forEachMetaChildren((child)=>{
child.controller.properties.tableLength = value
})
}
},
tsurfaceThickness: {
type: Number,
default: 1,
onChange: "updateDimension"
},
tbottomThickness: {
type: Number,
default: 1,
onChange: "updateDimension"
},
tbottomPadding: {
type: Number,
default: 1,
onChange: "updateDimension"
},
"left": {
type: Boolean,
default: false,
facesStartIndexes: [2, 3, 4],
onChange: "updateFaceVisibility",
querySelector: "meta-tbottom[align= left]"
},
"right": {
type: Boolean,
default: false,
facesStartIndexes: [0, 6, 7],
onChange: "updateFaceVisibility",
querySelector: "meta-tbottom[align= right]"
},
"front": {
type: Boolean,
default: false,
facesStartIndexes: [0, 1, 2],
onChange: "updateFaceVisibility",
querySelector: "meta-tbottom[align= front]"
},
"back": {
type: Boolean,
default: false,
facesStartIndexes: [4, 5, 6],
onChange: "updateFaceVisibility",
querySelector: "meta-tbottom[align= back]"
},
"surface": {
type: Boolean,
default: false,
facesStartIndexes: [8],
onChange: "updateFaceVisibility",
querySelector: "meta-tsurface"
},
onSelect: {type: String, default: '', attrName: 'onSelect' }
}
}
get tagName() {
return "meta-table";
}
get metaChildrenNames(){
return ['meta-tsurface', 'meta-tbottom']
}
resetComputedProperties(){
this.computedPropertiesKey.forEach((key) => {
this.computedProperties[key] = this.properties[key];
});
}
updateMetaObject (){
this.metaObject.group.position.z = this.properties.height / 2 || 0.5;
var geometry = this.metaObject.mesh.geometry,
tbottomPaddingTop = this.metaStyle['tbottom-padding-top'] || this.metaStyle['tbottom-padding'] || geometry.parameters.tbottomPadding || 0,
tbottomPaddingBottom = this.metaStyle['tbottom-padding-bottom'] || this.metaStyle['tbottom-padding'] || geometry.parameters.tbottomPadding || 0,
tsurfaceThickness = this.metaStyle['thickness'] || 0.03,
tbottomThickness = this.metaStyle['thickness'] || 0.03,
width = this.properties.width || this.computedProperties.width || 1,
length = this.properties.length || this.computedProperties.length || 1,
height = this.properties.height || this.computedProperties.height || 1;
geometry.update(width, height, length, tsurfaceThickness, tbottomThickness, tbottomPaddingTop, tbottomPaddingBottom);
if(this.metaStyle.metaStyle["position"] === 'absolute'){
this.setAbsolutePostion();
}
this.metaObject.mesh.userData.dom = this.dom;
}
setAbsolutePostion(){
var group = this.metaObject.group;
if(this.metaStyle.metaStyle.hasOwnProperty('left')){
group.position.x = - (this.parent.properties.width/2) + (this.metaStyle["left"] || 0) + (this.properties.width/2);
}
else if(this.metaStyle.metaStyle.hasOwnProperty('right')){
group.position.x = - (- (this.parent.properties.width/2) + (this.metaStyle["right"] || 0) + (this.properties.width/2));
}
if(this.metaStyle.metaStyle.hasOwnProperty('top')){
group.position.y = (this.parent.properties.length/2) - (this.metaStyle["top"] || 0) - (this.properties.length/2);
}
else if(this.metaStyle.metaStyle.hasOwnProperty('bottom')){
group.position.y = - ((this.parent.properties.length/2) - (this.metaStyle["bottom"] || 0) - (this.properties.length/2));
}
group.position.z = (this.parent.properties.height/2 || 0) + (this.metaStyle["z"] || 0) + (this.properties.height/2 || 0);
if(this.metaStyle.metaStyle['rotate-x']){
group.rotation.x = this.metaStyle.metaStyle['rotate-x'] * (Math.PI / 180);
}
if(this.metaStyle.metaStyle['rotate-y']){
group.rotation.y = this.metaStyle.metaStyle['rotate-y'] * (Math.PI / 180);
}
if(this.metaStyle.metaStyle['rotate-z']){
group.rotation.z = this.metaStyle.metaStyle['rotate-z'] * (Math.PI / 180);
}
}
updateTableDimension(targetController){
targetController.properties.tableWidth = this.properties.width
targetController.properties.tableHeight = this.properties.height
targetController.properties.tableLength = this.properties.length
}
updateTbottomVisibility(targetController, oldValue, newValue){
oldValue = oldValue || "front"
this.properties[oldValue] = false;
this.properties[targetController.properties.align] = true;
}
updateTSurfaceVisibility(targetController){
this.properties['surface'] = true;
}
updateFaceVisibility(value, oldValue, key){
this.metaObject.mesh.material.materials.forEach(function(material){
material.visible = false
});
_.forEach(this.dom.querySelectorAll(":scope > meta-tbottom, :scope > meta-tsurface"), (element) => {
var controller = element.controller
if(!controller) {
return;
}
if (controller.tagName === 'meta-tbottom') {
switch(controller.properties.align) {
case 'left':
// TODO: use propertiesSettings face name
this.metaObject.mesh.material.materials[2].visible = true;
this.metaObject.mesh.material.materials[3].visible = true;
this.metaObject.mesh.material.materials[4].visible = true;
break;
case 'right':
this.metaObject.mesh.material.materials[0].visible = true;
this.metaObject.mesh.material.materials[6].visible = true;
this.metaObject.mesh.material.materials[7].visible = true;
break;
case 'front':
this.metaObject.mesh.material.materials[0].visible = true;
this.metaObject.mesh.material.materials[1].visible = true;
this.metaObject.mesh.material.materials[2].visible = true;
break;
case 'back':
this.metaObject.mesh.material.materials[4].visible = true;
this.metaObject.mesh.material.materials[5].visible = true;
this.metaObject.mesh.material.materials[6].visible = true;
break;
}
} else if (controller.tagName === 'meta-tsurface'){
this.metaObject.mesh.material.materials[8].visible = true;
}
});
}
}
class MetaTable extends MRM.MetaComponent {
createdCallback() {
this.controller = new MetaTableController(this);
super.createdCallback()
}
metaDetached(e) {
var targetController = e.detail.controller;
if (this.controller.isChildren(targetController.tagName) ){
e.stopPropagation();
if(targetController.tagName === 'meta-tsurface'){
this.controller.properties['surface'] = false;
}else{
this.controller.properties[targetController.properties.align] = false;
}
this.controller.metaObject.group.remove(targetController.metaObject.group);
}
}
}
document.registerElement('meta-table', MetaTable);
|
//>>built
define({findLabel:"Najdi:",findTooltip:"Vnesite besedilo za iskanje",replaceLabel:"Zamenjaj z:",replaceTooltip:"Vnesite besedilo za zamenjavo",findReplace:"Najdi in zamenjaj",matchCase:"Razlikuj velike in male \u010drke",matchCaseTooltip:"Razlikuj velike in male \u010drke",backwards:"Nazaj",backwardsTooltip:"Vzvratno iskanje besedila",replaceAllButton:"Zamenjaj vse",replaceAllButtonTooltip:"Zamenjaj celotno besedilo",findButton:"Najdi",findButtonTooltip:"Najdi besedilo",replaceButton:"Zamenjaj",replaceButtonTooltip:"Zamenjaj besedilo",
replaceDialogText:"Zamenjanih ${0} pojavitev.",eofDialogText:"Zadnja pojavitev ${0}",eofDialogTextFind:"najdeno",eofDialogTextReplace:"zamenjano"}); |
module.exports = Cmds.addCommand({
cmds: [";skip"],
requires: {
guild: true,
loud: false
},
desc: "Skip to the next song",
args: "[song_name]",
example: "gonna give you up",
func: (cmd, args, msgObj, speaker, channel, guild) => {
var connection = guild.voiceConnection;
if (connection) {
var guildQueue = Music.guildQueue[guild.id];
var autoPlaylist = Data.guildGet(guild, Data.playlist);
var guildMusicInfo = Music.guildMusicInfo[guild.id];
var firstInQueue = guildQueue[0];
Util.log("Num songs in queue: " + guildQueue.length);
if (Util.checkStaff(guild, speaker) || (guildMusicInfo.isAuto == false && guildMusicInfo.activeAuthor.id == speaker.id)) {
if (guildMusicInfo.isAuto == false && guildQueue.length > 0 && guildMusicInfo.activeSong != null && guildMusicInfo.activeSong.title == firstInQueue[0].title) guildQueue.splice(0, 1);
Util.log(guildMusicInfo.isAuto == false + " | " + guildQueue.length + " | " + guildMusicInfo.activeSong + " | " + ((guildMusicInfo.activeSong && firstInQueue) ? guildMusicInfo.activeSong.title == firstInQueue[0].title : "N/A") + " | " + (guildMusicInfo.activeSong ? guildMusicInfo.activeSong.title : "N/A") + " | " + (firstInQueue ? firstInQueue[0].title : "N/A"))
Music.playNextQueue(guild, channel, true);
} else {
Util.print(channel, "You are not staff and you did not add this song");
}
}
}
}); |
const logging = require('../../../../../shared/logging');
const commands = require('../../../schema').commands;
const table = 'members';
const message1 = 'Adding table: ' + table;
const message2 = 'Dropping table: ' + table;
module.exports.up = (options) => {
const connection = options.connection;
return connection.schema.hasTable(table)
.then(function (exists) {
if (exists) {
logging.warn(message1);
return;
}
logging.info(message1);
return commands.createTable(table, connection);
});
};
module.exports.down = (options) => {
const connection = options.connection;
return connection.schema.hasTable(table)
.then(function (exists) {
if (!exists) {
logging.warn(message2);
return;
}
logging.info(message2);
return commands.deleteTable(table, connection);
});
};
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
let tests_run = 0;
function pingPongTest(host, on_complete) {
const N = 1000;
let count = 0;
let sent_final_ping = false;
const server = net.createServer({ allowHalfOpen: true }, function(socket) {
assert.strictEqual(socket.remoteAddress !== null, true);
assert.strictEqual(socket.remoteAddress !== undefined, true);
const address = socket.remoteAddress;
if (host === '127.0.0.1') {
assert.strictEqual(address, '127.0.0.1');
} else if (host == null || host === 'localhost') {
assert(address === '127.0.0.1' || address === '::ffff:127.0.0.1');
} else {
console.log(`host = ${host}, remoteAddress = ${address}`);
assert.strictEqual(address, '::1');
}
socket.setEncoding('utf8');
socket.setNoDelay();
socket.timeout = 0;
socket.on('data', function(data) {
console.log(`server got: ${JSON.stringify(data)}`);
assert.strictEqual(socket.readyState, 'open');
assert.strictEqual(count <= N, true);
if (/PING/.test(data)) {
socket.write('PONG');
}
});
socket.on('end', function() {
assert.strictEqual(socket.readyState, 'writeOnly');
socket.end();
});
socket.on('close', function(had_error) {
assert.strictEqual(had_error, false);
assert.strictEqual(socket.readyState, 'closed');
socket.server.close();
});
});
server.listen(0, host, function() {
const client = net.createConnection(server.address().port, host);
client.setEncoding('utf8');
client.on('connect', function() {
assert.strictEqual(client.readyState, 'open');
client.write('PING');
});
client.on('data', function(data) {
console.log(`client got: ${data}`);
assert.strictEqual(data, 'PONG');
count += 1;
if (sent_final_ping) {
assert.strictEqual(client.readyState, 'readOnly');
return;
}
assert.strictEqual(client.readyState, 'open');
if (count < N) {
client.write('PING');
} else {
sent_final_ping = true;
client.write('PING');
client.end();
}
});
client.on('close', function() {
assert.strictEqual(count, N + 1);
assert.strictEqual(sent_final_ping, true);
if (on_complete) on_complete();
tests_run += 1;
});
});
}
// All are run at once and will run on different ports.
pingPongTest('localhost');
pingPongTest(null);
// This IPv6 isn't working on Solaris.
if (!common.isSunOS) pingPongTest('::1');
process.on('exit', function() {
assert.strictEqual(tests_run, common.isSunOS ? 2 : 3);
});
|
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
|
'use strict';var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var property_binding_parser_1 = require('./property_binding_parser');
var text_interpolation_parser_1 = require('./text_interpolation_parser');
var directive_parser_1 = require('./directive_parser');
var view_splitter_1 = require('./view_splitter');
var style_encapsulator_1 = require('./style_encapsulator');
var CompileStepFactory = (function () {
function CompileStepFactory() {
}
CompileStepFactory.prototype.createSteps = function (view) { return null; };
return CompileStepFactory;
})();
exports.CompileStepFactory = CompileStepFactory;
var DefaultStepFactory = (function (_super) {
__extends(DefaultStepFactory, _super);
function DefaultStepFactory(_parser, _appId) {
_super.call(this);
this._parser = _parser;
this._appId = _appId;
this._componentUIDsCache = new Map();
}
DefaultStepFactory.prototype.createSteps = function (view) {
return [
new view_splitter_1.ViewSplitter(this._parser),
new property_binding_parser_1.PropertyBindingParser(this._parser),
new directive_parser_1.DirectiveParser(this._parser, view.directives),
new text_interpolation_parser_1.TextInterpolationParser(this._parser),
new style_encapsulator_1.StyleEncapsulator(this._appId, view, this._componentUIDsCache)
];
};
return DefaultStepFactory;
})(CompileStepFactory);
exports.DefaultStepFactory = DefaultStepFactory;
//# sourceMappingURL=compile_step_factory.js.map |
import { app, BrowserWindow } from 'electron';
let mainWindow = null;
let path = app.getPath('exe')
app.on('window-all-closed', () => {
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', () => {
console.log(path)
mainWindow = new BrowserWindow({width: 800, height: 600, globals: {id: 17}});
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.on('closed', () => {
mainWindow = null;
});
}); |
import slack from 'slack'
export default class SlackAPI {
constructor (token) {
this.token = token
this.slack = slack
}
users () {
return new Promise((resolve, reject) => {
this.slack.users.list({ token: this.token }, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
channels () {
return new Promise((resolve, reject) => {
this.slack.channels.list({ token: this.token }, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
channelHistory (channel, latest) {
return new Promise((resolve, reject) => {
const params = { token: this.token, channel, latest }
this.slack.channels.history(params, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
groups () {
return new Promise((resolve, reject) => {
this.slack.groups.list({ token: this.token }, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
groupHistory (channel, latest) {
return new Promise((resolve, reject) => {
const params = { token: this.token, channel, latest }
this.slack.groups.history(params, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
im () {
return new Promise((resolve, reject) => {
this.slack.im.list({ token: this.token }, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
imHistory (channel, latest) {
return new Promise((resolve, reject) => {
const params = { token: this.token, channel, latest }
this.slack.im.history(params, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
mpim () {
return new Promise((resolve, reject) => {
this.slack.mpim.list({ token: this.token }, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
mpimHistory (channel, latest) {
return new Promise((resolve, reject) => {
const params = { token: this.token, channel, latest }
this.slack.mpim.history(params, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
getSelfData () {
return new Promise((resolve, reject) => {
this.slack.auth.test({ token: this.token }, (err, res) => {
if (err)
reject(err)
else
resolve(res)
})
})
}
}
|
/**
* Test dependencies
*/
var assert = require('assert'),
Record = require('../../lib/record'),
RID = require('orientjs').RID,
_ = require('lodash'),
util = require('util');
describe('record helper class', function () {
var record;
before(function(done){
record = new Record();
done();
});
it('normalizeId: should correctly normalize an id', function (done) {
var collection1 = {
name: 'no id collection'
};
var testCollection1 = _.clone(collection1);
record.normalizeId(testCollection1);
assert(_.isEqual(testCollection1, collection1));
var testCollection2 = {
name: 'id collection',
id: '#1:0'
};
record.normalizeId(testCollection2);
assert(_.isUndefined(testCollection2.id));
assert(testCollection2['@rid'] instanceof RID);
assert.equal(testCollection2['@rid'].cluster, 1);
assert.equal(testCollection2['@rid'].position, 0);
assert(_.isEqual(testCollection2['@rid'], new RID('#1:0')), 'not equal to RID(\'#1:0\'), actual value: ' + util.inspect(testCollection2['@rid']));
var testCollection3 = {
name: 'id collection',
'@rid': new RID('#2:0')
};
record.normalizeId(testCollection3);
assert(_.isUndefined(testCollection3.id));
assert(_.isEqual(testCollection3['@rid'], new RID('#2:0')));
var testCollection4 = {
name: 'id collection',
id: '#1:0',
'@rid': new RID('#2:0')
};
record.normalizeId(testCollection4);
assert(_.isUndefined(testCollection4.id));
assert(_.isEqual(testCollection4['@rid'], new RID('#1:0')));
done();
});
});
|
/**
* KineticJS 3d JavaScript Library v1.0.0
* http://www.kineticjs.com/
* Copyright 2011, Eric Rowell
* Licensed under the MIT or GPL Version 2 licenses.
* Date: Aug 01 2011
*
* Copyright (C) 2011 by Eric Rowell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Kinetic_3d = function(canvasId){
this.canvas = document.getElementById(canvasId);
this.context = this.canvas.getContext("experimental-webgl");
this.drawStage = undefined;
// Canvas Events
this.mousePos = null;
this.mouseDown = false;
this.mouseUp = false;
// Animation
this.t = 0;
this.timeInterval = 0;
this.startTime = 0;
this.lastTime = 0;
this.frame = 0;
this.animating = false;
// provided by Paul Irish
window.requestAnimFrame = (function(callback){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
// initialize Brandon Jones's excellent glMatrix
this.initGlMatrix();
// shader type constants
this.BLUE_COLOR = "BLUE_COLOR";
this.VARYING_COLOR = "VARYING_COLOR";
this.TEXTURE = "TEXTURE";
this.TEXTURE_DIRECTIONAL_LIGHTING = "TEXTURE_DIRECTIONAL_LIGHTING";
this.shaderProgram = null;
this.mvMatrix = this.mat4.create();
this.pMatrix = this.mat4.create();
this.mvMatrixStack = [];
this.context.viewportWidth = this.canvas.width;
this.context.viewportHeight = this.canvas.height;
// init depth test
this.context.enable(this.context.DEPTH_TEST);
};
// ======================================= GENERAL =======================================
Kinetic_3d.prototype.getContext = function(){
return this.context;
};
Kinetic_3d.prototype.getCanvas = function(){
return this.canvas;
};
Kinetic_3d.prototype.clear = function(){
this.context.viewport(0, 0, this.context.viewportWidth, this.context.viewportHeight);
this.context.clear(this.context.COLOR_BUFFER_BIT | this.context.DEPTH_BUFFER_BIT);
};
Kinetic_3d.prototype.getCanvasPos = function(){
var obj = this.getCanvas();
var top = 0;
var left = 0;
while (obj.tagName != "BODY") {
top += obj.offsetTop;
left += obj.offsetLeft;
obj = obj.offsetParent;
}
return {
top: top,
left: left
};
};
// ======================================= STAGE =======================================
Kinetic_3d.prototype.setDrawStage = function(func){
this.drawStage = func;
this.listen();
};
Kinetic_3d.prototype.drawStage = function(){
if (this.drawStage !== undefined) {
this.drawStage();
}
};
// ======================================= CANVAS EVENTS =======================================
Kinetic_3d.prototype.reset = function(evt){
this.setMousePosition(evt);
if (!this.animating && this.drawStage !== undefined) {
this.drawStage();
}
this.mouseDown = false;
this.mouseUp = false;
};
Kinetic_3d.prototype.isMousedown = function(){
return this.mouseDown;
};
Kinetic_3d.prototype.isMouseup = function(){
return this.mouseUp;
};
Kinetic_3d.prototype.listen = function(){
// store current listeners
var that = this;
var canvasOnmousemove = this.canvas.onmousemove;
var canvasOnmousedown = this.canvas.onmousedown;
var canvasOnmouseup = this.canvas.onmouseup;
this.canvas.onmousemove = function(e){
if (!e) {
e = window.event;
}
that.reset(e);
if (typeof(canvasOnmousemove) == typeof(Function)) {
canvasOnmousemove(e);
}
};
this.canvas.onmousedown = function(e){
if (!e) {
e = window.event;
}
that.mouseDown = true;
that.reset(e);
if (typeof(canvasOnmousedown) == typeof(Function)) {
canvasOnmousedown(e);
}
};
this.canvas.onmouseup = function(e){
if (!e) {
e = window.event;
}
that.mouseUp = true;
that.reset(e);
if (typeof(canvasOnmouseup) == typeof(Function)) {
canvasOnmouseup(e);
}
};
};
Kinetic_3d.prototype.getMousePos = function(evt){
return this.mousePos;
};
Kinetic_3d.prototype.setMousePosition = function(evt){
var mouseX = evt.clientX - this.getCanvasPos().left + window.pageXOffset;
var mouseY = evt.clientY - this.getCanvasPos().top + window.pageYOffset;
this.mousePos = {
x: mouseX,
y: mouseY
};
};
// ======================================= ANIMATION =======================================
Kinetic_3d.prototype.isAnimating = function(){
return this.animating;
};
Kinetic_3d.prototype.getFrame = function(){
return this.frame;
};
Kinetic_3d.prototype.startAnimation = function(){
this.animating = true;
var date = new Date();
this.startTime = date.getTime();
this.lastTime = this.startTime;
if (this.drawStage !== undefined) {
this.drawStage();
}
this.animationLoop();
};
Kinetic_3d.prototype.stopAnimation = function(){
this.animating = false;
};
Kinetic_3d.prototype.getTimeInterval = function(){
return this.timeInterval;
};
Kinetic_3d.prototype.getTime = function(){
return this.t;
};
Kinetic_3d.prototype.getFps = function(){
return 1000 / this.timeInterval;
};
Kinetic_3d.prototype.animationLoop = function(){
var that = this;
this.frame++;
var date = new Date();
var thisTime = date.getTime();
this.timeInterval = thisTime - this.lastTime;
this.t += this.timeInterval;
this.lastTime = thisTime;
if (this.drawStage !== undefined) {
this.drawStage();
}
if (this.animating) {
requestAnimFrame(function(){
that.animationLoop();
});
}
};
// ======================================= WEBGL WRAPPER =======================================
Kinetic_3d.prototype.save = function(){
var copy = this.mat4.create();
this.mat4.set(this.mvMatrix, copy);
this.mvMatrixStack.push(copy);
};
Kinetic_3d.prototype.restore = function(){
if (this.mvMatrixStack.length == 0) {
throw "Invalid popMatrix!";
}
this.mvMatrix = this.mvMatrixStack.pop();
};
Kinetic_3d.prototype.getFragmentShaderGLSL = function(shaderType){
switch (shaderType) {
case this.BLUE_COLOR:
return "#ifdef GL_ES\n" +
"precision highp float;\n" +
"#endif\n" +
"void main(void) {\n" +
"gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);\n" +
"}";
case this.VARYING_COLOR:
return "#ifdef GL_ES\n" +
"precision highp float;\n" +
"#endif\n" +
"varying vec4 vColor;\n" +
"void main(void) {\n" +
"gl_FragColor = vColor;\n" +
"}";
case this.TEXTURE:
return "#ifdef GL_ES\n" +
"precision highp float;\n" +
"#endif\n" +
"varying vec2 vTextureCoord;\n" +
"uniform sampler2D uSampler;\n" +
"void main(void) {\n" +
"gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));\n" +
"}";
case this.TEXTURE_DIRECTIONAL_LIGHTING:
return "#ifdef GL_ES\n" +
"precision highp float;\n" +
"#endif\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec3 vLightWeighting;\n" +
"uniform sampler2D uSampler;\n" +
"void main(void) {\n" +
"vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));\n" +
"gl_FragColor = vec4(textureColor.rgb * vLightWeighting, textureColor.a);\n" +
"}";
}
};
Kinetic_3d.prototype.getVertexShaderGLSL = function(shaderType){
switch (shaderType) {
case this.BLUE_COLOR:
return "attribute vec3 aVertexPosition;\n" +
"uniform mat4 uMVMatrix;\n" +
"uniform mat4 uPMatrix;\n" +
"void main(void) {\n" +
"gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n" +
"}";
case this.VARYING_COLOR:
return "attribute vec3 aVertexPosition;\n" +
"attribute vec4 aVertexColor;\n" +
"uniform mat4 uMVMatrix;\n" +
"uniform mat4 uPMatrix;\n" +
"varying vec4 vColor;\n" +
"void main(void) {\n" +
"gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n" +
"vColor = aVertexColor;\n" +
"}";
case this.TEXTURE:
return "attribute vec3 aVertexPosition;\n" +
"attribute vec2 aTextureCoord;\n" +
"uniform mat4 uMVMatrix;\n" +
"uniform mat4 uPMatrix;\n" +
"varying vec2 vTextureCoord;\n" +
"void main(void) {\n" +
"gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n" +
"vTextureCoord = aTextureCoord;\n" +
"}";
case this.TEXTURE_DIRECTIONAL_LIGHTING:
return "attribute vec3 aVertexPosition;\n" +
"attribute vec3 aVertexNormal;\n" +
"attribute vec2 aTextureCoord;\n" +
"uniform mat4 uMVMatrix;\n" +
"uniform mat4 uPMatrix;\n" +
"uniform mat3 uNMatrix;\n" +
"uniform vec3 uAmbientColor;\n" +
"uniform vec3 uLightingDirection;\n" +
"uniform vec3 uDirectionalColor;\n" +
"uniform bool uUseLighting;\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec3 vLightWeighting;\n" +
"void main(void) {\n" +
"gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n" +
"vTextureCoord = aTextureCoord;\n" +
"if (!uUseLighting) {\n" +
"vLightWeighting = vec3(1.0, 1.0, 1.0);\n" +
"} else {\n" +
"vec3 transformedNormal = uNMatrix * aVertexNormal;\n" +
"float directionalLightWeighting = max(dot(transformedNormal, uLightingDirection), 0.0);\n" +
"vLightWeighting = uAmbientColor + uDirectionalColor * directionalLightWeighting;\n" +
"}\n" +
"}";
}
};
Kinetic_3d.prototype.initShaders = function(shaderType){
this.initPositionShader();
switch (shaderType) {
case this.VARYING_COLOR:
this.initColorShader();
break;
case this.TEXTURE:
this.initTextureShader();
break;
case this.TEXTURE_DIRECTIONAL_LIGHTING:
this.initTextureShader();
this.initNormalShader();
this.initLightingShader();
break;
}
};
Kinetic_3d.prototype.setShaderProgram = function(shaderType){
var fragmentGLSL = this.getFragmentShaderGLSL(shaderType);
var vertexGLSL = this.getVertexShaderGLSL(shaderType);
var fragmentShader = this.context.createShader(this.context.FRAGMENT_SHADER);
this.context.shaderSource(fragmentShader, fragmentGLSL);
this.context.compileShader(fragmentShader);
var vertexShader = this.context.createShader(this.context.VERTEX_SHADER);
this.context.shaderSource(vertexShader, vertexGLSL);
this.context.compileShader(vertexShader);
this.shaderProgram = this.context.createProgram();
this.context.attachShader(this.shaderProgram, vertexShader);
this.context.attachShader(this.shaderProgram, fragmentShader);
this.context.linkProgram(this.shaderProgram);
if (!this.context.getProgramParameter(this.shaderProgram, this.context.LINK_STATUS)) {
alert("Could not initialize shaders");
}
this.context.useProgram(this.shaderProgram);
// once shader program is loaded, it's time to init the shaders
this.initShaders(shaderType);
};
Kinetic_3d.prototype.perspective = function(viewAngle, minDist, maxDist){
this.mat4.perspective(viewAngle, this.context.viewportWidth / this.context.viewportHeight, minDist, maxDist, this.pMatrix);
};
Kinetic_3d.prototype.identity = function(){
this.mat4.identity(this.mvMatrix);
};
Kinetic_3d.prototype.translate = function(x, y, z){
this.mat4.translate(this.mvMatrix, [x, y, z]);
};
Kinetic_3d.prototype.rotate = function(angle, x, y, z){
this.mat4.rotate(this.mvMatrix, angle, [x, y, z]);
};
Kinetic_3d.prototype.initPositionShader = function(){
this.shaderProgram.vertexPositionAttribute = this.context.getAttribLocation(this.shaderProgram, "aVertexPosition");
this.context.enableVertexAttribArray(this.shaderProgram.vertexPositionAttribute);
this.shaderProgram.pMatrixUniform = this.context.getUniformLocation(this.shaderProgram, "uPMatrix");
this.shaderProgram.mvMatrixUniform = this.context.getUniformLocation(this.shaderProgram, "uMVMatrix");
};
Kinetic_3d.prototype.initColorShader = function(){
this.shaderProgram.vertexColorAttribute = this.context.getAttribLocation(this.shaderProgram, "aVertexColor");
this.context.enableVertexAttribArray(this.shaderProgram.vertexColorAttribute);
};
Kinetic_3d.prototype.initTextureShader = function(){
this.shaderProgram.textureCoordAttribute = this.context.getAttribLocation(this.shaderProgram, "aTextureCoord");
this.context.enableVertexAttribArray(this.shaderProgram.textureCoordAttribute);
this.shaderProgram.samplerUniform = this.context.getUniformLocation(this.shaderProgram, "uSampler");
};
Kinetic_3d.prototype.initNormalShader = function(){
this.shaderProgram.vertexNormalAttribute = this.context.getAttribLocation(this.shaderProgram, "aVertexNormal");
this.context.enableVertexAttribArray(this.shaderProgram.vertexNormalAttribute);
this.shaderProgram.nMatrixUniform = this.context.getUniformLocation(this.shaderProgram, "uNMatrix");
};
Kinetic_3d.prototype.initLightingShader = function(){
this.shaderProgram.useLightingUniform = this.context.getUniformLocation(this.shaderProgram, "uUseLighting");
this.shaderProgram.ambientColorUniform = this.context.getUniformLocation(this.shaderProgram, "uAmbientColor");
this.shaderProgram.lightingDirectionUniform = this.context.getUniformLocation(this.shaderProgram, "uLightingDirection");
this.shaderProgram.directionalColorUniform = this.context.getUniformLocation(this.shaderProgram, "uDirectionalColor");
};
Kinetic_3d.prototype.initTexture = function(texture){
this.context.pixelStorei(this.context.UNPACK_FLIP_Y_WEBGL, true);
this.context.bindTexture(this.context.TEXTURE_2D, texture);
this.context.texImage2D(this.context.TEXTURE_2D, 0, this.context.RGBA, this.context.RGBA, this.context.UNSIGNED_BYTE, texture.image);
this.context.texParameteri(this.context.TEXTURE_2D, this.context.TEXTURE_MAG_FILTER, this.context.NEAREST);
this.context.texParameteri(this.context.TEXTURE_2D, this.context.TEXTURE_MIN_FILTER, this.context.LINEAR_MIPMAP_NEAREST);
this.context.generateMipmap(this.context.TEXTURE_2D);
this.context.bindTexture(this.context.TEXTURE_2D, null);
};
Kinetic_3d.prototype.createArrayBuffer = function(vertices){
var buffer = this.context.createBuffer();
buffer.numElements = vertices.length;
this.context.bindBuffer(this.context.ARRAY_BUFFER, buffer);
this.context.bufferData(this.context.ARRAY_BUFFER, new Float32Array(vertices), this.context.STATIC_DRAW);
return buffer;
};
Kinetic_3d.prototype.createElementArrayBuffer = function(vertices){
var buffer = this.context.createBuffer();
buffer.numElements = vertices.length;
this.context.bindBuffer(this.context.ELEMENT_ARRAY_BUFFER, buffer);
this.context.bufferData(this.context.ELEMENT_ARRAY_BUFFER, new Uint16Array(vertices), this.context.STATIC_DRAW);
return buffer;
};
Kinetic_3d.prototype.pushPositionBuffer = function(buffers){
this.context.bindBuffer(this.context.ARRAY_BUFFER, buffers.positionBuffer);
this.context.vertexAttribPointer(this.shaderProgram.vertexPositionAttribute, 3, this.context.FLOAT, false, 0, 0);
};
Kinetic_3d.prototype.pushColorBuffer = function(buffers){
this.context.bindBuffer(this.context.ARRAY_BUFFER, buffers.colorBuffer);
this.context.vertexAttribPointer(this.shaderProgram.vertexColorAttribute, 4, this.context.FLOAT, false, 0, 0);
};
Kinetic_3d.prototype.pushTextureBuffer = function(buffers, texture){
this.context.bindBuffer(this.context.ARRAY_BUFFER, buffers.textureBuffer);
this.context.vertexAttribPointer(this.shaderProgram.textureCoordAttribute, 2, this.context.FLOAT, false, 0, 0);
this.context.activeTexture(this.context.TEXTURE0);
this.context.bindTexture(this.context.TEXTURE_2D, texture);
this.context.uniform1i(this.shaderProgram.samplerUniform, 0);
};
Kinetic_3d.prototype.pushIndexBuffer = function(buffers){
this.context.bindBuffer(this.context.ELEMENT_ARRAY_BUFFER, buffers.indexBuffer);
};
Kinetic_3d.prototype.pushNormalBuffer = function(buffers){
this.context.bindBuffer(this.context.ARRAY_BUFFER, buffers.normalBuffer);
this.context.vertexAttribPointer(this.shaderProgram.vertexNormalAttribute, 3, this.context.FLOAT, false, 0, 0);
};
Kinetic_3d.prototype.setMatrixUniforms = function(){
this.context.uniformMatrix4fv(this.shaderProgram.pMatrixUniform, false, this.pMatrix);
this.context.uniformMatrix4fv(this.shaderProgram.mvMatrixUniform, false, this.mvMatrix);
var normalMatrix = this.mat3.create();
this.mat4.toInverseMat3(this.mvMatrix, normalMatrix);
this.mat3.transpose(normalMatrix);
this.context.uniformMatrix3fv(this.shaderProgram.nMatrixUniform, false, normalMatrix);
};
Kinetic_3d.prototype.drawElements = function(buffers){
this.setMatrixUniforms();
// draw elements
this.context.drawElements(this.context.TRIANGLES, buffers.indexBuffer.numElements, this.context.UNSIGNED_SHORT, 0);
};
Kinetic_3d.prototype.drawArrays = function(buffers){
this.setMatrixUniforms();
// draw arrays
this.context.drawArrays(this.context.TRIANGLES, 0, buffers.positionBuffer.numElements / 3);
};
Kinetic_3d.prototype.enableLighting = function(){
this.context.uniform1i(this.shaderProgram.useLightingUniform, true);
};
Kinetic_3d.prototype.setAmbientLighting = function(red, green, blue){
this.context.uniform3f(this.shaderProgram.ambientColorUniform, parseFloat(red), parseFloat(green), parseFloat(blue));
};
Kinetic_3d.prototype.setDirectionalLighting = function(x, y, z, red, green, blue){
// directional lighting
var lightingDirection = [x, y, z];
var adjustedLD = this.vec3.create();
this.vec3.normalize(lightingDirection, adjustedLD);
this.vec3.scale(adjustedLD, -1);
this.context.uniform3fv(this.shaderProgram.lightingDirectionUniform, adjustedLD);
// directional color
this.context.uniform3f(this.shaderProgram.directionalColorUniform, parseFloat(red), parseFloat(green), parseFloat(blue));
};
Kinetic_3d.prototype.initGlMatrix = function(){
// glMatrix v0.9.5
glMatrixArrayType=typeof Float32Array!="undefined"?Float32Array:typeof WebGLFloatArray!="undefined"?WebGLFloatArray:Array;var vec3={};vec3.create=function(a){var b=new glMatrixArrayType(3);if(a){b[0]=a[0];b[1]=a[1];b[2]=a[2]}return b};vec3.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];return b};vec3.add=function(a,b,c){if(!c||a==c){a[0]+=b[0];a[1]+=b[1];a[2]+=b[2];return a}c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];return c};
vec3.subtract=function(a,b,c){if(!c||a==c){a[0]-=b[0];a[1]-=b[1];a[2]-=b[2];return a}c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];return c};vec3.negate=function(a,b){b||(b=a);b[0]=-a[0];b[1]=-a[1];b[2]=-a[2];return b};vec3.scale=function(a,b,c){if(!c||a==c){a[0]*=b;a[1]*=b;a[2]*=b;return a}c[0]=a[0]*b;c[1]=a[1]*b;c[2]=a[2]*b;return c};
vec3.normalize=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=Math.sqrt(c*c+d*d+e*e);if(g){if(g==1){b[0]=c;b[1]=d;b[2]=e;return b}}else{b[0]=0;b[1]=0;b[2]=0;return b}g=1/g;b[0]=c*g;b[1]=d*g;b[2]=e*g;return b};vec3.cross=function(a,b,c){c||(c=a);var d=a[0],e=a[1];a=a[2];var g=b[0],f=b[1];b=b[2];c[0]=e*b-a*f;c[1]=a*g-d*b;c[2]=d*f-e*g;return c};vec3.length=function(a){var b=a[0],c=a[1];a=a[2];return Math.sqrt(b*b+c*c+a*a)};vec3.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};
vec3.direction=function(a,b,c){c||(c=a);var d=a[0]-b[0],e=a[1]-b[1];a=a[2]-b[2];b=Math.sqrt(d*d+e*e+a*a);if(!b){c[0]=0;c[1]=0;c[2]=0;return c}b=1/b;c[0]=d*b;c[1]=e*b;c[2]=a*b;return c};vec3.lerp=function(a,b,c,d){d||(d=a);d[0]=a[0]+c*(b[0]-a[0]);d[1]=a[1]+c*(b[1]-a[1]);d[2]=a[2]+c*(b[2]-a[2]);return d};vec3.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+"]"};var mat3={};
mat3.create=function(a){var b=new glMatrixArrayType(9);if(a){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9]}return b};mat3.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return b};mat3.identity=function(a){a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=1;a[5]=0;a[6]=0;a[7]=0;a[8]=1;return a};
mat3.transpose=function(a,b){if(!b||a==b){var c=a[1],d=a[2],e=a[5];a[1]=a[3];a[2]=a[6];a[3]=c;a[5]=a[7];a[6]=d;a[7]=e;return a}b[0]=a[0];b[1]=a[3];b[2]=a[6];b[3]=a[1];b[4]=a[4];b[5]=a[7];b[6]=a[2];b[7]=a[5];b[8]=a[8];return b};mat3.toMat4=function(a,b){b||(b=mat4.create());b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=0;b[4]=a[3];b[5]=a[4];b[6]=a[5];b[7]=0;b[8]=a[6];b[9]=a[7];b[10]=a[8];b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return b};
mat3.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+"]"};var mat4={};mat4.create=function(a){var b=new glMatrixArrayType(16);if(a){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15]}return b};
mat4.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return b};mat4.identity=function(a){a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=0;a[5]=1;a[6]=0;a[7]=0;a[8]=0;a[9]=0;a[10]=1;a[11]=0;a[12]=0;a[13]=0;a[14]=0;a[15]=1;return a};
mat4.transpose=function(a,b){if(!b||a==b){var c=a[1],d=a[2],e=a[3],g=a[6],f=a[7],h=a[11];a[1]=a[4];a[2]=a[8];a[3]=a[12];a[4]=c;a[6]=a[9];a[7]=a[13];a[8]=d;a[9]=g;a[11]=a[14];a[12]=e;a[13]=f;a[14]=h;return a}b[0]=a[0];b[1]=a[4];b[2]=a[8];b[3]=a[12];b[4]=a[1];b[5]=a[5];b[6]=a[9];b[7]=a[13];b[8]=a[2];b[9]=a[6];b[10]=a[10];b[11]=a[14];b[12]=a[3];b[13]=a[7];b[14]=a[11];b[15]=a[15];return b};
mat4.determinant=function(a){var b=a[0],c=a[1],d=a[2],e=a[3],g=a[4],f=a[5],h=a[6],i=a[7],j=a[8],k=a[9],l=a[10],o=a[11],m=a[12],n=a[13],p=a[14];a=a[15];return m*k*h*e-j*n*h*e-m*f*l*e+g*n*l*e+j*f*p*e-g*k*p*e-m*k*d*i+j*n*d*i+m*c*l*i-b*n*l*i-j*c*p*i+b*k*p*i+m*f*d*o-g*n*d*o-m*c*h*o+b*n*h*o+g*c*p*o-b*f*p*o-j*f*d*a+g*k*d*a+j*c*h*a-b*k*h*a-g*c*l*a+b*f*l*a};
mat4.inverse=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=a[3],f=a[4],h=a[5],i=a[6],j=a[7],k=a[8],l=a[9],o=a[10],m=a[11],n=a[12],p=a[13],r=a[14],s=a[15],A=c*h-d*f,B=c*i-e*f,t=c*j-g*f,u=d*i-e*h,v=d*j-g*h,w=e*j-g*i,x=k*p-l*n,y=k*r-o*n,z=k*s-m*n,C=l*r-o*p,D=l*s-m*p,E=o*s-m*r,q=1/(A*E-B*D+t*C+u*z-v*y+w*x);b[0]=(h*E-i*D+j*C)*q;b[1]=(-d*E+e*D-g*C)*q;b[2]=(p*w-r*v+s*u)*q;b[3]=(-l*w+o*v-m*u)*q;b[4]=(-f*E+i*z-j*y)*q;b[5]=(c*E-e*z+g*y)*q;b[6]=(-n*w+r*t-s*B)*q;b[7]=(k*w-o*t+m*B)*q;b[8]=(f*D-h*z+j*x)*q;
b[9]=(-c*D+d*z-g*x)*q;b[10]=(n*v-p*t+s*A)*q;b[11]=(-k*v+l*t-m*A)*q;b[12]=(-f*C+h*y-i*x)*q;b[13]=(c*C-d*y+e*x)*q;b[14]=(-n*u+p*B-r*A)*q;b[15]=(k*u-l*B+o*A)*q;return b};mat4.toRotationMat=function(a,b){b||(b=mat4.create());b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=0;b[13]=0;b[14]=0;b[15]=1;return b};
mat4.toMat3=function(a,b){b||(b=mat3.create());b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[4];b[4]=a[5];b[5]=a[6];b[6]=a[8];b[7]=a[9];b[8]=a[10];return b};mat4.toInverseMat3=function(a,b){var c=a[0],d=a[1],e=a[2],g=a[4],f=a[5],h=a[6],i=a[8],j=a[9],k=a[10],l=k*f-h*j,o=-k*g+h*i,m=j*g-f*i,n=c*l+d*o+e*m;if(!n)return null;n=1/n;b||(b=mat3.create());b[0]=l*n;b[1]=(-k*d+e*j)*n;b[2]=(h*d-e*f)*n;b[3]=o*n;b[4]=(k*c-e*i)*n;b[5]=(-h*c+e*g)*n;b[6]=m*n;b[7]=(-j*c+d*i)*n;b[8]=(f*c-d*g)*n;return b};
mat4.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],g=a[2],f=a[3],h=a[4],i=a[5],j=a[6],k=a[7],l=a[8],o=a[9],m=a[10],n=a[11],p=a[12],r=a[13],s=a[14];a=a[15];var A=b[0],B=b[1],t=b[2],u=b[3],v=b[4],w=b[5],x=b[6],y=b[7],z=b[8],C=b[9],D=b[10],E=b[11],q=b[12],F=b[13],G=b[14];b=b[15];c[0]=A*d+B*h+t*l+u*p;c[1]=A*e+B*i+t*o+u*r;c[2]=A*g+B*j+t*m+u*s;c[3]=A*f+B*k+t*n+u*a;c[4]=v*d+w*h+x*l+y*p;c[5]=v*e+w*i+x*o+y*r;c[6]=v*g+w*j+x*m+y*s;c[7]=v*f+w*k+x*n+y*a;c[8]=z*d+C*h+D*l+E*p;c[9]=z*e+C*i+D*o+E*r;c[10]=z*
g+C*j+D*m+E*s;c[11]=z*f+C*k+D*n+E*a;c[12]=q*d+F*h+G*l+b*p;c[13]=q*e+F*i+G*o+b*r;c[14]=q*g+F*j+G*m+b*s;c[15]=q*f+F*k+G*n+b*a;return c};mat4.multiplyVec3=function(a,b,c){c||(c=b);var d=b[0],e=b[1];b=b[2];c[0]=a[0]*d+a[4]*e+a[8]*b+a[12];c[1]=a[1]*d+a[5]*e+a[9]*b+a[13];c[2]=a[2]*d+a[6]*e+a[10]*b+a[14];return c};
mat4.multiplyVec4=function(a,b,c){c||(c=b);var d=b[0],e=b[1],g=b[2];b=b[3];c[0]=a[0]*d+a[4]*e+a[8]*g+a[12]*b;c[1]=a[1]*d+a[5]*e+a[9]*g+a[13]*b;c[2]=a[2]*d+a[6]*e+a[10]*g+a[14]*b;c[3]=a[3]*d+a[7]*e+a[11]*g+a[15]*b;return c};
mat4.translate=function(a,b,c){var d=b[0],e=b[1];b=b[2];if(!c||a==c){a[12]=a[0]*d+a[4]*e+a[8]*b+a[12];a[13]=a[1]*d+a[5]*e+a[9]*b+a[13];a[14]=a[2]*d+a[6]*e+a[10]*b+a[14];a[15]=a[3]*d+a[7]*e+a[11]*b+a[15];return a}var g=a[0],f=a[1],h=a[2],i=a[3],j=a[4],k=a[5],l=a[6],o=a[7],m=a[8],n=a[9],p=a[10],r=a[11];c[0]=g;c[1]=f;c[2]=h;c[3]=i;c[4]=j;c[5]=k;c[6]=l;c[7]=o;c[8]=m;c[9]=n;c[10]=p;c[11]=r;c[12]=g*d+j*e+m*b+a[12];c[13]=f*d+k*e+n*b+a[13];c[14]=h*d+l*e+p*b+a[14];c[15]=i*d+o*e+r*b+a[15];return c};
mat4.scale=function(a,b,c){var d=b[0],e=b[1];b=b[2];if(!c||a==c){a[0]*=d;a[1]*=d;a[2]*=d;a[3]*=d;a[4]*=e;a[5]*=e;a[6]*=e;a[7]*=e;a[8]*=b;a[9]*=b;a[10]*=b;a[11]*=b;return a}c[0]=a[0]*d;c[1]=a[1]*d;c[2]=a[2]*d;c[3]=a[3]*d;c[4]=a[4]*e;c[5]=a[5]*e;c[6]=a[6]*e;c[7]=a[7]*e;c[8]=a[8]*b;c[9]=a[9]*b;c[10]=a[10]*b;c[11]=a[11]*b;c[12]=a[12];c[13]=a[13];c[14]=a[14];c[15]=a[15];return c};
mat4.rotate=function(a,b,c,d){var e=c[0],g=c[1];c=c[2];var f=Math.sqrt(e*e+g*g+c*c);if(!f)return null;if(f!=1){f=1/f;e*=f;g*=f;c*=f}var h=Math.sin(b),i=Math.cos(b),j=1-i;b=a[0];f=a[1];var k=a[2],l=a[3],o=a[4],m=a[5],n=a[6],p=a[7],r=a[8],s=a[9],A=a[10],B=a[11],t=e*e*j+i,u=g*e*j+c*h,v=c*e*j-g*h,w=e*g*j-c*h,x=g*g*j+i,y=c*g*j+e*h,z=e*c*j+g*h;e=g*c*j-e*h;g=c*c*j+i;if(d){if(a!=d){d[12]=a[12];d[13]=a[13];d[14]=a[14];d[15]=a[15]}}else d=a;d[0]=b*t+o*u+r*v;d[1]=f*t+m*u+s*v;d[2]=k*t+n*u+A*v;d[3]=l*t+p*u+B*
v;d[4]=b*w+o*x+r*y;d[5]=f*w+m*x+s*y;d[6]=k*w+n*x+A*y;d[7]=l*w+p*x+B*y;d[8]=b*z+o*e+r*g;d[9]=f*z+m*e+s*g;d[10]=k*z+n*e+A*g;d[11]=l*z+p*e+B*g;return d};mat4.rotateX=function(a,b,c){var d=Math.sin(b);b=Math.cos(b);var e=a[4],g=a[5],f=a[6],h=a[7],i=a[8],j=a[9],k=a[10],l=a[11];if(c){if(a!=c){c[0]=a[0];c[1]=a[1];c[2]=a[2];c[3]=a[3];c[12]=a[12];c[13]=a[13];c[14]=a[14];c[15]=a[15]}}else c=a;c[4]=e*b+i*d;c[5]=g*b+j*d;c[6]=f*b+k*d;c[7]=h*b+l*d;c[8]=e*-d+i*b;c[9]=g*-d+j*b;c[10]=f*-d+k*b;c[11]=h*-d+l*b;return c};
mat4.rotateY=function(a,b,c){var d=Math.sin(b);b=Math.cos(b);var e=a[0],g=a[1],f=a[2],h=a[3],i=a[8],j=a[9],k=a[10],l=a[11];if(c){if(a!=c){c[4]=a[4];c[5]=a[5];c[6]=a[6];c[7]=a[7];c[12]=a[12];c[13]=a[13];c[14]=a[14];c[15]=a[15]}}else c=a;c[0]=e*b+i*-d;c[1]=g*b+j*-d;c[2]=f*b+k*-d;c[3]=h*b+l*-d;c[8]=e*d+i*b;c[9]=g*d+j*b;c[10]=f*d+k*b;c[11]=h*d+l*b;return c};
mat4.rotateZ=function(a,b,c){var d=Math.sin(b);b=Math.cos(b);var e=a[0],g=a[1],f=a[2],h=a[3],i=a[4],j=a[5],k=a[6],l=a[7];if(c){if(a!=c){c[8]=a[8];c[9]=a[9];c[10]=a[10];c[11]=a[11];c[12]=a[12];c[13]=a[13];c[14]=a[14];c[15]=a[15]}}else c=a;c[0]=e*b+i*d;c[1]=g*b+j*d;c[2]=f*b+k*d;c[3]=h*b+l*d;c[4]=e*-d+i*b;c[5]=g*-d+j*b;c[6]=f*-d+k*b;c[7]=h*-d+l*b;return c};
mat4.frustum=function(a,b,c,d,e,g,f){f||(f=mat4.create());var h=b-a,i=d-c,j=g-e;f[0]=e*2/h;f[1]=0;f[2]=0;f[3]=0;f[4]=0;f[5]=e*2/i;f[6]=0;f[7]=0;f[8]=(b+a)/h;f[9]=(d+c)/i;f[10]=-(g+e)/j;f[11]=-1;f[12]=0;f[13]=0;f[14]=-(g*e*2)/j;f[15]=0;return f};mat4.perspective=function(a,b,c,d,e){a=c*Math.tan(a*Math.PI/360);b=a*b;return mat4.frustum(-b,b,-a,a,c,d,e)};
mat4.ortho=function(a,b,c,d,e,g,f){f||(f=mat4.create());var h=b-a,i=d-c,j=g-e;f[0]=2/h;f[1]=0;f[2]=0;f[3]=0;f[4]=0;f[5]=2/i;f[6]=0;f[7]=0;f[8]=0;f[9]=0;f[10]=-2/j;f[11]=0;f[12]=-(a+b)/h;f[13]=-(d+c)/i;f[14]=-(g+e)/j;f[15]=1;return f};
mat4.lookAt=function(a,b,c,d){d||(d=mat4.create());var e=a[0],g=a[1];a=a[2];var f=c[0],h=c[1],i=c[2];c=b[1];var j=b[2];if(e==b[0]&&g==c&&a==j)return mat4.identity(d);var k,l,o,m;c=e-b[0];j=g-b[1];b=a-b[2];m=1/Math.sqrt(c*c+j*j+b*b);c*=m;j*=m;b*=m;k=h*b-i*j;i=i*c-f*b;f=f*j-h*c;if(m=Math.sqrt(k*k+i*i+f*f)){m=1/m;k*=m;i*=m;f*=m}else f=i=k=0;h=j*f-b*i;l=b*k-c*f;o=c*i-j*k;if(m=Math.sqrt(h*h+l*l+o*o)){m=1/m;h*=m;l*=m;o*=m}else o=l=h=0;d[0]=k;d[1]=h;d[2]=c;d[3]=0;d[4]=i;d[5]=l;d[6]=j;d[7]=0;d[8]=f;d[9]=
o;d[10]=b;d[11]=0;d[12]=-(k*e+i*g+f*a);d[13]=-(h*e+l*g+o*a);d[14]=-(c*e+j*g+b*a);d[15]=1;return d};mat4.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+"]"};quat4={};quat4.create=function(a){var b=new glMatrixArrayType(4);if(a){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3]}return b};quat4.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];return b};
quat4.calculateW=function(a,b){var c=a[0],d=a[1],e=a[2];if(!b||a==b){a[3]=-Math.sqrt(Math.abs(1-c*c-d*d-e*e));return a}b[0]=c;b[1]=d;b[2]=e;b[3]=-Math.sqrt(Math.abs(1-c*c-d*d-e*e));return b};quat4.inverse=function(a,b){if(!b||a==b){a[0]*=1;a[1]*=1;a[2]*=1;return a}b[0]=-a[0];b[1]=-a[1];b[2]=-a[2];b[3]=a[3];return b};quat4.length=function(a){var b=a[0],c=a[1],d=a[2];a=a[3];return Math.sqrt(b*b+c*c+d*d+a*a)};
quat4.normalize=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=a[3],f=Math.sqrt(c*c+d*d+e*e+g*g);if(f==0){b[0]=0;b[1]=0;b[2]=0;b[3]=0;return b}f=1/f;b[0]=c*f;b[1]=d*f;b[2]=e*f;b[3]=g*f;return b};quat4.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],g=a[2];a=a[3];var f=b[0],h=b[1],i=b[2];b=b[3];c[0]=d*b+a*f+e*i-g*h;c[1]=e*b+a*h+g*f-d*i;c[2]=g*b+a*i+d*h-e*f;c[3]=a*b-d*f-e*h-g*i;return c};
quat4.multiplyVec3=function(a,b,c){c||(c=b);var d=b[0],e=b[1],g=b[2];b=a[0];var f=a[1],h=a[2];a=a[3];var i=a*d+f*g-h*e,j=a*e+h*d-b*g,k=a*g+b*e-f*d;d=-b*d-f*e-h*g;c[0]=i*a+d*-b+j*-h-k*-f;c[1]=j*a+d*-f+k*-b-i*-h;c[2]=k*a+d*-h+i*-f-j*-b;return c};quat4.toMat3=function(a,b){b||(b=mat3.create());var c=a[0],d=a[1],e=a[2],g=a[3],f=c+c,h=d+d,i=e+e,j=c*f,k=c*h;c=c*i;var l=d*h;d=d*i;e=e*i;f=g*f;h=g*h;g=g*i;b[0]=1-(l+e);b[1]=k-g;b[2]=c+h;b[3]=k+g;b[4]=1-(j+e);b[5]=d-f;b[6]=c-h;b[7]=d+f;b[8]=1-(j+l);return b};
quat4.toMat4=function(a,b){b||(b=mat4.create());var c=a[0],d=a[1],e=a[2],g=a[3],f=c+c,h=d+d,i=e+e,j=c*f,k=c*h;c=c*i;var l=d*h;d=d*i;e=e*i;f=g*f;h=g*h;g=g*i;b[0]=1-(l+e);b[1]=k-g;b[2]=c+h;b[3]=0;b[4]=k+g;b[5]=1-(j+e);b[6]=d-f;b[7]=0;b[8]=c-h;b[9]=d+f;b[10]=1-(j+l);b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return b};quat4.slerp=function(a,b,c,d){d||(d=a);var e=c;if(a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]<0)e=-1*c;d[0]=1-c*a[0]+e*b[0];d[1]=1-c*a[1]+e*b[1];d[2]=1-c*a[2]+e*b[2];d[3]=1-c*a[3]+e*b[3];return d};
quat4.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+"]"};
// encapsulte mat3, mat4, and vec3
this.mat3 = mat3;
this.mat4 = mat4;
this.vec3 = vec3;
};
|
import {ModifyCollectionObserver} from './collection-observation';
let setProto = Set.prototype;
export function getSetObserver(taskQueue, set) {
return ModifySetObserver.for(taskQueue, set);
}
class ModifySetObserver extends ModifyCollectionObserver {
constructor(taskQueue, set) {
super(taskQueue, set);
}
/**
* Searches for observer or creates a new one associated with given set instance
* @param taskQueue
* @param set instance for which observer is searched
* @returns ModifySetObserver always the same instance for any given set instance
*/
static for(taskQueue, set) {
if (!('__set_observer__' in set)) {
let observer = ModifySetObserver.create(taskQueue, set);
Reflect.defineProperty(
set,
'__set_observer__',
{ value: observer, enumerable: false, configurable: false });
}
return set.__set_observer__;
}
static create(taskQueue, set) {
let observer = new ModifySetObserver(taskQueue, set);
let proto = setProto;
if (proto.add !== set.add || proto.delete !== set.delete || proto.clear !== set.clear) {
proto = {
add: set.add,
delete: set.delete,
clear: set.clear
};
}
set.add = function() {
let type = 'add';
let oldSize = set.size;
let methodCallResult = proto.add.apply(set, arguments);
let hasValue = set.size === oldSize;
if (!hasValue) {
observer.addChangeRecord({
type: type,
object: set,
value: Array.from(set).pop()
});
}
return methodCallResult;
};
set.delete = function() {
let hasValue = set.has(arguments[0]);
let methodCallResult = proto.delete.apply(set, arguments);
if (hasValue) {
observer.addChangeRecord({
type: 'delete',
object: set,
value: arguments[0]
});
}
return methodCallResult;
};
set.clear = function() {
let methodCallResult = proto.clear.apply(set, arguments);
observer.addChangeRecord({
type: 'clear',
object: set
});
return methodCallResult;
};
return observer;
}
}
|
dc.ui.FeaturedReport = Backbone.View.extend({
attributes: {
'class': 'report'
},
events: {
'click .ok' : 'save',
'click .edit_glyph' : 'edit',
'click .cancel' : 'cancel',
'click .delete' : 'deleteReport'
},
initialize: function(options) {
_.bindAll(this,'_onError','_onSuccess');
},
renderTmpl: function( editing ){
var tmpl = ( editing ? JST['featured_report_edit'] : JST['featured_report_display'] ),
json = this.model.toJSON();
this.$el.html( tmpl( json ) ).attr('data-id', this.model.id );
},
render: function(){
this.renderTmpl( this.model.isNew() );
return this;
},
cancel: function(){
if ( this.model.isNew() ){ // hmm how to kill ourselves?
// get our parent to do it for us
this.model.collection.remove( this.model );
} else {
this.render();
}
},
deleteReport: function(){
this.model.destroy({
success: function(model,resp){
model.collection.remove( model );
}
});
},
edit: function(){
this.renderTmpl( true );
},
_onSuccess : function(model, resp) {
this.render();
dc.ui.spinner.hide();
},
_onError : function(model, resp) {
resp = JSON.parse(resp.responseText);
if ( resp.errors ){
this.$('.errors').html( "The following errors were encountered:<ul>" +
_.reduce( resp.errors, function(memo,err){ return memo + '<li>'+err+'</li>'; }, '' ) +
'</ul>' );
}
dc.ui.spinner.hide();
},
save: function(){
dc.ui.spinner.show( 'Saving' );
this.model.save( this.$('form.edit').serializeJSON(), {
error: this._onError,
success: this._onSuccess
});
}
});
dc.ui.FeaturedReporting = Backbone.View.extend({
attributes: {
'class': 'featured_reports'
},
events: {
'click .reload' : 'reload',
'click .add' : 'addReport'
},
initialize: function(options) {
_.bindAll(this,'appendReport','prependReport','render','saveSortOrder');
this.collection.bind( 'reset', this.render );
this.collection.bind( 'add', this.prependReport );
this.collection.bind( 'remove', this.render );
},
saveSortOrder: function(){
var ids = _.map( this.$('.listing .report[data-id]'), function( el ){
return el.getAttribute('data-id');
});
$.ajax( this.collection.url + '/present_order', {
method: 'POST',
data: { order: ids }
} );
},
addReport: function(){
this.collection.add({ });
},
prependReport: function( model ){
var report = new dc.ui.FeaturedReport( { model: model });
this.$('.listing').prepend( report.render().el );
},
appendReport: function( model ){
var report = new dc.ui.FeaturedReport( { model: model });
this.$('.listing').append( report.render().el );
},
render: function() {
this.$el.html(JST['featured_reporting']({}));
this.collection.each( this.appendReport );
this.$('.listing').sortable({
placeholder: "drop-placeholder",
forcePlaceholderSize: true,
stop: this.saveSortOrder
});
return this;
},
reload: function() {
this.collection.fetch();
},
});
|
/*!
* Knockout JavaScript library v3.3.0
* (c) Steven Sanderson - http://knockoutjs.com/
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
(function () {
var DEBUG = true;
(function (undefined) {
// (0, eval)('this') is a robust way of getting a reference to the global object
// For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
var window = this || (0, eval)('this'),
document = window['document'],
navigator = window['navigator'],
jQueryInstance = window["jQuery"],
JSON = window["JSON"];
(function (factory) {
// Support three module loading scenarios
if (typeof define === 'function' && define['amd']) {
// [1] AMD anonymous module
define(['exports', 'require'], factory);
} else if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
// [2] CommonJS/Node.js
factory(module['exports'] || exports); // module.exports is for Node.js
} else {
// [3] No module loader (plain <script> tag) - put directly in global namespace
factory(window['ko'] = {});
}
}(function (koExports, amdRequire) {
// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
var ko = typeof koExports !== 'undefined' ? koExports : {};
// Google Closure Compiler helpers (used only to make the minified file smaller)
ko.exportSymbol = function (koPath, object) {
var tokens = koPath.split(".");
// In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
// At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
var target = ko;
for (var i = 0; i < tokens.length - 1; i++)
target = target[tokens[i]];
target[tokens[tokens.length - 1]] = object;
};
ko.exportProperty = function (owner, publicName, object) {
owner[publicName] = object;
};
ko.version = "3.3.0";
ko.exportSymbol('version', ko.version);
ko.utils = (function () {
function objectForEach(obj, action) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
action(prop, obj[prop]);
}
}
}
function extend(target, source) {
if (source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
}
return target;
}
function setPrototypeOf(obj, proto) {
obj.__proto__ = proto;
return obj;
}
var canSetPrototype = ({ __proto__: [] } instanceof Array);
// Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
var knownEvents = {}, knownEventTypesByEventName = {};
var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
objectForEach(knownEvents, function (eventType, knownEventsForType) {
if (knownEventsForType.length) {
for (var i = 0, j = knownEventsForType.length; i < j; i++)
knownEventTypesByEventName[knownEventsForType[i]] = eventType;
}
});
var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
// Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
// Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
// Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
// If there is a future need to detect specific versions of IE10+, we will amend this.
var ieVersion = document && (function () {
var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
// Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
while (
div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
iElems[0]
) { }
return version > 4 ? version : undefined;
}());
var isIe6 = ieVersion === 6,
isIe7 = ieVersion === 7;
function isClickOnCheckableElement(element, eventType) {
if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
if (eventType.toLowerCase() != "click") return false;
var inputType = element.type;
return (inputType == "checkbox") || (inputType == "radio");
}
// For details on the pattern for changing node classes
// see: https://github.com/knockout/knockout/issues/1597
var cssClassNameRegex = /\S+/g;
function toggleDomNodeCssClass(node, classNames, shouldHaveClass) {
var addOrRemoveFn;
if (classNames) {
if (typeof node.classList === 'object') {
addOrRemoveFn = node.classList[shouldHaveClass ? 'add' : 'remove'];
ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function (className) {
addOrRemoveFn.call(node.classList, className);
});
} else if (typeof node.className['baseVal'] === 'string') {
// SVG tag .classNames is an SVGAnimatedString instance
toggleObjectClassPropertyString(node.className, 'baseVal', classNames, shouldHaveClass);
} else {
// node.className ought to be a string.
toggleObjectClassPropertyString(node, 'className', classNames, shouldHaveClass);
}
}
}
function toggleObjectClassPropertyString(obj, prop, classNames, shouldHaveClass) {
// obj/prop is either a node/'className' or a SVGAnimatedString/'baseVal'.
var currentClassNames = obj[prop].match(cssClassNameRegex) || [];
ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function (className) {
ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
});
obj[prop] = currentClassNames.join(" ");
}
return {
fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
arrayForEach: function (array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i], i);
},
arrayIndexOf: function (array, item) {
if (typeof Array.prototype.indexOf == "function")
return Array.prototype.indexOf.call(array, item);
for (var i = 0, j = array.length; i < j; i++)
if (array[i] === item)
return i;
return -1;
},
arrayFirst: function (array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++)
if (predicate.call(predicateOwner, array[i], i))
return array[i];
return null;
},
arrayRemoveItem: function (array, itemToRemove) {
var index = ko.utils.arrayIndexOf(array, itemToRemove);
if (index > 0) {
array.splice(index, 1);
}
else if (index === 0) {
array.shift();
}
},
arrayGetDistinctValues: function (array) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++) {
if (ko.utils.arrayIndexOf(result, array[i]) < 0)
result.push(array[i]);
}
return result;
},
arrayMap: function (array, mapping) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
result.push(mapping(array[i], i));
return result;
},
arrayFilter: function (array, predicate) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
if (predicate(array[i], i))
result.push(array[i]);
return result;
},
arrayPushAll: function (array, valuesToPush) {
if (valuesToPush instanceof Array)
array.push.apply(array, valuesToPush);
else
for (var i = 0, j = valuesToPush.length; i < j; i++)
array.push(valuesToPush[i]);
return array;
},
addOrRemoveItem: function (array, value, included) {
var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
if (existingEntryIndex < 0) {
if (included)
array.push(value);
} else {
if (!included)
array.splice(existingEntryIndex, 1);
}
},
canSetPrototype: canSetPrototype,
extend: extend,
setPrototypeOf: setPrototypeOf,
setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
objectForEach: objectForEach,
objectMap: function (source, mapping) {
if (!source)
return source;
var target = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = mapping(source[prop], prop, source);
}
}
return target;
},
emptyDomNode: function (domNode) {
while (domNode.firstChild) {
ko.removeNode(domNode.firstChild);
}
},
moveCleanedNodesToContainerElement: function (nodes) {
// Ensure it's a real array, as we're about to reparent the nodes and
// we don't want the underlying collection to change while we're doing that.
var nodesArray = ko.utils.makeArray(nodes);
var templateDocument = (nodesArray[0] && nodesArray[0].ownerDocument) || document;
var container = templateDocument.createElement('div');
for (var i = 0, j = nodesArray.length; i < j; i++) {
container.appendChild(ko.cleanNode(nodesArray[i]));
}
return container;
},
cloneNodes: function (nodesArray, shouldCleanNodes) {
for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
var clonedNode = nodesArray[i].cloneNode(true);
newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
}
return newNodesArray;
},
setDomNodeChildren: function (domNode, childNodes) {
ko.utils.emptyDomNode(domNode);
if (childNodes) {
for (var i = 0, j = childNodes.length; i < j; i++)
domNode.appendChild(childNodes[i]);
}
},
replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
if (nodesToReplaceArray.length > 0) {
var insertionPoint = nodesToReplaceArray[0];
var parent = insertionPoint.parentNode;
for (var i = 0, j = newNodesArray.length; i < j; i++)
parent.insertBefore(newNodesArray[i], insertionPoint);
for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
ko.removeNode(nodesToReplaceArray[i]);
}
}
},
fixUpContinuousNodeArray: function (continuousNodeArray, parentNode) {
// Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
// them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
// new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
// leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
// So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
//
// Rules:
// [A] Any leading nodes that have been removed should be ignored
// These most likely correspond to memoization nodes that were already removed during binding
// See https://github.com/SteveSanderson/knockout/pull/440
// [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
// and include any nodes that have been inserted among the previous collection
if (continuousNodeArray.length) {
// The parent node can be a virtual element; so get the real parent node
parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
// Rule [A]
while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
continuousNodeArray.splice(0, 1);
// Rule [B]
if (continuousNodeArray.length > 1) {
var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
// Replace with the actual new continuous node set
continuousNodeArray.length = 0;
while (current !== last) {
continuousNodeArray.push(current);
current = current.nextSibling;
if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
return;
}
continuousNodeArray.push(last);
}
}
return continuousNodeArray;
},
setOptionNodeSelectionState: function (optionNode, isSelected) {
// IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
if (ieVersion < 7)
optionNode.setAttribute("selected", isSelected);
else
optionNode.selected = isSelected;
},
stringTrim: function (string) {
return string === null || string === undefined ? '' :
string.trim ?
string.trim() :
string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
},
stringStartsWith: function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
},
domNodeIsContainedBy: function (node, containedByNode) {
if (node === containedByNode)
return true;
if (node.nodeType === 11)
return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
if (containedByNode.contains)
return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
if (containedByNode.compareDocumentPosition)
return (containedByNode.compareDocumentPosition(node) & 16) == 16;
while (node && node != containedByNode) {
node = node.parentNode;
}
return !!node;
},
domNodeIsAttachedToDocument: function (node) {
return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
},
anyDomNodeIsAttachedToDocument: function (nodes) {
return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
},
tagNameLower: function (element) {
// For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
// Possible future optimization: If we know it's an element from an XHTML document (not HTML),
// we don't need to do the .toLowerCase() as it will always be lower case anyway.
return element && element.tagName && element.tagName.toLowerCase();
},
registerEventHandler: function (element, eventType, handler) {
var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
if (!mustUseAttachEvent && jQueryInstance) {
jQueryInstance(element)['bind'](eventType, handler);
} else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
element.addEventListener(eventType, handler, false);
else if (typeof element.attachEvent != "undefined") {
var attachEventHandler = function (event) { handler.call(element, event); },
attachEventName = "on" + eventType;
element.attachEvent(attachEventName, attachEventHandler);
// IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
// so to avoid leaks, we have to remove them manually. See bug #856
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
element.detachEvent(attachEventName, attachEventHandler);
});
} else
throw new Error("Browser doesn't support addEventListener or attachEvent");
},
triggerEvent: function (element, eventType) {
if (!(element && element.nodeType))
throw new Error("element must be a DOM node when calling triggerEvent");
// For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
// event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
// IE doesn't change the checked state when you trigger the click event using "fireEvent".
// In both cases, we'll use the click method instead.
var useClickWorkaround = isClickOnCheckableElement(element, eventType);
if (jQueryInstance && !useClickWorkaround) {
jQueryInstance(element)['trigger'](eventType);
} else if (typeof document.createEvent == "function") {
if (typeof element.dispatchEvent == "function") {
var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
var event = document.createEvent(eventCategory);
event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
element.dispatchEvent(event);
}
else
throw new Error("The supplied element doesn't support dispatchEvent");
} else if (useClickWorkaround && element.click) {
element.click();
} else if (typeof element.fireEvent != "undefined") {
element.fireEvent("on" + eventType);
} else {
throw new Error("Browser doesn't support triggering events");
}
},
unwrapObservable: function (value) {
return ko.isObservable(value) ? value() : value;
},
peekObservable: function (value) {
return ko.isObservable(value) ? value.peek() : value;
},
toggleDomNodeCssClass: toggleDomNodeCssClass,
setTextContent: function (element, textContent) {
var value = ko.utils.unwrapObservable(textContent);
if ((value === null) || (value === undefined))
value = "";
// We need there to be exactly one child: a text node.
// If there are no children, more than one, or if it's not a text node,
// we'll clear everything and create a single text node.
var innerTextNode = ko.virtualElements.firstChild(element);
if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
} else {
innerTextNode.data = value;
}
ko.utils.forceRefresh(element);
},
setElementName: function (element, name) {
element.name = name;
// Workaround IE 6/7 issue
// - https://github.com/SteveSanderson/knockout/issues/197
// - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
if (ieVersion <= 7) {
try {
element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
}
catch (e) { } // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
}
},
forceRefresh: function (node) {
// Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
if (ieVersion >= 9) {
// For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
var elem = node.nodeType == 1 ? node : node.parentNode;
if (elem.style)
elem.style.zoom = elem.style.zoom;
}
},
ensureSelectElementIsRenderedCorrectly: function (selectElement) {
// Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
// (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
// Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
if (ieVersion) {
var originalWidth = selectElement.style.width;
selectElement.style.width = 0;
selectElement.style.width = originalWidth;
}
},
range: function (min, max) {
min = ko.utils.unwrapObservable(min);
max = ko.utils.unwrapObservable(max);
var result = [];
for (var i = min; i <= max; i++)
result.push(i);
return result;
},
makeArray: function (arrayLikeObject) {
var result = [];
for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
result.push(arrayLikeObject[i]);
};
return result;
},
isIe6: isIe6,
isIe7: isIe7,
ieVersion: ieVersion,
getFormFields: function (form, fieldName) {
var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
var isMatchingField = (typeof fieldName == 'string')
? function (field) { return field.name === fieldName }
: function (field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
var matches = [];
for (var i = fields.length - 1; i >= 0; i--) {
if (isMatchingField(fields[i]))
matches.push(fields[i]);
};
return matches;
},
parseJson: function (jsonString) {
if (typeof jsonString == "string") {
jsonString = ko.utils.stringTrim(jsonString);
if (jsonString) {
if (JSON && JSON.parse) // Use native parsing where available
return JSON.parse(jsonString);
return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
}
}
return null;
},
stringifyJson: function (data, replacer, space) { // replacer and space are optional
if (!JSON || !JSON.stringify)
throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
},
postJson: function (urlOrForm, data, options) {
options = options || {};
var params = options['params'] || {};
var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
var url = urlOrForm;
// If we were given a form, use its 'action' URL and pick out any requested field values
if ((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
var originalForm = urlOrForm;
url = originalForm.action;
for (var i = includeFields.length - 1; i >= 0; i--) {
var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
for (var j = fields.length - 1; j >= 0; j--)
params[fields[j].name] = fields[j].value;
}
}
data = ko.utils.unwrapObservable(data);
var form = document.createElement("form");
form.style.display = "none";
form.action = url;
form.method = "post";
for (var key in data) {
// Since 'data' this is a model object, we include all properties including those inherited from its prototype
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
form.appendChild(input);
}
objectForEach(params, function (key, value) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = value;
form.appendChild(input);
});
document.body.appendChild(form);
options['submitter'] ? options['submitter'](form) : form.submit();
setTimeout(function () { form.parentNode.removeChild(form); }, 0);
}
}
}());
ko.exportSymbol('utils', ko.utils);
ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
ko.exportSymbol('utils.extend', ko.utils.extend);
ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
ko.exportSymbol('utils.postJson', ko.utils.postJson);
ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
ko.exportSymbol('utils.range', ko.utils.range);
ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
ko.exportSymbol('utils.setTextContent', ko.utils.setTextContent);
ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
if (!Function.prototype['bind']) {
// Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
// In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
Function.prototype['bind'] = function (object) {
var originalFunction = this;
if (arguments.length === 1) {
return function () {
return originalFunction.apply(object, arguments);
};
} else {
var partialArgs = Array.prototype.slice.call(arguments, 1);
return function () {
var args = partialArgs.slice(0);
args.push.apply(args, arguments);
return originalFunction.apply(object, args);
};
}
};
}
ko.utils.domData = new (function () {
var uniqueId = 0;
var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
var dataStore = {};
function getAll(node, createIfNotFound) {
var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
if (!hasExistingDataStore) {
if (!createIfNotFound)
return undefined;
dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
dataStore[dataStoreKey] = {};
}
return dataStore[dataStoreKey];
}
return {
get: function (node, key) {
var allDataForNode = getAll(node, false);
return allDataForNode === undefined ? undefined : allDataForNode[key];
},
set: function (node, key, value) {
if (value === undefined) {
// Make sure we don't actually create a new domData key if we are actually deleting a value
if (getAll(node, false) === undefined)
return;
}
var allDataForNode = getAll(node, true);
allDataForNode[key] = value;
},
clear: function (node) {
var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
if (dataStoreKey) {
delete dataStore[dataStoreKey];
node[dataStoreKeyExpandoPropertyName] = null;
return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
}
return false;
},
nextKey: function () {
return (uniqueId++) + dataStoreKeyExpandoPropertyName;
}
};
})();
ko.exportSymbol('utils.domData', ko.utils.domData);
ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
ko.utils.domNodeDisposal = new (function () {
var domDataKey = ko.utils.domData.nextKey();
var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
function getDisposeCallbacksCollection(node, createIfNotFound) {
var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
if ((allDisposeCallbacks === undefined) && createIfNotFound) {
allDisposeCallbacks = [];
ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
}
return allDisposeCallbacks;
}
function destroyCallbacksCollection(node) {
ko.utils.domData.set(node, domDataKey, undefined);
}
function cleanSingleNode(node) {
// Run all the dispose callbacks
var callbacks = getDisposeCallbacksCollection(node, false);
if (callbacks) {
callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
for (var i = 0; i < callbacks.length; i++)
callbacks[i](node);
}
// Erase the DOM data
ko.utils.domData.clear(node);
// Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
ko.utils.domNodeDisposal["cleanExternalData"](node);
// Clear any immediate-child comment nodes, as these wouldn't have been found by
// node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
if (cleanableNodeTypesWithDescendants[node.nodeType])
cleanImmediateCommentTypeChildren(node);
}
function cleanImmediateCommentTypeChildren(nodeWithChildren) {
var child, nextChild = nodeWithChildren.firstChild;
while (child = nextChild) {
nextChild = child.nextSibling;
if (child.nodeType === 8)
cleanSingleNode(child);
}
}
return {
addDisposeCallback: function (node, callback) {
if (typeof callback != "function")
throw new Error("Callback must be a function");
getDisposeCallbacksCollection(node, true).push(callback);
},
removeDisposeCallback: function (node, callback) {
var callbacksCollection = getDisposeCallbacksCollection(node, false);
if (callbacksCollection) {
ko.utils.arrayRemoveItem(callbacksCollection, callback);
if (callbacksCollection.length == 0)
destroyCallbacksCollection(node);
}
},
cleanNode: function (node) {
// First clean this node, where applicable
if (cleanableNodeTypes[node.nodeType]) {
cleanSingleNode(node);
// ... then its descendants, where applicable
if (cleanableNodeTypesWithDescendants[node.nodeType]) {
// Clone the descendants list in case it changes during iteration
var descendants = [];
ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
for (var i = 0, j = descendants.length; i < j; i++)
cleanSingleNode(descendants[i]);
}
}
return node;
},
removeNode: function (node) {
ko.cleanNode(node);
if (node.parentNode)
node.parentNode.removeChild(node);
},
"cleanExternalData": function (node) {
// Special support for jQuery here because it's so commonly used.
// Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
// so notify it to tear down any resources associated with the node & descendants here.
if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function"))
jQueryInstance['cleanData']([node]);
}
};
})();
ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
ko.exportSymbol('cleanNode', ko.cleanNode);
ko.exportSymbol('removeNode', ko.removeNode);
ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
(function () {
var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
function simpleHtmlParse(html, documentContext) {
documentContext || (documentContext = document);
var windowContext = documentContext['parentWindow'] || documentContext['defaultView'] || window;
// Based on jQuery's "clean" function, but only accounting for table-related elements.
// If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
// Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
// a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
// This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
// (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
// Trim whitespace, otherwise indexOf won't work as expected
var tags = ko.utils.stringTrim(html).toLowerCase(), div = documentContext.createElement("div");
// Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
!tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
(!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
/* anything else */[0, "", ""];
// Go to html and back, then peel off extra wrappers
// Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
if (typeof windowContext['innerShiv'] == "function") {
div.appendChild(windowContext['innerShiv'](markup));
} else {
div.innerHTML = markup;
}
// Move to the right depth
while (wrap[0]--)
div = div.lastChild;
return ko.utils.makeArray(div.lastChild.childNodes);
}
function jQueryHtmlParse(html, documentContext) {
// jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
if (jQueryInstance['parseHTML']) {
return jQueryInstance['parseHTML'](html, documentContext) || []; // Ensure we always return an array and never null
} else {
// For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
var elems = jQueryInstance['clean']([html], documentContext);
// As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
// Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
// Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
if (elems && elems[0]) {
// Find the top-most parent element that's a direct child of a document fragment
var elem = elems[0];
while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
elem = elem.parentNode;
// ... then detach it
if (elem.parentNode)
elem.parentNode.removeChild(elem);
}
return elems;
}
}
ko.utils.parseHtmlFragment = function (html, documentContext) {
return jQueryInstance ? jQueryHtmlParse(html, documentContext) // As below, benefit from jQuery's optimisations where possible
: simpleHtmlParse(html, documentContext); // ... otherwise, this simple logic will do in most common cases.
};
ko.utils.setHtml = function (node, html) {
ko.utils.emptyDomNode(node);
// There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
html = ko.utils.unwrapObservable(html);
if ((html !== null) && (html !== undefined)) {
if (typeof html != 'string')
html = html.toString();
// jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
// for example <tr> elements which are not normally allowed to exist on their own.
// If you've referenced jQuery we'll use that rather than duplicating its code.
if (jQueryInstance) {
jQueryInstance(node)['html'](html);
} else {
// ... otherwise, use KO's own parsing logic.
var parsedNodes = ko.utils.parseHtmlFragment(html, node.ownerDocument);
for (var i = 0; i < parsedNodes.length; i++)
node.appendChild(parsedNodes[i]);
}
}
};
})();
ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
ko.memoization = (function () {
var memos = {};
function randomMax8HexChars() {
return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
}
function generateRandomId() {
return randomMax8HexChars() + randomMax8HexChars();
}
function findMemoNodes(rootNode, appendToArray) {
if (!rootNode)
return;
if (rootNode.nodeType == 8) {
var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
if (memoId != null)
appendToArray.push({ domNode: rootNode, memoId: memoId });
} else if (rootNode.nodeType == 1) {
for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
findMemoNodes(childNodes[i], appendToArray);
}
}
return {
memoize: function (callback) {
if (typeof callback != "function")
throw new Error("You can only pass a function to ko.memoization.memoize()");
var memoId = generateRandomId();
memos[memoId] = callback;
return "<!--[ko_memo:" + memoId + "]-->";
},
unmemoize: function (memoId, callbackParams) {
var callback = memos[memoId];
if (callback === undefined)
throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
try {
callback.apply(null, callbackParams || []);
return true;
}
finally { delete memos[memoId]; }
},
unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
var memos = [];
findMemoNodes(domNode, memos);
for (var i = 0, j = memos.length; i < j; i++) {
var node = memos[i].domNode;
var combinedParams = [node];
if (extraCallbackParamsArray)
ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
ko.memoization.unmemoize(memos[i].memoId, combinedParams);
node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
if (node.parentNode)
node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
}
},
parseMemoText: function (memoText) {
var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
return match ? match[1] : null;
}
};
})();
ko.exportSymbol('memoization', ko.memoization);
ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
ko.extenders = {
'throttle': function (target, timeout) {
// Throttling means two things:
// (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
// notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
target['throttleEvaluation'] = timeout;
// (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
// so the target cannot change value synchronously or faster than a certain rate
var writeTimeoutInstance = null;
return ko.dependentObservable({
'read': target,
'write': function (value) {
clearTimeout(writeTimeoutInstance);
writeTimeoutInstance = setTimeout(function () {
target(value);
}, timeout);
}
});
},
'rateLimit': function (target, options) {
var timeout, method, limitFunction;
if (typeof options == 'number') {
timeout = options;
} else {
timeout = options['timeout'];
method = options['method'];
}
limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle;
target.limit(function (callback) {
return limitFunction(callback, timeout);
});
},
'notify': function (target, notifyWhen) {
target["equalityComparer"] = notifyWhen == "always" ?
null : // null equalityComparer means to always notify
valuesArePrimitiveAndEqual;
}
};
var primitiveTypes = { 'undefined': 1, 'boolean': 1, 'number': 1, 'string': 1 };
function valuesArePrimitiveAndEqual(a, b) {
var oldValueIsPrimitive = (a === null) || (typeof (a) in primitiveTypes);
return oldValueIsPrimitive ? (a === b) : false;
}
function throttle(callback, timeout) {
var timeoutInstance;
return function () {
if (!timeoutInstance) {
timeoutInstance = setTimeout(function () {
timeoutInstance = undefined;
callback();
}, timeout);
}
};
}
function debounce(callback, timeout) {
var timeoutInstance;
return function () {
clearTimeout(timeoutInstance);
timeoutInstance = setTimeout(callback, timeout);
};
}
function applyExtenders(requestedExtenders) {
var target = this;
if (requestedExtenders) {
ko.utils.objectForEach(requestedExtenders, function (key, value) {
var extenderHandler = ko.extenders[key];
if (typeof extenderHandler == 'function') {
target = extenderHandler(target, value) || target;
}
});
}
return target;
}
ko.exportSymbol('extenders', ko.extenders);
ko.subscription = function (target, callback, disposeCallback) {
this._target = target;
this.callback = callback;
this.disposeCallback = disposeCallback;
this.isDisposed = false;
ko.exportProperty(this, 'dispose', this.dispose);
};
ko.subscription.prototype.dispose = function () {
this.isDisposed = true;
this.disposeCallback();
};
ko.subscribable = function () {
ko.utils.setPrototypeOfOrExtend(this, ko.subscribable['fn']);
this._subscriptions = {};
this._versionNumber = 1;
}
var defaultEvent = "change";
var ko_subscribable_fn = {
subscribe: function (callback, callbackTarget, event) {
var self = this;
event = event || defaultEvent;
var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
var subscription = new ko.subscription(self, boundCallback, function () {
ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
if (self.afterSubscriptionRemove)
self.afterSubscriptionRemove(event);
});
if (self.beforeSubscriptionAdd)
self.beforeSubscriptionAdd(event);
if (!self._subscriptions[event])
self._subscriptions[event] = [];
self._subscriptions[event].push(subscription);
return subscription;
},
"notifySubscribers": function (valueToNotify, event) {
event = event || defaultEvent;
if (event === defaultEvent) {
this.updateVersion();
}
if (this.hasSubscriptionsForEvent(event)) {
try {
ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) {
// In case a subscription was disposed during the arrayForEach cycle, check
// for isDisposed on each subscription before invoking its callback
if (!subscription.isDisposed)
subscription.callback(valueToNotify);
}
} finally {
ko.dependencyDetection.end(); // End suppressing dependency detection
}
}
},
getVersion: function () {
return this._versionNumber;
},
hasChanged: function (versionToCheck) {
return this.getVersion() !== versionToCheck;
},
updateVersion: function () {
++this._versionNumber;
},
limit: function (limitFunction) {
var self = this, selfIsObservable = ko.isObservable(self),
isPending, previousValue, pendingValue, beforeChange = 'beforeChange';
if (!self._origNotifySubscribers) {
self._origNotifySubscribers = self["notifySubscribers"];
self["notifySubscribers"] = function (value, event) {
if (!event || event === defaultEvent) {
self._rateLimitedChange(value);
} else if (event === beforeChange) {
self._rateLimitedBeforeChange(value);
} else {
self._origNotifySubscribers(value, event);
}
};
}
var finish = limitFunction(function () {
// If an observable provided a reference to itself, access it to get the latest value.
// This allows computed observables to delay calculating their value until needed.
if (selfIsObservable && pendingValue === self) {
pendingValue = self();
}
isPending = false;
if (self.isDifferent(previousValue, pendingValue)) {
self._origNotifySubscribers(previousValue = pendingValue);
}
});
self._rateLimitedChange = function (value) {
isPending = true;
pendingValue = value;
finish();
};
self._rateLimitedBeforeChange = function (value) {
if (!isPending) {
previousValue = value;
self._origNotifySubscribers(value, beforeChange);
}
};
},
hasSubscriptionsForEvent: function (event) {
return this._subscriptions[event] && this._subscriptions[event].length;
},
getSubscriptionsCount: function (event) {
if (event) {
return this._subscriptions[event] && this._subscriptions[event].length || 0;
} else {
var total = 0;
ko.utils.objectForEach(this._subscriptions, function (eventName, subscriptions) {
total += subscriptions.length;
});
return total;
}
},
isDifferent: function (oldValue, newValue) {
return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
},
extend: applyExtenders
};
ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
// For browsers that support proto assignment, we overwrite the prototype of each
// observable instance. Since observables are functions, we need Function.prototype
// to still be in the prototype chain.
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
}
ko.subscribable['fn'] = ko_subscribable_fn;
ko.isSubscribable = function (instance) {
return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
};
ko.exportSymbol('subscribable', ko.subscribable);
ko.exportSymbol('isSubscribable', ko.isSubscribable);
ko.computedContext = ko.dependencyDetection = (function () {
var outerFrames = [],
currentFrame,
lastId = 0;
// Return a unique ID that can be assigned to an observable for dependency tracking.
// Theoretically, you could eventually overflow the number storage size, resulting
// in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
// or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
// take over 285 years to reach that number.
// Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
function getId() {
return ++lastId;
}
function begin(options) {
outerFrames.push(currentFrame);
currentFrame = options;
}
function end() {
currentFrame = outerFrames.pop();
}
return {
begin: begin,
end: end,
registerDependency: function (subscribable) {
if (currentFrame) {
if (!ko.isSubscribable(subscribable))
throw new Error("Only subscribable things can act as dependencies");
currentFrame.callback(subscribable, subscribable._id || (subscribable._id = getId()));
}
},
ignore: function (callback, callbackTarget, callbackArgs) {
try {
begin();
return callback.apply(callbackTarget, callbackArgs || []);
} finally {
end();
}
},
getDependenciesCount: function () {
if (currentFrame)
return currentFrame.computed.getDependenciesCount();
},
isInitial: function () {
if (currentFrame)
return currentFrame.isInitial;
}
};
})();
ko.exportSymbol('computedContext', ko.computedContext);
ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
ko.exportSymbol('computedContext.isSleeping', ko.computedContext.isSleeping);
ko.exportSymbol('ignoreDependencies', ko.ignoreDependencies = ko.dependencyDetection.ignore);
ko.observable = function (initialValue) {
var _latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
// Ignore writes if the value hasn't changed
if (observable.isDifferent(_latestValue, arguments[0])) {
observable.valueWillMutate();
_latestValue = arguments[0];
if (DEBUG) observable._latestValue = _latestValue;
observable.valueHasMutated();
}
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return _latestValue;
}
}
ko.subscribable.call(observable);
ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
if (DEBUG) observable._latestValue = _latestValue;
observable.peek = function () { return _latestValue };
observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
ko.exportProperty(observable, 'peek', observable.peek);
ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
return observable;
}
ko.observable['fn'] = {
"equalityComparer": valuesArePrimitiveAndEqual
};
var protoProperty = ko.observable.protoProperty = "__ko_proto__";
ko.observable['fn'][protoProperty] = ko.observable;
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.observable constructor
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko.observable['fn'], ko.subscribable['fn']);
}
ko.hasPrototype = function (instance, prototype) {
if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
if (instance[protoProperty] === prototype) return true;
return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
};
ko.isObservable = function (instance) {
return ko.hasPrototype(instance, ko.observable);
}
ko.isWriteableObservable = function (instance) {
// Observable
if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
return true;
// Writeable dependent observable
if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
return true;
// Anything else
return false;
}
ko.exportSymbol('observable', ko.observable);
ko.exportSymbol('isObservable', ko.isObservable);
ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);
ko.observableArray = function (initialValues) {
initialValues = initialValues || [];
if (typeof initialValues != 'object' || !('length' in initialValues))
throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
var result = ko.observable(initialValues);
ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
return result.extend({ 'trackArrayChanges': true });
};
ko.observableArray['fn'] = {
'remove': function (valueOrPredicate) {
var underlyingArray = this.peek();
var removedValues = [];
var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
for (var i = 0; i < underlyingArray.length; i++) {
var value = underlyingArray[i];
if (predicate(value)) {
if (removedValues.length === 0) {
this.valueWillMutate();
}
removedValues.push(value);
underlyingArray.splice(i, 1);
i--;
}
}
if (removedValues.length) {
this.valueHasMutated();
}
return removedValues;
},
'removeAll': function (arrayOfValues) {
// If you passed zero args, we remove everything
if (arrayOfValues === undefined) {
var underlyingArray = this.peek();
var allValues = underlyingArray.slice(0);
this.valueWillMutate();
underlyingArray.splice(0, underlyingArray.length);
this.valueHasMutated();
return allValues;
}
// If you passed an arg, we interpret it as an array of entries to remove
if (!arrayOfValues)
return [];
return this['remove'](function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
},
'destroy': function (valueOrPredicate) {
var underlyingArray = this.peek();
var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
this.valueWillMutate();
for (var i = underlyingArray.length - 1; i >= 0; i--) {
var value = underlyingArray[i];
if (predicate(value))
underlyingArray[i]["_destroy"] = true;
}
this.valueHasMutated();
},
'destroyAll': function (arrayOfValues) {
// If you passed zero args, we destroy everything
if (arrayOfValues === undefined)
return this['destroy'](function () { return true });
// If you passed an arg, we interpret it as an array of entries to destroy
if (!arrayOfValues)
return [];
return this['destroy'](function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
},
'indexOf': function (item) {
var underlyingArray = this();
return ko.utils.arrayIndexOf(underlyingArray, item);
},
'replace': function (oldItem, newItem) {
var index = this['indexOf'](oldItem);
if (index >= 0) {
this.valueWillMutate();
this.peek()[index] = newItem;
this.valueHasMutated();
}
}
};
// Populate ko.observableArray.fn with read/write functions from native arrays
// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
ko.observableArray['fn'][methodName] = function () {
// Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
// (for consistency with mutating regular observables)
var underlyingArray = this.peek();
this.valueWillMutate();
this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
this.valueHasMutated();
return methodCallResult;
};
});
// Populate ko.observableArray.fn with read-only functions from native arrays
ko.utils.arrayForEach(["slice"], function (methodName) {
ko.observableArray['fn'][methodName] = function () {
var underlyingArray = this();
return underlyingArray[methodName].apply(underlyingArray, arguments);
};
});
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.observableArray constructor
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
}
ko.exportSymbol('observableArray', ko.observableArray);
var arrayChangeEventName = 'arrayChange';
ko.extenders['trackArrayChanges'] = function (target) {
// Only modify the target observable once
if (target.cacheDiffForKnownOperation) {
return;
}
var trackingChanges = false,
cachedDiff = null,
arrayChangeSubscription,
pendingNotifications = 0,
underlyingBeforeSubscriptionAddFunction = target.beforeSubscriptionAdd,
underlyingAfterSubscriptionRemoveFunction = target.afterSubscriptionRemove;
// Watch "subscribe" calls, and for array change events, ensure change tracking is enabled
target.beforeSubscriptionAdd = function (event) {
if (underlyingBeforeSubscriptionAddFunction)
underlyingBeforeSubscriptionAddFunction.call(target, event);
if (event === arrayChangeEventName) {
trackChanges();
}
};
// Watch "dispose" calls, and for array change events, ensure change tracking is disabled when all are disposed
target.afterSubscriptionRemove = function (event) {
if (underlyingAfterSubscriptionRemoveFunction)
underlyingAfterSubscriptionRemoveFunction.call(target, event);
if (event === arrayChangeEventName && !target.hasSubscriptionsForEvent(arrayChangeEventName)) {
arrayChangeSubscription.dispose();
trackingChanges = false;
}
};
function trackChanges() {
// Calling 'trackChanges' multiple times is the same as calling it once
if (trackingChanges) {
return;
}
trackingChanges = true;
// Intercept "notifySubscribers" to track how many times it was called.
var underlyingNotifySubscribersFunction = target['notifySubscribers'];
target['notifySubscribers'] = function (valueToNotify, event) {
if (!event || event === defaultEvent) {
++pendingNotifications;
}
return underlyingNotifySubscribersFunction.apply(this, arguments);
};
// Each time the array changes value, capture a clone so that on the next
// change it's possible to produce a diff
var previousContents = [].concat(target.peek() || []);
cachedDiff = null;
arrayChangeSubscription = target.subscribe(function (currentContents) {
// Make a copy of the current contents and ensure it's an array
currentContents = [].concat(currentContents || []);
// Compute the diff and issue notifications, but only if someone is listening
if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
var changes = getChanges(previousContents, currentContents);
}
// Eliminate references to the old, removed items, so they can be GCed
previousContents = currentContents;
cachedDiff = null;
pendingNotifications = 0;
if (changes && changes.length) {
target['notifySubscribers'](changes, arrayChangeEventName);
}
});
}
function getChanges(previousContents, currentContents) {
// We try to re-use cached diffs.
// The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
// plugin, which without this check would not be compatible with arrayChange notifications. Normally,
// notifications are issued immediately so we wouldn't be queueing up more than one.
if (!cachedDiff || pendingNotifications > 1) {
cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true });
}
return cachedDiff;
}
target.cacheDiffForKnownOperation = function (rawArray, operationName, args) {
// Only run if we're currently tracking changes for this observable array
// and there aren't any pending deferred notifications.
if (!trackingChanges || pendingNotifications) {
return;
}
var diff = [],
arrayLength = rawArray.length,
argsLength = args.length,
offset = 0;
function pushDiff(status, value, index) {
return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
}
switch (operationName) {
case 'push':
offset = arrayLength;
case 'unshift':
for (var index = 0; index < argsLength; index++) {
pushDiff('added', args[index], offset + index);
}
break;
case 'pop':
offset = arrayLength - 1;
case 'shift':
if (arrayLength) {
pushDiff('deleted', rawArray[offset], offset);
}
break;
case 'splice':
// Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
endAddIndex = startIndex + argsLength - 2,
endIndex = Math.max(endDeleteIndex, endAddIndex),
additions = [], deletions = [];
for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
if (index < endDeleteIndex)
deletions.push(pushDiff('deleted', rawArray[index], index));
if (index < endAddIndex)
additions.push(pushDiff('added', args[argsIndex], index));
}
ko.utils.findMovesInArrayComparison(deletions, additions);
break;
default:
return;
}
cachedDiff = diff;
};
};
ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
var _latestValue,
_needsEvaluation = true,
_isBeingEvaluated = false,
_suppressDisposalUntilDisposeWhenReturnsFalse = false,
_isDisposed = false,
readFunction = evaluatorFunctionOrOptions,
pure = false,
isSleeping = false;
if (readFunction && typeof readFunction == "object") {
// Single-parameter syntax - everything is on this "options" param
options = readFunction;
readFunction = options["read"];
} else {
// Multi-parameter syntax - construct the options according to the params passed
options = options || {};
if (!readFunction)
readFunction = options["read"];
}
if (typeof readFunction != "function")
throw new Error("Pass a function that returns the value of the ko.computed");
function addDependencyTracking(id, target, trackingObj) {
if (pure && target === dependentObservable) {
throw Error("A 'pure' computed must not be called recursively");
}
dependencyTracking[id] = trackingObj;
trackingObj._order = _dependenciesCount++;
trackingObj._version = target.getVersion();
}
function haveDependenciesChanged() {
var id, dependency;
for (id in dependencyTracking) {
if (dependencyTracking.hasOwnProperty(id)) {
dependency = dependencyTracking[id];
if (dependency._target.hasChanged(dependency._version)) {
return true;
}
}
}
}
function disposeComputed() {
if (!isSleeping && dependencyTracking) {
ko.utils.objectForEach(dependencyTracking, function (id, dependency) {
if (dependency.dispose)
dependency.dispose();
});
}
dependencyTracking = null;
_dependenciesCount = 0;
_isDisposed = true;
_needsEvaluation = false;
isSleeping = false;
}
function evaluatePossiblyAsync() {
var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
clearTimeout(evaluationTimeoutInstance);
evaluationTimeoutInstance = setTimeout(function () {
evaluateImmediate(true /*notifyChange*/);
}, throttleEvaluationTimeout);
} else if (dependentObservable._evalRateLimited) {
dependentObservable._evalRateLimited();
} else {
evaluateImmediate(true /*notifyChange*/);
}
}
function evaluateImmediate(notifyChange) {
if (_isBeingEvaluated) {
// If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
// This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
// certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
// their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
return;
}
// Do not evaluate (and possibly capture new dependencies) if disposed
if (_isDisposed) {
return;
}
if (disposeWhen && disposeWhen()) {
// See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
if (!_suppressDisposalUntilDisposeWhenReturnsFalse) {
dispose();
return;
}
} else {
// It just did return false, so we can stop suppressing now
_suppressDisposalUntilDisposeWhenReturnsFalse = false;
}
_isBeingEvaluated = true;
try {
// Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
// Then, during evaluation, we cross off any that are in fact still being used.
var disposalCandidates = dependencyTracking,
disposalCount = _dependenciesCount,
isInitial = pure ? undefined : !_dependenciesCount; // If we're evaluating when there are no previous dependencies, it must be the first time
ko.dependencyDetection.begin({
callback: function (subscribable, id) {
if (!_isDisposed) {
if (disposalCount && disposalCandidates[id]) {
// Don't want to dispose this subscription, as it's still being used
addDependencyTracking(id, subscribable, disposalCandidates[id]);
delete disposalCandidates[id];
--disposalCount;
} else if (!dependencyTracking[id]) {
// Brand new subscription - add it
addDependencyTracking(id, subscribable, isSleeping ? { _target: subscribable } : subscribable.subscribe(evaluatePossiblyAsync));
}
}
},
computed: dependentObservable,
isInitial: isInitial
});
dependencyTracking = {};
_dependenciesCount = 0;
try {
var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction();
} finally {
ko.dependencyDetection.end();
// For each subscription no longer being used, remove it from the active subscriptions list and dispose it
if (disposalCount && !isSleeping) {
ko.utils.objectForEach(disposalCandidates, function (id, toDispose) {
if (toDispose.dispose)
toDispose.dispose();
});
}
_needsEvaluation = false;
}
if (dependentObservable.isDifferent(_latestValue, newValue)) {
if (!isSleeping) {
notify(_latestValue, "beforeChange");
}
_latestValue = newValue;
if (DEBUG) dependentObservable._latestValue = _latestValue;
if (isSleeping) {
dependentObservable.updateVersion();
} else if (notifyChange) {
notify(_latestValue);
}
}
if (isInitial) {
notify(_latestValue, "awake");
}
} finally {
_isBeingEvaluated = false;
}
if (!_dependenciesCount)
dispose();
}
function dependentObservable() {
if (arguments.length > 0) {
if (typeof writeFunction === "function") {
// Writing a value
writeFunction.apply(evaluatorFunctionTarget, arguments);
} else {
throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
}
return this; // Permits chained assignments
} else {
// Reading the value
ko.dependencyDetection.registerDependency(dependentObservable);
if (_needsEvaluation || (isSleeping && haveDependenciesChanged())) {
evaluateImmediate();
}
return _latestValue;
}
}
function peek() {
// Peek won't re-evaluate, except while the computed is sleeping or to get the initial value when "deferEvaluation" is set.
if ((_needsEvaluation && !_dependenciesCount) || (isSleeping && haveDependenciesChanged())) {
evaluateImmediate();
}
return _latestValue;
}
function isActive() {
return _needsEvaluation || _dependenciesCount > 0;
}
function notify(value, event) {
dependentObservable["notifySubscribers"](value, event);
}
// By here, "options" is always non-null
var writeFunction = options["write"],
disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
disposeWhenOption = options["disposeWhen"] || options.disposeWhen,
disposeWhen = disposeWhenOption,
dispose = disposeComputed,
dependencyTracking = {},
_dependenciesCount = 0,
evaluationTimeoutInstance = null;
if (!evaluatorFunctionTarget)
evaluatorFunctionTarget = options["owner"];
ko.subscribable.call(dependentObservable);
ko.utils.setPrototypeOfOrExtend(dependentObservable, ko.dependentObservable['fn']);
dependentObservable.peek = peek;
dependentObservable.getDependenciesCount = function () { return _dependenciesCount; };
dependentObservable.hasWriteFunction = typeof writeFunction === "function";
dependentObservable.dispose = function () { dispose(); };
dependentObservable.isActive = isActive;
// Replace the limit function with one that delays evaluation as well.
var originalLimit = dependentObservable.limit;
dependentObservable.limit = function (limitFunction) {
originalLimit.call(dependentObservable, limitFunction);
dependentObservable._evalRateLimited = function () {
dependentObservable._rateLimitedBeforeChange(_latestValue);
_needsEvaluation = true; // Mark as dirty
// Pass the observable to the rate-limit code, which will access it when
// it's time to do the notification.
dependentObservable._rateLimitedChange(dependentObservable);
}
};
if (options['pure']) {
pure = true;
isSleeping = true; // Starts off sleeping; will awake on the first subscription
dependentObservable.beforeSubscriptionAdd = function (event) {
// If asleep, wake up the computed by subscribing to any dependencies.
if (!_isDisposed && isSleeping && event == 'change') {
isSleeping = false;
if (_needsEvaluation || haveDependenciesChanged()) {
dependencyTracking = null;
_dependenciesCount = 0;
_needsEvaluation = true;
evaluateImmediate();
} else {
// First put the dependencies in order
var dependeciesOrder = [];
ko.utils.objectForEach(dependencyTracking, function (id, dependency) {
dependeciesOrder[dependency._order] = id;
});
// Next, subscribe to each one
ko.utils.arrayForEach(dependeciesOrder, function (id, order) {
var dependency = dependencyTracking[id],
subscription = dependency._target.subscribe(evaluatePossiblyAsync);
subscription._order = order;
subscription._version = dependency._version;
dependencyTracking[id] = subscription;
});
}
if (!_isDisposed) { // test since evaluating could trigger disposal
notify(_latestValue, "awake");
}
}
};
dependentObservable.afterSubscriptionRemove = function (event) {
if (!_isDisposed && event == 'change' && !dependentObservable.hasSubscriptionsForEvent('change')) {
ko.utils.objectForEach(dependencyTracking, function (id, dependency) {
if (dependency.dispose) {
dependencyTracking[id] = {
_target: dependency._target,
_order: dependency._order,
_version: dependency._version
};
dependency.dispose();
}
});
isSleeping = true;
notify(undefined, "asleep");
}
};
// Because a pure computed is not automatically updated while it is sleeping, we can't
// simply return the version number. Instead, we check if any of the dependencies have
// changed and conditionally re-evaluate the computed observable.
dependentObservable._originalGetVersion = dependentObservable.getVersion;
dependentObservable.getVersion = function () {
if (isSleeping && (_needsEvaluation || haveDependenciesChanged())) {
evaluateImmediate();
}
return dependentObservable._originalGetVersion();
};
} else if (options['deferEvaluation']) {
// This will force a computed with deferEvaluation to evaluate when the first subscriptions is registered.
dependentObservable.beforeSubscriptionAdd = function (event) {
if (event == 'change' || event == 'beforeChange') {
peek();
}
}
}
ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
// Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
if (disposeWhenNodeIsRemoved) {
// Since this computed is associated with a DOM node, and we don't want to dispose the computed
// until the DOM node is *removed* from the document (as opposed to never having been in the document),
// we'll prevent disposal until "disposeWhen" first returns false.
_suppressDisposalUntilDisposeWhenReturnsFalse = true;
// Only watch for the node's disposal if the value really is a node. It might not be,
// e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
// after first false result" behaviour even if there's no specific node to watch. This
// technique is intended for KO's internal use only and shouldn't be documented or used
// by application code, as it's likely to change in a future version of KO.
if (disposeWhenNodeIsRemoved.nodeType) {
disposeWhen = function () {
return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption());
};
}
}
// Evaluate, unless sleeping or deferEvaluation is true
if (!isSleeping && !options['deferEvaluation'])
evaluateImmediate();
// Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
// removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
if (disposeWhenNodeIsRemoved && isActive() && disposeWhenNodeIsRemoved.nodeType) {
dispose = function () {
ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose);
disposeComputed();
};
ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
}
return dependentObservable;
};
ko.isComputed = function (instance) {
return ko.hasPrototype(instance, ko.dependentObservable);
};
var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
ko.dependentObservable[protoProp] = ko.observable;
ko.dependentObservable['fn'] = {
"equalityComparer": valuesArePrimitiveAndEqual
};
ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.dependentObservable constructor
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko.dependentObservable['fn'], ko.subscribable['fn']);
}
ko.exportSymbol('dependentObservable', ko.dependentObservable);
ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
ko.exportSymbol('isComputed', ko.isComputed);
ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {
if (typeof evaluatorFunctionOrOptions === 'function') {
return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, { 'pure': true });
} else {
evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object
evaluatorFunctionOrOptions['pure'] = true;
return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);
}
}
ko.exportSymbol('pureComputed', ko.pureComputed);
(function () {
var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
ko.toJS = function (rootObject) {
if (arguments.length == 0)
throw new Error("When calling ko.toJS, pass the object you want to convert.");
// We just unwrap everything at every level in the object graph
return mapJsObjectGraph(rootObject, function (valueToMap) {
// Loop because an observable's value might in turn be another observable wrapper
for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth) ; i++)
valueToMap = valueToMap();
return valueToMap;
});
};
ko.toJSON = function (rootObject, replacer, space) { // replacer and space are optional
var plainJavaScriptObject = ko.toJS(rootObject);
return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
};
function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
visitedObjects = visitedObjects || new objectLookup();
rootObject = mapInputCallback(rootObject);
var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
if (!canHaveProperties)
return rootObject;
var outputProperties = rootObject instanceof Array ? [] : {};
visitedObjects.save(rootObject, outputProperties);
visitPropertiesOrArrayEntries(rootObject, function (indexer) {
var propertyValue = mapInputCallback(rootObject[indexer]);
switch (typeof propertyValue) {
case "boolean":
case "number":
case "string":
case "function":
outputProperties[indexer] = propertyValue;
break;
case "object":
case "undefined":
var previouslyMappedValue = visitedObjects.get(propertyValue);
outputProperties[indexer] = (previouslyMappedValue !== undefined)
? previouslyMappedValue
: mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
break;
}
});
return outputProperties;
}
function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
if (rootObject instanceof Array) {
for (var i = 0; i < rootObject.length; i++)
visitorCallback(i);
// For arrays, also respect toJSON property for custom mappings (fixes #278)
if (typeof rootObject['toJSON'] == 'function')
visitorCallback('toJSON');
} else {
for (var propertyName in rootObject) {
visitorCallback(propertyName);
}
}
};
function objectLookup() {
this.keys = [];
this.values = [];
};
objectLookup.prototype = {
constructor: objectLookup,
save: function (key, value) {
var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
if (existingIndex >= 0)
this.values[existingIndex] = value;
else {
this.keys.push(key);
this.values.push(value);
}
},
get: function (key) {
var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
}
};
})();
ko.exportSymbol('toJS', ko.toJS);
ko.exportSymbol('toJSON', ko.toJSON);
(function () {
var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
// Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
// are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
// that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
ko.selectExtensions = {
readValue: function (element) {
switch (ko.utils.tagNameLower(element)) {
case 'option':
if (element[hasDomDataExpandoProperty] === true)
return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
return ko.utils.ieVersion <= 7
? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
: element.value;
case 'select':
return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
default:
return element.value;
}
},
writeValue: function (element, value, allowUnset) {
switch (ko.utils.tagNameLower(element)) {
case 'option':
switch (typeof value) {
case "string":
ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
delete element[hasDomDataExpandoProperty];
}
element.value = value;
break;
default:
// Store arbitrary object using DomData
ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
element[hasDomDataExpandoProperty] = true;
// Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
element.value = typeof value === "number" ? value : "";
break;
}
break;
case 'select':
if (value === "" || value === null) // A blank string or null value will select the caption
value = undefined;
var selection = -1;
for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
optionValue = ko.selectExtensions.readValue(element.options[i]);
// Include special check to handle selecting a caption with a blank string value
if (optionValue == value || (optionValue == "" && value === undefined)) {
selection = i;
break;
}
}
if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
element.selectedIndex = selection;
}
break;
default:
if ((value === null) || (value === undefined))
value = "";
element.value = value;
break;
}
}
};
})();
ko.exportSymbol('selectExtensions', ko.selectExtensions);
ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
ko.expressionRewriting = (function () {
var javaScriptReservedWords = ["true", "false", "null", "undefined"];
// Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
// This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
// This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
function getWriteableValue(expression) {
if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
return false;
var match = expression.match(javaScriptAssignmentTarget);
return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
}
// The following regular expressions will be used to split an object-literal string into tokens
// These two match strings, either with double quotes or single quotes
var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
// Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
// as a regular expression (this is handled by the parsing loop below).
stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
// These characters have special meaning to the parser and must not appear in the middle of a
// token, except as part of a string.
specials = ',"\'{}()/:[\\]',
// Match text (at least two characters) that does not contain any of the above special characters,
// although some of the special characters are allowed to start it (all but the colon and comma).
// The text can contain spaces, but leading or trailing spaces are skipped.
everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
// Match any non-space character not matched already. This will match colons and commas, since they're
// not matched by "everyThingElse", but will also match any other single character that wasn't already
// matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
oneNotSpace = '[^\\s]',
// Create the actual regular expression by or-ing the above strings. The order is important.
bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
// Match end of previous token to determine whether a slash is a division or regex.
divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
keywordRegexLookBehind = { 'in': 1, 'return': 1, 'typeof': 1 };
function parseObjectLiteral(objectLiteralString) {
// Trim leading and trailing spaces from the string
var str = ko.utils.stringTrim(objectLiteralString);
// Trim braces '{' surrounding the whole object literal
if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
// Split into tokens
var result = [], toks = str.match(bindingToken), key, values = [], depth = 0;
if (toks) {
// Append a comma so that we don't need a separate code block to deal with the last item
toks.push(',');
for (var i = 0, tok; tok = toks[i]; ++i) {
var c = tok.charCodeAt(0);
// A comma signals the end of a key/value pair if depth is zero
if (c === 44) { // ","
if (depth <= 0) {
result.push((key && values.length) ? { key: key, value: values.join('') } : { 'unknown': key || values.join('') });
key = depth = 0;
values = [];
continue;
}
// Simply skip the colon that separates the name and value
} else if (c === 58) { // ":"
if (!depth && !key && values.length === 1) {
key = values.pop();
continue;
}
// A set of slashes is initially matched as a regular expression, but could be division
} else if (c === 47 && i && tok.length > 1) { // "/"
// Look at the end of the previous token to determine if the slash is actually division
var match = toks[i - 1].match(divisionLookBehind);
if (match && !keywordRegexLookBehind[match[0]]) {
// The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
str = str.substr(str.indexOf(tok) + 1);
toks = str.match(bindingToken);
toks.push(',');
i = -1;
// Continue with just the slash
tok = '/';
}
// Increment depth for parentheses, braces, and brackets so that interior commas are ignored
} else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
++depth;
} else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
--depth;
// The key will be the first token; if it's a string, trim the quotes
} else if (!key && !values.length && (c === 34 || c === 39)) { // '"', "'"
tok = tok.slice(1, -1);
}
values.push(tok);
}
}
return result;
}
// Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
var twoWayBindings = {};
function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
bindingOptions = bindingOptions || {};
function processKeyValue(key, val) {
var writableVal;
function callPreprocessHook(obj) {
return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
}
if (!bindingParams) {
if (!callPreprocessHook(ko['getBindingHandler'](key)))
return;
if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
// For two-way bindings, provide a write method in case the value
// isn't a writable observable.
propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
}
}
// Values are wrapped in a function so that each value can be accessed independently
if (makeValueAccessors) {
val = 'function(){return ' + val + ' }';
}
resultStrings.push("'" + key + "':" + val);
}
var resultStrings = [],
propertyAccessorResultStrings = [],
makeValueAccessors = bindingOptions['valueAccessors'],
bindingParams = bindingOptions['bindingParams'],
keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
ko.utils.arrayForEach(keyValueArray, function (keyValue) {
processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
});
if (propertyAccessorResultStrings.length)
processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
return resultStrings.join(",");
}
return {
bindingRewriteValidators: [],
twoWayBindings: twoWayBindings,
parseObjectLiteral: parseObjectLiteral,
preProcessBindings: preProcessBindings,
keyValueArrayContainsKey: function (keyValueArray, key) {
for (var i = 0; i < keyValueArray.length; i++)
if (keyValueArray[i]['key'] == key)
return true;
return false;
},
// Internal, private KO utility for updating model properties from within bindings
// property: If the property being updated is (or might be) an observable, pass it here
// If it turns out to be a writable observable, it will be written to directly
// allBindings: An object with a get method to retrieve bindings in the current execution context.
// This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
// key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
// value: The value to be written
// checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
// it is !== existing value on that writable observable
writeValueToProperty: function (property, allBindings, key, value, checkIfDifferent) {
if (!property || !ko.isObservable(property)) {
var propWriters = allBindings.get('_ko_property_writers');
if (propWriters && propWriters[key])
propWriters[key](value);
} else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
property(value);
}
}
};
})();
ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
// Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
// all bindings could use an official 'property writer' API without needing to declare that they might). However,
// since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
// as an internal implementation detail in the short term.
// For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
// undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
// public API, and we reserve the right to remove it at any time if we create a real public property writers API.
ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
(function () {
// "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
// may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
// If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
// of that virtual hierarchy
//
// The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
// without having to scatter special cases all over the binding and templating code.
// IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
// but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
// So, use node.text where available, and node.nodeValue elsewhere
var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
function isStartComment(node) {
return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
}
function isEndComment(node) {
return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
}
function getVirtualChildren(startComment, allowUnbalanced) {
var currentNode = startComment;
var depth = 1;
var children = [];
while (currentNode = currentNode.nextSibling) {
if (isEndComment(currentNode)) {
depth--;
if (depth === 0)
return children;
}
children.push(currentNode);
if (isStartComment(currentNode))
depth++;
}
if (!allowUnbalanced)
throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
return null;
}
function getMatchingEndComment(startComment, allowUnbalanced) {
var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
if (allVirtualChildren) {
if (allVirtualChildren.length > 0)
return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
return startComment.nextSibling;
} else
return null; // Must have no matching end comment, and allowUnbalanced is true
}
function getUnbalancedChildTags(node) {
// e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
// from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
var childNode = node.firstChild, captureRemaining = null;
if (childNode) {
do {
if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
captureRemaining.push(childNode);
else if (isStartComment(childNode)) {
var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
childNode = matchingEndComment;
else
captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
} else if (isEndComment(childNode)) {
captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
}
} while (childNode = childNode.nextSibling);
}
return captureRemaining;
}
ko.virtualElements = {
allowedBindings: {},
childNodes: function (node) {
return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
},
emptyNode: function (node) {
if (!isStartComment(node))
ko.utils.emptyDomNode(node);
else {
var virtualChildren = ko.virtualElements.childNodes(node);
for (var i = 0, j = virtualChildren.length; i < j; i++)
ko.removeNode(virtualChildren[i]);
}
},
setDomNodeChildren: function (node, childNodes) {
if (!isStartComment(node))
ko.utils.setDomNodeChildren(node, childNodes);
else {
ko.virtualElements.emptyNode(node);
var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
for (var i = 0, j = childNodes.length; i < j; i++)
endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
}
},
prepend: function (containerNode, nodeToPrepend) {
if (!isStartComment(containerNode)) {
if (containerNode.firstChild)
containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
else
containerNode.appendChild(nodeToPrepend);
} else {
// Start comments must always have a parent and at least one following sibling (the end comment)
containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
}
},
insertAfter: function (containerNode, nodeToInsert, insertAfterNode) {
if (!insertAfterNode) {
ko.virtualElements.prepend(containerNode, nodeToInsert);
} else if (!isStartComment(containerNode)) {
// Insert after insertion point
if (insertAfterNode.nextSibling)
containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
else
containerNode.appendChild(nodeToInsert);
} else {
// Children of start comments must always have a parent and at least one following sibling (the end comment)
containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
}
},
firstChild: function (node) {
if (!isStartComment(node))
return node.firstChild;
if (!node.nextSibling || isEndComment(node.nextSibling))
return null;
return node.nextSibling;
},
nextSibling: function (node) {
if (isStartComment(node))
node = getMatchingEndComment(node);
if (node.nextSibling && isEndComment(node.nextSibling))
return null;
return node.nextSibling;
},
hasBindingValue: isStartComment,
virtualNodeBindingValue: function (node) {
var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
return regexMatch ? regexMatch[1] : null;
},
normaliseVirtualElementDomStructure: function (elementVerified) {
// Workaround for https://github.com/SteveSanderson/knockout/issues/155
// (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
// that are direct descendants of <ul> into the preceding <li>)
if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
return;
// Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
// must be intended to appear *after* that child, so move them there.
var childNode = elementVerified.firstChild;
if (childNode) {
do {
if (childNode.nodeType === 1) {
var unbalancedTags = getUnbalancedChildTags(childNode);
if (unbalancedTags) {
// Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
var nodeToInsertBefore = childNode.nextSibling;
for (var i = 0; i < unbalancedTags.length; i++) {
if (nodeToInsertBefore)
elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
else
elementVerified.appendChild(unbalancedTags[i]);
}
}
}
} while (childNode = childNode.nextSibling);
}
}
};
})();
ko.exportSymbol('virtualElements', ko.virtualElements);
ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
(function () {
var defaultBindingAttributeName = "data-bind";
ko.bindingProvider = function () {
this.bindingCache = {};
};
ko.utils.extend(ko.bindingProvider.prototype, {
'nodeHasBindings': function (node) {
switch (node.nodeType) {
case 1: // Element
return node.getAttribute(defaultBindingAttributeName) != null
|| ko.components['getComponentNameForNode'](node);
case 8: // Comment node
return ko.virtualElements.hasBindingValue(node);
default: return false;
}
},
'getBindings': function (node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext),
parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);
},
'getBindingAccessors': function (node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext),
parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;
return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'getBindingsString': function (node, bindingContext) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName); // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
default: return null;
}
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'parseBindingsString': function (bindingsString, bindingContext, node, options) {
try {
var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
return bindingFunction(bindingContext, node);
} catch (ex) {
ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
throw ex;
}
}
});
ko.bindingProvider['instance'] = new ko.bindingProvider();
function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
return cache[cacheKey]
|| (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
}
function createBindingsStringEvaluator(bindingsString, options) {
// Build the source for a function that evaluates "expression"
// For each scope variable, add an extra level of "with" nesting
// Example result: with(sc1) { with(sc0) { return (expression) } }
var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
return new Function("$context", "$element", functionBody);
}
})();
ko.exportSymbol('bindingProvider', ko.bindingProvider);
(function () {
ko.bindingHandlers = {};
// The following element types will not be recursed into during binding. In the future, we
// may consider adding <template> to this list, because such elements' contents are always
// intended to be bound in a different context from where they appear in the document.
var bindingDoesNotRecurseIntoElementTypes = {
// Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents,
// because it's unexpected and a potential XSS issue
'script': true,
'textarea': true
};
// Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
ko['getBindingHandler'] = function (bindingKey) {
return ko.bindingHandlers[bindingKey];
};
// The ko.bindingContext constructor is only called directly to create the root context. For child
// contexts, use bindingContext.createChildContext or bindingContext.extend.
ko.bindingContext = function (dataItemOrAccessor, parentContext, dataItemAlias, extendCallback) {
// The binding context object includes static properties for the current, parent, and root view models.
// If a view model is actually stored in an observable, the corresponding binding context object, and
// any child contexts, must be updated when the view model is changed.
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any obsevables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
ko.utils.extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
// During the first execution, "subscribable" isn't set, so don't bother doing the update then.
if (subscribable) {
self._subscribable = subscribable;
}
} else {
self['$parents'] = [];
self['$root'] = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self['ko'] = ko;
}
self['$rawData'] = dataItemOrObservable;
self['$data'] = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self['$data'];
}
function disposeWhen() {
return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
}
var self = this,
isFunc = typeof (dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
nodes,
subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
// At this point, the binding context has been initialized, and the "subscribable" computed observable is
// subscribed to any observables that were accessed in the process. If there is nothing to track, the
// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
// the context object.
if (subscribable.isActive()) {
self._subscribable = subscribable;
// Always notify because even if the model ($data) hasn't changed, other context properties might have changed
subscribable['equalityComparer'] = null;
// We need to be able to dispose of this computed observable when it's no longer needed. This would be
// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
// we cannot assume that those nodes have any relation to each other. So instead we track any node that
// the context is attached to, and dispose the computed when all of those nodes have been cleaned.
// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
nodes = [];
subscribable._addNode = function (node) {
nodes.push(node);
ko.utils.domNodeDisposal.addDisposeCallback(node, function (node) {
ko.utils.arrayRemoveItem(nodes, node);
if (!nodes.length) {
subscribable.dispose();
self._subscribable = subscribable = undefined;
}
});
};
}
}
// Extend the binding context hierarchy with a new view model object. If the parent context is watching
// any obsevables, the new child context will automatically get a dependency on the parent context.
// But this does not mean that the $data value of the child context will also get updated. If the child
// view model also depends on the parent view model, you must provide a function that returns the correct
// view model on each update.
ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback) {
return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function (self, parentContext) {
// Extend the context hierarchy by setting the appropriate pointers
self['$parentContext'] = parentContext;
self['$parent'] = parentContext['$data'];
self['$parents'] = (parentContext['$parents'] || []).slice(0);
self['$parents'].unshift(self['$parent']);
if (extendCallback)
extendCallback(self);
});
};
// Extend the binding context with new custom properties. This doesn't change the context hierarchy.
// Similarly to "child" contexts, provide a function here to make sure that the correct values are set
// when an observable view model is updated.
ko.bindingContext.prototype['extend'] = function (properties) {
// If the parent context references an observable view model, "_subscribable" will always be the
// latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
return new ko.bindingContext(this._subscribable || this['$data'], this, null, function (self, parentContext) {
// This "child" context doesn't directly track a parent observable view model,
// so we need to manually set the $rawData value to match the parent.
self['$rawData'] = parentContext['$rawData'];
ko.utils.extend(self, typeof (properties) == "function" ? properties() : properties);
});
};
// Returns the valueAccesor function for a binding value
function makeValueAccessor(value) {
return function () {
return value;
};
}
// Returns the value of a valueAccessor function
function evaluateValueAccessor(valueAccessor) {
return valueAccessor();
}
// Given a function that returns bindings, create and return a new object that contains
// binding value-accessors functions. Each accessor function calls the original function
// so that it always gets the latest value and all dependencies are captured. This is used
// by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
function makeAccessorsFromFunction(callback) {
return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function (value, key) {
return function () {
return callback()[key];
};
});
}
// Given a bindings function or object, create and return a new object that contains
// binding value-accessors functions. This is used by ko.applyBindingsToNode.
function makeBindingAccessors(bindings, context, node) {
if (typeof bindings === 'function') {
return makeAccessorsFromFunction(bindings.bind(null, context, node));
} else {
return ko.utils.objectMap(bindings, makeValueAccessor);
}
}
// This function is used if the binding provider doesn't include a getBindingAccessors function.
// It must be called with 'this' set to the provider instance.
function getBindingsAndMakeAccessors(node, context) {
return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
}
function validateThatBindingIsAllowedForVirtualElements(bindingName) {
var validator = ko.virtualElements.allowedBindings[bindingName];
if (!validator)
throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
}
function applyBindingsToDescendantsInternal(bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
var currentChild,
nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
provider = ko.bindingProvider['instance'],
preprocessNode = provider['preprocessNode'];
// Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
// possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
// implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
// trigger insertion of <template> contents at that point in the document.
if (preprocessNode) {
while (currentChild = nextInQueue) {
nextInQueue = ko.virtualElements.nextSibling(currentChild);
preprocessNode.call(provider, currentChild);
}
// Reset nextInQueue for the next loop
nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
}
while (currentChild = nextInQueue) {
// Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
nextInQueue = ko.virtualElements.nextSibling(currentChild);
applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
}
}
function applyBindingsToNodeAndDescendantsInternal(bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
var shouldBindDescendants = true;
// Perf optimisation: Apply bindings only if...
// (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
// Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
// (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
var isElement = (nodeVerified.nodeType === 1);
if (isElement) // Workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
|| ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
if (shouldApplyBindings)
shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
// We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
// * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
// hence bindingContextsMayDifferFromDomParentElement is false
// * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
// skip over any number of intermediate virtual elements, any of which might define a custom binding context,
// hence bindingContextsMayDifferFromDomParentElement is true
applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
}
}
var boundElementDomDataKey = ko.utils.domData.nextKey();
function topologicalSortBindings(bindings) {
// Depth-first sort
var result = [], // The list of key/handler pairs that we will return
bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
if (!bindingsConsidered[bindingKey]) {
var binding = ko['getBindingHandler'](bindingKey);
if (binding) {
// First add dependencies (if any) of the current binding
if (binding['after']) {
cyclicDependencyStack.push(bindingKey);
ko.utils.arrayForEach(binding['after'], function (bindingDependencyKey) {
if (bindings[bindingDependencyKey]) {
if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
} else {
pushBinding(bindingDependencyKey);
}
}
});
cyclicDependencyStack.length--;
}
// Next add the current binding
result.push({ key: bindingKey, handler: binding });
}
bindingsConsidered[bindingKey] = true;
}
});
return result;
}
function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
// Prevent multiple applyBindings calls for the same node, except when a binding value is specified
var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
if (!sourceBindings) {
if (alreadyBound) {
throw Error("You cannot apply bindings multiple times to the same element.");
}
ko.utils.domData.set(node, boundElementDomDataKey, true);
}
// Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
// we can easily recover it just by scanning up the node's ancestors in the DOM
// (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
ko.storedBindingContextForNode(node, bindingContext);
// Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
var bindings;
if (sourceBindings && typeof sourceBindings !== 'function') {
bindings = sourceBindings;
} else {
var provider = ko.bindingProvider['instance'],
getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
// Get the binding from the provider within a computed observable so that we can update the bindings whenever
// the binding context is updated or if the binding provider accesses observables.
var bindingsUpdater = ko.dependentObservable(
function () {
bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
// Register a dependency on the binding context to support obsevable view models.
if (bindings && bindingContext._subscribable)
bindingContext._subscribable();
return bindings;
},
null, { disposeWhenNodeIsRemoved: node }
);
if (!bindings || !bindingsUpdater.isActive())
bindingsUpdater = null;
}
var bindingHandlerThatControlsDescendantBindings;
if (bindings) {
// Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
// context update), just return the value accessor from the binding. Otherwise, return a function that always gets
// the latest binding value and registers a dependency on the binding updater.
var getValueAccessor = bindingsUpdater
? function (bindingKey) {
return function () {
return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
};
} : function (bindingKey) {
return bindings[bindingKey];
};
// Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
function allBindings() {
return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
}
// The following is the 3.x allBindings API
allBindings['get'] = function (key) {
return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
};
allBindings['has'] = function (key) {
return key in bindings;
};
// First put the bindings into the right order
var orderedBindings = topologicalSortBindings(bindings);
// Go through the sorted bindings, calling init and update for each
ko.utils.arrayForEach(orderedBindings, function (bindingKeyAndHandler) {
// Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
// so bindingKeyAndHandler.handler will always be nonnull.
var handlerInitFn = bindingKeyAndHandler.handler["init"],
handlerUpdateFn = bindingKeyAndHandler.handler["update"],
bindingKey = bindingKeyAndHandler.key;
if (node.nodeType === 8) {
validateThatBindingIsAllowedForVirtualElements(bindingKey);
}
try {
// Run init, ignoring any dependencies
if (typeof handlerInitFn == "function") {
ko.dependencyDetection.ignore(function () {
var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
// If this binding handler claims to control descendant bindings, make a note of this
if (initResult && initResult['controlsDescendantBindings']) {
if (bindingHandlerThatControlsDescendantBindings !== undefined)
throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
bindingHandlerThatControlsDescendantBindings = bindingKey;
}
});
}
// Run update in its own computed wrapper
if (typeof handlerUpdateFn == "function") {
ko.dependentObservable(
function () {
handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
},
null,
{ disposeWhenNodeIsRemoved: node }
);
}
} catch (ex) {
ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
throw ex;
}
});
}
return {
'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
};
};
var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
ko.storedBindingContextForNode = function (node, bindingContext) {
if (arguments.length == 2) {
ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
if (bindingContext._subscribable)
bindingContext._subscribable._addNode(node);
} else {
return ko.utils.domData.get(node, storedBindingContextDomDataKey);
}
}
function getBindingContext(viewModelOrBindingContext) {
return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
? viewModelOrBindingContext
: new ko.bindingContext(viewModelOrBindingContext);
}
ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(node);
return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
};
ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
var context = getBindingContext(viewModelOrBindingContext);
return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
};
ko.applyBindingsToDescendants = function (viewModelOrBindingContext, rootNode) {
if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
};
ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
// If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
if (!jQueryInstance && window['jQuery']) {
jQueryInstance = window['jQuery'];
}
if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
};
// Retrieving binding context from arbitrary nodes
ko.contextFor = function (node) {
// We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
switch (node.nodeType) {
case 1:
case 8:
var context = ko.storedBindingContextForNode(node);
if (context) return context;
if (node.parentNode) return ko.contextFor(node.parentNode);
break;
}
return undefined;
};
ko.dataFor = function (node) {
var context = ko.contextFor(node);
return context ? context['$data'] : undefined;
};
ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
ko.exportSymbol('applyBindings', ko.applyBindings);
ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
ko.exportSymbol('contextFor', ko.contextFor);
ko.exportSymbol('dataFor', ko.dataFor);
})();
(function (undefined) {
var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight
loadedDefinitionsCache = {}; // Tracks component loads that have already completed
ko.components = {
get: function (componentName, callback) {
var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);
if (cachedDefinition) {
// It's already loaded and cached. Reuse the same definition object.
// Note that for API consistency, even cache hits complete asynchronously by default.
// You can bypass this by putting synchronous:true on your component config.
if (cachedDefinition.isSynchronousComponent) {
ko.dependencyDetection.ignore(function () { // See comment in loaderRegistryBehaviors.js for reasoning
callback(cachedDefinition.definition);
});
} else {
setTimeout(function () { callback(cachedDefinition.definition); }, 0);
}
} else {
// Join the loading process that is already underway, or start a new one.
loadComponentAndNotify(componentName, callback);
}
},
clearCachedDefinition: function (componentName) {
delete loadedDefinitionsCache[componentName];
},
_getFirstResultFromLoaders: getFirstResultFromLoaders
};
function getObjectOwnProperty(obj, propName) {
return obj.hasOwnProperty(propName) ? obj[propName] : undefined;
}
function loadComponentAndNotify(componentName, callback) {
var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
completedAsync;
if (!subscribable) {
// It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
subscribable.subscribe(callback);
beginLoadingComponent(componentName, function (definition, config) {
var isSynchronousComponent = !!(config && config['synchronous']);
loadedDefinitionsCache[componentName] = { definition: definition, isSynchronousComponent: isSynchronousComponent };
delete loadingSubscribablesCache[componentName];
// For API consistency, all loads complete asynchronously. However we want to avoid
// adding an extra setTimeout if it's unnecessary (i.e., the completion is already
// async) since setTimeout(..., 0) still takes about 16ms or more on most browsers.
//
// You can bypass the 'always synchronous' feature by putting the synchronous:true
// flag on your component configuration when you register it.
if (completedAsync || isSynchronousComponent) {
// Note that notifySubscribers ignores any dependencies read within the callback.
// See comment in loaderRegistryBehaviors.js for reasoning
subscribable['notifySubscribers'](definition);
} else {
setTimeout(function () {
subscribable['notifySubscribers'](definition);
}, 0);
}
});
completedAsync = true;
} else {
subscribable.subscribe(callback);
}
}
function beginLoadingComponent(componentName, callback) {
getFirstResultFromLoaders('getConfig', [componentName], function (config) {
if (config) {
// We have a config, so now load its definition
getFirstResultFromLoaders('loadComponent', [componentName, config], function (definition) {
callback(definition, config);
});
} else {
// The component has no config - it's unknown to all the loaders.
// Note that this is not an error (e.g., a module loading error) - that would abort the
// process and this callback would not run. For this callback to run, all loaders must
// have confirmed they don't know about this component.
callback(null, null);
}
});
}
function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
// On the first call in the stack, start with the full set of loaders
if (!candidateLoaders) {
candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array
}
// Try the next candidate
var currentCandidateLoader = candidateLoaders.shift();
if (currentCandidateLoader) {
var methodInstance = currentCandidateLoader[methodName];
if (methodInstance) {
var wasAborted = false,
synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function (result) {
if (wasAborted) {
callback(null);
} else if (result !== null) {
// This candidate returned a value. Use it.
callback(result);
} else {
// Try the next candidate
getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
}
}));
// Currently, loaders may not return anything synchronously. This leaves open the possibility
// that we'll extend the API to support synchronous return values in the future. It won't be
// a breaking change, because currently no loader is allowed to return anything except undefined.
if (synchronousReturnValue !== undefined) {
wasAborted = true;
// Method to suppress exceptions will remain undocumented. This is only to keep
// KO's specs running tidily, since we can observe the loading got aborted without
// having exceptions cluttering up the console too.
if (!currentCandidateLoader['suppressLoaderExceptions']) {
throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');
}
}
} else {
// This candidate doesn't have the relevant handler. Synchronously move on to the next one.
getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
}
} else {
// No candidates returned a value
callback(null);
}
}
// Reference the loaders via string name so it's possible for developers
// to replace the whole array by assigning to ko.components.loaders
ko.components['loaders'] = [];
ko.exportSymbol('components', ko.components);
ko.exportSymbol('components.get', ko.components.get);
ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);
})();
(function (undefined) {
// The default loader is responsible for two things:
// 1. Maintaining the default in-memory registry of component configuration objects
// (i.e., the thing you're writing to when you call ko.components.register(someName, ...))
// 2. Answering requests for components by fetching configuration objects
// from that default in-memory registry and resolving them into standard
// component definition objects (of the form { createViewModel: ..., template: ... })
// Custom loaders may override either of these facilities, i.e.,
// 1. To supply configuration objects from some other source (e.g., conventions)
// 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.
var defaultConfigRegistry = {};
ko.components.register = function (componentName, config) {
if (!config) {
throw new Error('Invalid configuration for ' + componentName);
}
if (ko.components.isRegistered(componentName)) {
throw new Error('Component ' + componentName + ' is already registered');
}
defaultConfigRegistry[componentName] = config;
}
ko.components.isRegistered = function (componentName) {
return componentName in defaultConfigRegistry;
}
ko.components.unregister = function (componentName) {
delete defaultConfigRegistry[componentName];
ko.components.clearCachedDefinition(componentName);
}
ko.components.defaultLoader = {
'getConfig': function (componentName, callback) {
var result = defaultConfigRegistry.hasOwnProperty(componentName)
? defaultConfigRegistry[componentName]
: null;
callback(result);
},
'loadComponent': function (componentName, config, callback) {
var errorCallback = makeErrorCallback(componentName);
possiblyGetConfigFromAmd(errorCallback, config, function (loadedConfig) {
resolveConfig(componentName, errorCallback, loadedConfig, callback);
});
},
'loadTemplate': function (componentName, templateConfig, callback) {
resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);
},
'loadViewModel': function (componentName, viewModelConfig, callback) {
resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);
}
};
var createViewModelKey = 'createViewModel';
// Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it
// into the standard component definition format:
// { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.
// Since both template and viewModel may need to be resolved asynchronously, both tasks are performed
// in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,
// so this is implemented manually below.
function resolveConfig(componentName, errorCallback, config, callback) {
var result = {},
makeCallBackWhenZero = 2,
tryIssueCallback = function () {
if (--makeCallBackWhenZero === 0) {
callback(result);
}
},
templateConfig = config['template'],
viewModelConfig = config['viewModel'];
if (templateConfig) {
possiblyGetConfigFromAmd(errorCallback, templateConfig, function (loadedConfig) {
ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function (resolvedTemplate) {
result['template'] = resolvedTemplate;
tryIssueCallback();
});
});
} else {
tryIssueCallback();
}
if (viewModelConfig) {
possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function (loadedConfig) {
ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function (resolvedViewModel) {
result[createViewModelKey] = resolvedViewModel;
tryIssueCallback();
});
});
} else {
tryIssueCallback();
}
}
function resolveTemplate(errorCallback, templateConfig, callback) {
if (typeof templateConfig === 'string') {
// Markup - parse it
callback(ko.utils.parseHtmlFragment(templateConfig));
} else if (templateConfig instanceof Array) {
// Assume already an array of DOM nodes - pass through unchanged
callback(templateConfig);
} else if (isDocumentFragment(templateConfig)) {
// Document fragment - use its child nodes
callback(ko.utils.makeArray(templateConfig.childNodes));
} else if (templateConfig['element']) {
var element = templateConfig['element'];
if (isDomElement(element)) {
// Element instance - copy its child nodes
callback(cloneNodesFromTemplateSourceElement(element));
} else if (typeof element === 'string') {
// Element ID - find it, then copy its child nodes
var elemInstance = document.getElementById(element);
if (elemInstance) {
callback(cloneNodesFromTemplateSourceElement(elemInstance));
} else {
errorCallback('Cannot find element with ID ' + element);
}
} else {
errorCallback('Unknown element type: ' + element);
}
} else {
errorCallback('Unknown template value: ' + templateConfig);
}
}
function resolveViewModel(errorCallback, viewModelConfig, callback) {
if (typeof viewModelConfig === 'function') {
// Constructor - convert to standard factory function format
// By design, this does *not* supply componentInfo to the constructor, as the intent is that
// componentInfo contains non-viewmodel data (e.g., the component's element) that should only
// be used in factory functions, not viewmodel constructors.
callback(function (params /*, componentInfo */) {
return new viewModelConfig(params);
});
} else if (typeof viewModelConfig[createViewModelKey] === 'function') {
// Already a factory function - use it as-is
callback(viewModelConfig[createViewModelKey]);
} else if ('instance' in viewModelConfig) {
// Fixed object instance - promote to createViewModel format for API consistency
var fixedInstance = viewModelConfig['instance'];
callback(function (params, componentInfo) {
return fixedInstance;
});
} else if ('viewModel' in viewModelConfig) {
// Resolved AMD module whose value is of the form { viewModel: ... }
resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);
} else {
errorCallback('Unknown viewModel value: ' + viewModelConfig);
}
}
function cloneNodesFromTemplateSourceElement(elemInstance) {
switch (ko.utils.tagNameLower(elemInstance)) {
case 'script':
return ko.utils.parseHtmlFragment(elemInstance.text);
case 'textarea':
return ko.utils.parseHtmlFragment(elemInstance.value);
case 'template':
// For browsers with proper <template> element support (i.e., where the .content property
// gives a document fragment), use that document fragment.
if (isDocumentFragment(elemInstance.content)) {
return ko.utils.cloneNodes(elemInstance.content.childNodes);
}
}
// Regular elements such as <div>, and <template> elements on old browsers that don't really
// understand <template> and just treat it as a regular container
return ko.utils.cloneNodes(elemInstance.childNodes);
}
function isDomElement(obj) {
if (window['HTMLElement']) {
return obj instanceof HTMLElement;
} else {
return obj && obj.tagName && obj.nodeType === 1;
}
}
function isDocumentFragment(obj) {
if (window['DocumentFragment']) {
return obj instanceof DocumentFragment;
} else {
return obj && obj.nodeType === 11;
}
}
function possiblyGetConfigFromAmd(errorCallback, config, callback) {
if (typeof config['require'] === 'string') {
// The config is the value of an AMD module
if (amdRequire || window['require']) {
(amdRequire || window['require'])([config['require']], callback);
} else {
errorCallback('Uses require, but no AMD loader is present');
}
} else {
callback(config);
}
}
function makeErrorCallback(componentName) {
return function (message) {
throw new Error('Component \'' + componentName + '\': ' + message);
};
}
ko.exportSymbol('components.register', ko.components.register);
ko.exportSymbol('components.isRegistered', ko.components.isRegistered);
ko.exportSymbol('components.unregister', ko.components.unregister);
// Expose the default loader so that developers can directly ask it for configuration
// or to resolve configuration
ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);
// By default, the default loader is the only registered component loader
ko.components['loaders'].push(ko.components.defaultLoader);
// Privately expose the underlying config registry for use in old-IE shim
ko.components._allRegisteredComponents = defaultConfigRegistry;
})();
(function (undefined) {
// Overridable API for determining which component name applies to a given node. By overriding this,
// you can for example map specific tagNames to components that are not preregistered.
ko.components['getComponentNameForNode'] = function (node) {
var tagNameLower = ko.utils.tagNameLower(node);
return ko.components.isRegistered(tagNameLower) && tagNameLower;
};
ko.components.addBindingsForCustomElement = function (allBindings, node, bindingContext, valueAccessors) {
// Determine if it's really a custom element matching a component
if (node.nodeType === 1) {
var componentName = ko.components['getComponentNameForNode'](node);
if (componentName) {
// It does represent a component, so add a component binding for it
allBindings = allBindings || {};
if (allBindings['component']) {
// Avoid silently overwriting some other 'component' binding that may already be on the element
throw new Error('Cannot use the "component" binding on a custom element matching a component');
}
var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };
allBindings['component'] = valueAccessors
? function () { return componentBindingValue; }
: componentBindingValue;
}
}
return allBindings;
}
var nativeBindingProviderInstance = new ko.bindingProvider();
function getComponentParamsFromCustomElement(elem, bindingContext) {
var paramsAttribute = elem.getAttribute('params');
if (paramsAttribute) {
var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),
rawParamComputedValues = ko.utils.objectMap(params, function (paramValue, paramName) {
return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });
}),
result = ko.utils.objectMap(rawParamComputedValues, function (paramValueComputed, paramName) {
var paramValue = paramValueComputed.peek();
// Does the evaluation of the parameter value unwrap any observables?
if (!paramValueComputed.isActive()) {
// No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.
// Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed)
return paramValue;
} else {
// Yes it does. Supply a computed property that unwraps both the outer (binding expression)
// level of observability, and any inner (resulting model value) level of observability.
// This means the component doesn't have to worry about multiple unwrapping. If the value is a
// writable observable, the computed will also be writable and pass the value on to the observable.
return ko.computed({
'read': function () {
return ko.utils.unwrapObservable(paramValueComputed());
},
'write': ko.isWriteableObservable(paramValue) && function (value) {
paramValueComputed()(value);
},
disposeWhenNodeIsRemoved: elem
});
}
});
// Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'
// This is in case the developer wants to react to outer (binding) observability separately from inner
// (model value) observability, or in case the model value observable has subobservables.
if (!result.hasOwnProperty('$raw')) {
result['$raw'] = rawParamComputedValues;
}
return result;
} else {
// For consistency, absence of a "params" attribute is treated the same as the presence of
// any empty one. Otherwise component viewmodels need special code to check whether or not
// 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.
return { '$raw': {} };
}
}
// --------------------------------------------------------------------------------
// Compatibility code for older (pre-HTML5) IE browsers
if (ko.utils.ieVersion < 9) {
// Whenever you preregister a component, enable it as a custom element in the current document
ko.components['register'] = (function (originalFunction) {
return function (componentName) {
document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element
return originalFunction.apply(this, arguments);
}
})(ko.components['register']);
// Whenever you create a document fragment, enable all preregistered component names as custom elements
// This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements
document.createDocumentFragment = (function (originalFunction) {
return function () {
var newDocFrag = originalFunction(),
allComponents = ko.components._allRegisteredComponents;
for (var componentName in allComponents) {
if (allComponents.hasOwnProperty(componentName)) {
newDocFrag.createElement(componentName);
}
}
return newDocFrag;
};
})(document.createDocumentFragment);
}
})(); (function (undefined) {
var componentLoadingOperationUniqueId = 0;
ko.bindingHandlers['component'] = {
'init': function (element, valueAccessor, ignored1, ignored2, bindingContext) {
var currentViewModel,
currentLoadingOperationId,
disposeAssociatedComponentViewModel = function () {
var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];
if (typeof currentViewModelDispose === 'function') {
currentViewModelDispose.call(currentViewModel);
}
// Any in-flight loading operation is no longer relevant, so make sure we ignore its completion
currentLoadingOperationId = null;
},
originalChildNodes = ko.utils.makeArray(ko.virtualElements.childNodes(element));
ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);
ko.computed(function () {
var value = ko.utils.unwrapObservable(valueAccessor()),
componentName, componentParams;
if (typeof value === 'string') {
componentName = value;
} else {
componentName = ko.utils.unwrapObservable(value['name']);
componentParams = ko.utils.unwrapObservable(value['params']);
}
if (!componentName) {
throw new Error('No component name specified');
}
var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;
ko.components.get(componentName, function (componentDefinition) {
// If this is not the current load operation for this element, ignore it.
if (currentLoadingOperationId !== loadingOperationId) {
return;
}
// Clean up previous state
disposeAssociatedComponentViewModel();
// Instantiate and bind new component. Implicitly this cleans any old DOM nodes.
if (!componentDefinition) {
throw new Error('Unknown component \'' + componentName + '\'');
}
cloneTemplateIntoElement(componentName, componentDefinition, element);
var componentViewModel = createViewModel(componentDefinition, element, originalChildNodes, componentParams),
childBindingContext = bindingContext['createChildContext'](componentViewModel, /* dataItemAlias */ undefined, function (ctx) {
ctx['$component'] = componentViewModel;
ctx['$componentTemplateNodes'] = originalChildNodes;
});
currentViewModel = componentViewModel;
ko.applyBindingsToDescendants(childBindingContext, element);
});
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
}
};
ko.virtualElements.allowedBindings['component'] = true;
function cloneTemplateIntoElement(componentName, componentDefinition, element) {
var template = componentDefinition['template'];
if (!template) {
throw new Error('Component \'' + componentName + '\' has no template');
}
var clonedNodesArray = ko.utils.cloneNodes(template);
ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);
}
function createViewModel(componentDefinition, element, originalChildNodes, componentParams) {
var componentViewModelFactory = componentDefinition['createViewModel'];
return componentViewModelFactory
? componentViewModelFactory.call(componentDefinition, componentParams, { 'element': element, 'templateNodes': originalChildNodes })
: componentParams; // Template-only component
}
})();
var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
ko.bindingHandlers['attr'] = {
'update': function (element, valueAccessor, allBindings) {
var value = ko.utils.unwrapObservable(valueAccessor()) || {};
ko.utils.objectForEach(value, function (attrName, attrValue) {
attrValue = ko.utils.unwrapObservable(attrValue);
// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
// when someProp is a "no value"-like value (strictly null, false, or undefined)
// (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
if (toRemove)
element.removeAttribute(attrName);
// In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
// HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
// but instead of figuring out the mode, we'll just set the attribute through the Javascript
// property for IE <= 8.
if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
attrName = attrHtmlToJavascriptMap[attrName];
if (toRemove)
element.removeAttribute(attrName);
else
element[attrName] = attrValue;
} else if (!toRemove) {
element.setAttribute(attrName, attrValue.toString());
}
// Treat "name" specially - although you can think of it as an attribute, it also needs
// special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
// Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
// entirely, and there's no strong reason to allow for such casing in HTML.
if (attrName === "name") {
ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
}
});
}
};
(function () {
ko.bindingHandlers['checked'] = {
'after': ['value', 'attr'],
'init': function (element, valueAccessor, allBindings) {
var checkedValue = ko.pureComputed(function () {
// Treat "value" like "checkedValue" when it is included with "checked" binding
if (allBindings['has']('checkedValue')) {
return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
} else if (allBindings['has']('value')) {
return ko.utils.unwrapObservable(allBindings.get('value'));
}
return element.value;
});
function updateModel() {
// This updates the model value from the view value.
// It runs in response to DOM events (click) and changes in checkedValue.
var isChecked = element.checked,
elemValue = useCheckedValue ? checkedValue() : isChecked;
// When we're first setting up this computed, don't change any model state.
if (ko.computedContext.isInitial()) {
return;
}
// We can ignore unchecked radio buttons, because some other radio
// button will be getting checked, and that one can take care of updating state.
if (isRadio && !isChecked) {
return;
}
var modelValue = ko.dependencyDetection.ignore(valueAccessor);
if (isValueArray) {
if (oldElemValue !== elemValue) {
// When we're responding to the checkedValue changing, and the element is
// currently checked, replace the old elem value with the new elem value
// in the model array.
if (isChecked) {
ko.utils.addOrRemoveItem(modelValue, elemValue, true);
ko.utils.addOrRemoveItem(modelValue, oldElemValue, false);
}
oldElemValue = elemValue;
} else {
// When we're responding to the user having checked/unchecked a checkbox,
// add/remove the element value to the model array.
ko.utils.addOrRemoveItem(modelValue, elemValue, isChecked);
}
} else {
ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
}
};
function updateView() {
// This updates the view value from the model value.
// It runs in response to changes in the bound (checked) value.
var modelValue = ko.utils.unwrapObservable(valueAccessor());
if (isValueArray) {
// When a checkbox is bound to an array, being checked represents its value being present in that array
element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
} else if (isCheckbox) {
// When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
element.checked = modelValue;
} else {
// For radio buttons, being checked means that the radio button's value corresponds to the model value
element.checked = (checkedValue() === modelValue);
}
};
var isCheckbox = element.type == "checkbox",
isRadio = element.type == "radio";
// Only bind to check boxes and radio buttons
if (!isCheckbox && !isRadio) {
return;
}
var isValueArray = isCheckbox && (ko.utils.unwrapObservable(valueAccessor()) instanceof Array),
oldElemValue = isValueArray ? checkedValue() : undefined,
useCheckedValue = isRadio || isValueArray;
// IE 6 won't allow radio buttons to be selected unless they have a name
if (isRadio && !element.name)
ko.bindingHandlers['uniqueName']['init'](element, function () { return true });
// Set up two computeds to update the binding:
// The first responds to changes in the checkedValue value and to element clicks
ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
ko.utils.registerEventHandler(element, "click", updateModel);
// The second responds to changes in the model value (the one associated with the checked binding)
ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
}
};
ko.expressionRewriting.twoWayBindings['checked'] = true;
ko.bindingHandlers['checkedValue'] = {
'update': function (element, valueAccessor) {
element.value = ko.utils.unwrapObservable(valueAccessor());
}
};
})(); var classesWrittenByBindingKey = '__ko__cssValue';
ko.bindingHandlers['css'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value !== null && typeof value == "object") {
ko.utils.objectForEach(value, function (className, shouldHaveClass) {
shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
});
} else {
value = String(value || ''); // Make sure we don't try to store or set a non-string value
ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
element[classesWrittenByBindingKey] = value;
ko.utils.toggleDomNodeCssClass(element, value, true);
}
}
};
ko.bindingHandlers['enable'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value && element.disabled)
element.removeAttribute("disabled");
else if ((!value) && (!element.disabled))
element.disabled = true;
}
};
ko.bindingHandlers['disable'] = {
'update': function (element, valueAccessor) {
ko.bindingHandlers['enable']['update'](element, function () { return !ko.utils.unwrapObservable(valueAccessor()) });
}
};
// For certain common events (currently just 'click'), allow a simplified data-binding syntax
// e.g. click:handler instead of the usual full-length event:{click:handler}
function makeEventHandlerShortcut(eventName) {
ko.bindingHandlers[eventName] = {
'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var newValueAccessor = function () {
var result = {};
result[eventName] = valueAccessor();
return result;
};
return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
}
}
}
ko.bindingHandlers['event'] = {
'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var eventsToHandle = valueAccessor() || {};
ko.utils.objectForEach(eventsToHandle, function (eventName) {
if (typeof eventName == "string") {
ko.utils.registerEventHandler(element, eventName, function (event) {
var handlerReturnValue;
var handlerFunction = valueAccessor()[eventName];
if (!handlerFunction)
return;
try {
// Take all the event args, and prefix with the viewmodel
var argsForHandler = ko.utils.makeArray(arguments);
viewModel = bindingContext['$data'];
argsForHandler.unshift(viewModel);
handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
} finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
var bubble = allBindings.get(eventName + 'Bubble') !== false;
if (!bubble) {
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
}
});
}
});
}
};
// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
ko.bindingHandlers['foreach'] = {
makeTemplateValueAccessor: function (valueAccessor) {
return function () {
var modelValue = valueAccessor(),
unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
// If unwrappedValue is the array, pass in the wrapped value on its own
// The value will be unwrapped and tracked within the template binding
// (See https://github.com/SteveSanderson/knockout/issues/523)
if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
// If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
ko.utils.unwrapObservable(modelValue);
return {
'foreach': unwrappedValue['data'],
'as': unwrappedValue['as'],
'includeDestroyed': unwrappedValue['includeDestroyed'],
'afterAdd': unwrappedValue['afterAdd'],
'beforeRemove': unwrappedValue['beforeRemove'],
'afterRender': unwrappedValue['afterRender'],
'beforeMove': unwrappedValue['beforeMove'],
'afterMove': unwrappedValue['afterMove'],
'templateEngine': ko.nativeTemplateEngine.instance
};
};
},
'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
},
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
}
};
ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings['foreach'] = true;
var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
var hasfocusLastValue = '__ko_hasfocusLastValue';
ko.bindingHandlers['hasfocus'] = {
'init': function (element, valueAccessor, allBindings) {
var handleElementFocusChange = function (isFocused) {
// Where possible, ignore which event was raised and determine focus state using activeElement,
// as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
// However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
// prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
// from calling 'blur()' on the element when it loses focus.
// Discussion at https://github.com/SteveSanderson/knockout/pull/352
element[hasfocusUpdatingProperty] = true;
var ownerDoc = element.ownerDocument;
if ("activeElement" in ownerDoc) {
var active;
try {
active = ownerDoc.activeElement;
} catch (e) {
// IE9 throws if you access activeElement during page load (see issue #703)
active = ownerDoc.body;
}
isFocused = (active === element);
}
var modelValue = valueAccessor();
ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
//cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
element[hasfocusLastValue] = isFocused;
element[hasfocusUpdatingProperty] = false;
};
var handleElementFocusIn = handleElementFocusChange.bind(null, true);
var handleElementFocusOut = handleElementFocusChange.bind(null, false);
ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
},
'update': function (element, valueAccessor) {
var value = !!ko.utils.unwrapObservable(valueAccessor()); //force boolean to compare with last value
if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
value ? element.focus() : element.blur();
ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
}
}
};
ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
ko.bindingHandlers['html'] = {
'init': function () {
// Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor) {
// setHtml will unwrap the value if needed
ko.utils.setHtml(element, valueAccessor());
}
};
// Makes a binding like with or if
function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
ko.bindingHandlers[bindingKey] = {
'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var didDisplayOnLastUpdate,
savedNodes;
ko.computed(function () {
var dataValue = ko.utils.unwrapObservable(valueAccessor()),
shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
isFirstRender = !savedNodes,
needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
if (needsRefresh) {
// Save a copy of the inner nodes on the initial update, but only if we have dependencies.
if (isFirstRender && ko.computedContext.getDependenciesCount()) {
savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
}
if (shouldDisplay) {
if (!isFirstRender) {
ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
}
ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
} else {
ko.virtualElements.emptyNode(element);
}
didDisplayOnLastUpdate = shouldDisplay;
}
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
}
};
ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings[bindingKey] = true;
}
// Construct the actual binding handlers
makeWithIfBinding('if');
makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
makeWithIfBinding('with', true /* isWith */, false /* isNot */,
function (bindingContext, dataValue) {
return bindingContext['createChildContext'](dataValue);
}
);
var captionPlaceholder = {};
ko.bindingHandlers['options'] = {
'init': function (element) {
if (ko.utils.tagNameLower(element) !== "select")
throw new Error("options binding applies only to SELECT elements");
// Remove all existing <option>s.
while (element.length > 0) {
element.remove(0);
}
// Ensures that the binding processor doesn't try to bind the options
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings) {
function selectedOptions() {
return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
}
var selectWasPreviouslyEmpty = element.length == 0,
multiple = element.multiple,
previousScrollTop = (!selectWasPreviouslyEmpty && multiple) ? element.scrollTop : null,
unwrappedArray = ko.utils.unwrapObservable(valueAccessor()),
valueAllowUnset = allBindings.get('valueAllowUnset') && allBindings['has']('value'),
includeDestroyed = allBindings.get('optionsIncludeDestroyed'),
arrayToDomNodeChildrenOptions = {},
captionValue,
filteredArray,
previousSelectedValues = [];
if (!valueAllowUnset) {
if (multiple) {
previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
} else if (element.selectedIndex >= 0) {
previousSelectedValues.push(ko.selectExtensions.readValue(element.options[element.selectedIndex]));
}
}
if (unwrappedArray) {
if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
unwrappedArray = [unwrappedArray];
// Filter out any entries marked as destroyed
filteredArray = ko.utils.arrayFilter(unwrappedArray, function (item) {
return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
});
// If caption is included, add it to the array
if (allBindings['has']('optionsCaption')) {
captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
// If caption value is null or undefined, don't show a caption
if (captionValue !== null && captionValue !== undefined) {
filteredArray.unshift(captionPlaceholder);
}
}
} else {
// If a falsy value is provided (e.g. null), we'll simply empty the select element
}
function applyToObject(object, predicate, defaultValue) {
var predicateType = typeof predicate;
if (predicateType == "function") // Given a function; run it against the data value
return predicate(object);
else if (predicateType == "string") // Given a string; treat it as a property name on the data value
return object[predicate];
else // Given no optionsText arg; use the data value itself
return defaultValue;
}
// The following functions can run at two different times:
// The first is when the whole array is being updated directly from this binding handler.
// The second is when an observable value for a specific array entry is updated.
// oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
var itemUpdate = false;
function optionForArrayItem(arrayEntry, index, oldOptions) {
if (oldOptions.length) {
previousSelectedValues = !valueAllowUnset && oldOptions[0].selected ? [ko.selectExtensions.readValue(oldOptions[0])] : [];
itemUpdate = true;
}
var option = element.ownerDocument.createElement("option");
if (arrayEntry === captionPlaceholder) {
ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
ko.selectExtensions.writeValue(option, undefined);
} else {
// Apply a value to the option element
var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
// Apply some text to the option element
var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
ko.utils.setTextContent(option, optionText);
}
return [option];
}
// By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
// problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
arrayToDomNodeChildrenOptions['beforeRemove'] =
function (option) {
element.removeChild(option);
};
function setSelectionCallback(arrayEntry, newOptions) {
if (itemUpdate && valueAllowUnset) {
// The model value is authoritative, so make sure its value is the one selected
// There is no need to use dependencyDetection.ignore since setDomNodeChildrenFromArrayMapping does so already.
ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
} else if (previousSelectedValues.length) {
// IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
// That's why we first added them without selection. Now it's time to set the selection.
var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
// If this option was changed from being selected during a single-item update, notify the change
if (itemUpdate && !isSelected) {
ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
}
}
}
var callback = setSelectionCallback;
if (allBindings['has']('optionsAfterRender') && typeof allBindings.get('optionsAfterRender') == "function") {
callback = function (arrayEntry, newOptions) {
setSelectionCallback(arrayEntry, newOptions);
ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
}
}
ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
ko.dependencyDetection.ignore(function () {
if (valueAllowUnset) {
// The model value is authoritative, so make sure its value is the one selected
ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
} else {
// Determine if the selection has changed as a result of updating the options list
var selectionChanged;
if (multiple) {
// For a multiple-select box, compare the new selection count to the previous one
// But if nothing was selected before, the selection can't have changed
selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
} else {
// For a single-select box, compare the current value to the previous value
// But if nothing was selected before or nothing is selected now, just look for a change in selection
selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
: (previousSelectedValues.length || element.selectedIndex >= 0);
}
// Ensure consistency between model value and selected option.
// If the dropdown was changed so that selection is no longer the same,
// notify the value or selectedOptions binding.
if (selectionChanged) {
ko.utils.triggerEvent(element, "change");
}
}
});
// Workaround for IE bug
ko.utils.ensureSelectElementIsRenderedCorrectly(element);
if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
element.scrollTop = previousScrollTop;
}
};
ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
ko.bindingHandlers['selectedOptions'] = {
'after': ['options', 'foreach'],
'init': function (element, valueAccessor, allBindings) {
ko.utils.registerEventHandler(element, "change", function () {
var value = valueAccessor(), valueToWrite = [];
ko.utils.arrayForEach(element.getElementsByTagName("option"), function (node) {
if (node.selected)
valueToWrite.push(ko.selectExtensions.readValue(node));
});
ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
});
},
'update': function (element, valueAccessor) {
if (ko.utils.tagNameLower(element) != "select")
throw new Error("values binding applies only to SELECT elements");
var newValue = ko.utils.unwrapObservable(valueAccessor());
if (newValue && typeof newValue.length == "number") {
ko.utils.arrayForEach(element.getElementsByTagName("option"), function (node) {
var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
ko.utils.setOptionNodeSelectionState(node, isSelected);
});
}
}
};
ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
ko.bindingHandlers['style'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
ko.utils.objectForEach(value, function (styleName, styleValue) {
styleValue = ko.utils.unwrapObservable(styleValue);
if (styleValue === null || styleValue === undefined || styleValue === false) {
// Empty string removes the value, whereas null/undefined have no effect
styleValue = "";
}
element.style[styleName] = styleValue;
});
}
};
ko.bindingHandlers['submit'] = {
'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
if (typeof valueAccessor() != "function")
throw new Error("The value for a submit binding must be a function");
ko.utils.registerEventHandler(element, "submit", function (event) {
var handlerReturnValue;
var value = valueAccessor();
try { handlerReturnValue = value.call(bindingContext['$data'], element); }
finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
});
}
};
ko.bindingHandlers['text'] = {
'init': function () {
// Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
// It should also make things faster, as we no longer have to consider whether the text node might be bindable.
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor) {
ko.utils.setTextContent(element, valueAccessor());
}
};
ko.virtualElements.allowedBindings['text'] = true;
(function () {
if (window && window.navigator) {
var parseVersion = function (matches) {
if (matches) {
return parseFloat(matches[1]);
}
};
// Detect various browser versions because some old versions don't fully support the 'input' event
var operaVersion = window.opera && window.opera.version && parseInt(window.opera.version()),
userAgent = window.navigator.userAgent,
safariVersion = parseVersion(userAgent.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),
firefoxVersion = parseVersion(userAgent.match(/Firefox\/([^ ]*)/));
}
// IE 8 and 9 have bugs that prevent the normal events from firing when the value changes.
// But it does fire the 'selectionchange' event on many of those, presumably because the
// cursor is moving and that counts as the selection changing. The 'selectionchange' event is
// fired at the document level only and doesn't directly indicate which element changed. We
// set up just one event handler for the document and use 'activeElement' to determine which
// element was changed.
if (ko.utils.ieVersion < 10) {
var selectionChangeRegisteredName = ko.utils.domData.nextKey(),
selectionChangeHandlerName = ko.utils.domData.nextKey();
var selectionChangeHandler = function (event) {
var target = this.activeElement,
handler = target && ko.utils.domData.get(target, selectionChangeHandlerName);
if (handler) {
handler(event);
}
};
var registerForSelectionChangeEvent = function (element, handler) {
var ownerDoc = element.ownerDocument;
if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) {
ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true);
ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler);
}
ko.utils.domData.set(element, selectionChangeHandlerName, handler);
};
}
ko.bindingHandlers['textInput'] = {
'init': function (element, valueAccessor, allBindings) {
var previousElementValue = element.value,
timeoutHandle,
elementValueBeforeEvent;
var updateModel = function (event) {
clearTimeout(timeoutHandle);
elementValueBeforeEvent = timeoutHandle = undefined;
var elementValue = element.value;
if (previousElementValue !== elementValue) {
// Provide a way for tests to know exactly which event was processed
if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type;
previousElementValue = elementValue;
ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue);
}
};
var deferUpdateModel = function (event) {
if (!timeoutHandle) {
// The elementValueBeforeEvent variable is set *only* during the brief gap between an
// event firing and the updateModel function running. This allows us to ignore model
// updates that are from the previous state of the element, usually due to techniques
// such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost.
elementValueBeforeEvent = element.value;
var handler = DEBUG ? updateModel.bind(element, { type: event.type }) : updateModel;
timeoutHandle = setTimeout(handler, 4);
}
};
var updateView = function () {
var modelValue = ko.utils.unwrapObservable(valueAccessor());
if (modelValue === null || modelValue === undefined) {
modelValue = '';
}
if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) {
setTimeout(updateView, 4);
return;
}
// Update the element only if the element and model are different. On some browsers, updating the value
// will move the cursor to the end of the input, which would be bad while the user is typing.
if (element.value !== modelValue) {
previousElementValue = modelValue; // Make sure we ignore events (propertychange) that result from updating the value
element.value = modelValue;
}
};
var onEvent = function (event, handler) {
ko.utils.registerEventHandler(element, event, handler);
};
if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) {
// Provide a way for tests to specify exactly which events are bound
ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function (eventName) {
if (eventName.slice(0, 5) == 'after') {
onEvent(eventName.slice(5), deferUpdateModel);
} else {
onEvent(eventName, updateModel);
}
});
} else {
if (ko.utils.ieVersion < 10) {
// Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever
// any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code,
// but that's an acceptable compromise for this binding. IE 9 does support 'input', but since it doesn't fire it
// when using autocomplete, we'll use 'propertychange' for it also.
onEvent('propertychange', function (event) {
if (event.propertyName === 'value') {
updateModel(event);
}
});
if (ko.utils.ieVersion == 8) {
// IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from
// JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following
// events too.
onEvent('keyup', updateModel); // A single keystoke
onEvent('keydown', updateModel); // The first character when a key is held down
}
if (ko.utils.ieVersion >= 8) {
// Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using
// the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text
// out of the field, and cutting or deleting text using the context menu. 'selectionchange'
// can detect all of those except dragging text out of the field, for which we use 'dragend'.
// These are also needed in IE8 because of the bug described above.
registerForSelectionChangeEvent(element, updateModel); // 'selectionchange' covers cut, paste, drop, delete, etc.
onEvent('dragend', deferUpdateModel);
}
} else {
// All other supported browsers support the 'input' event, which fires whenever the content of the element is changed
// through the user interface.
onEvent('input', updateModel);
if (safariVersion < 5 && ko.utils.tagNameLower(element) === "textarea") {
// Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput'
// but only when typing). So we'll just catch as much as we can with keydown, cut, and paste.
onEvent('keydown', deferUpdateModel);
onEvent('paste', deferUpdateModel);
onEvent('cut', deferUpdateModel);
} else if (operaVersion < 11) {
// Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations.
// We can try to catch some of those using 'keydown'.
onEvent('keydown', deferUpdateModel);
} else if (firefoxVersion < 4.0) {
// Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete
onEvent('DOMAutoComplete', updateModel);
// Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input.
onEvent('dragdrop', updateModel); // <3.5
onEvent('drop', updateModel); // 3.5
}
}
}
// Bind to the change event so that we can catch programmatic updates of the value that fire this event.
onEvent('change', updateModel);
ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
}
};
ko.expressionRewriting.twoWayBindings['textInput'] = true;
// textinput is an alias for textInput
ko.bindingHandlers['textinput'] = {
// preprocess is the only way to set up a full alias
'preprocess': function (value, name, addBinding) {
addBinding('textInput', value);
}
};
})(); ko.bindingHandlers['uniqueName'] = {
'init': function (element, valueAccessor) {
if (valueAccessor()) {
var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
ko.utils.setElementName(element, name);
}
}
};
ko.bindingHandlers['uniqueName'].currentIndex = 0;
ko.bindingHandlers['value'] = {
'after': ['options', 'foreach'],
'init': function (element, valueAccessor, allBindings) {
// If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit
if (element.tagName.toLowerCase() == "input" && (element.type == "checkbox" || element.type == "radio")) {
ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor });
return;
}
// Always catch "change" event; possibly other events too if asked
var eventsToCatch = ["change"];
var requestedEventsToCatch = allBindings.get("valueUpdate");
var propertyChangedFired = false;
var elementValueBeforeEvent = null;
if (requestedEventsToCatch) {
if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
requestedEventsToCatch = [requestedEventsToCatch];
ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
}
var valueUpdateHandler = function () {
elementValueBeforeEvent = null;
propertyChangedFired = false;
var modelValue = valueAccessor();
var elementValue = ko.selectExtensions.readValue(element);
ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
}
// Workaround for https://github.com/SteveSanderson/knockout/issues/122
// IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
&& element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
ko.utils.registerEventHandler(element, "blur", function () {
if (propertyChangedFired) {
valueUpdateHandler();
}
});
}
ko.utils.arrayForEach(eventsToCatch, function (eventName) {
// The syntax "after<eventname>" means "run the handler asynchronously after the event"
// This is useful, for example, to catch "keydown" events after the browser has updated the control
// (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
var handler = valueUpdateHandler;
if (ko.utils.stringStartsWith(eventName, "after")) {
handler = function () {
// The elementValueBeforeEvent variable is non-null *only* during the brief gap between
// a keyX event firing and the valueUpdateHandler running, which is scheduled to happen
// at the earliest asynchronous opportunity. We store this temporary information so that
// if, between keyX and valueUpdateHandler, the underlying model value changes separately,
// we can overwrite that model value change with the value the user just typed. Otherwise,
// techniques like rateLimit can trigger model changes at critical moments that will
// override the user's inputs, causing keystrokes to be lost.
elementValueBeforeEvent = ko.selectExtensions.readValue(element);
setTimeout(valueUpdateHandler, 0);
};
eventName = eventName.substring("after".length);
}
ko.utils.registerEventHandler(element, eventName, handler);
});
var updateFromModel = function () {
var newValue = ko.utils.unwrapObservable(valueAccessor());
var elementValue = ko.selectExtensions.readValue(element);
if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) {
setTimeout(updateFromModel, 0);
return;
}
var valueHasChanged = (newValue !== elementValue);
if (valueHasChanged) {
if (ko.utils.tagNameLower(element) === "select") {
var allowUnset = allBindings.get('valueAllowUnset');
var applyValueAction = function () {
ko.selectExtensions.writeValue(element, newValue, allowUnset);
};
applyValueAction();
if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
// If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
// because you're not allowed to have a model value that disagrees with a visible UI selection.
ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
} else {
// Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
// right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
// to apply the value as well.
setTimeout(applyValueAction, 0);
}
} else {
ko.selectExtensions.writeValue(element, newValue);
}
}
};
ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
},
'update': function () { } // Keep for backwards compatibility with code that may have wrapped value binding
};
ko.expressionRewriting.twoWayBindings['value'] = true;
ko.bindingHandlers['visible'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var isCurrentlyVisible = !(element.style.display == "none");
if (value && !isCurrentlyVisible)
element.style.display = "";
else if ((!value) && isCurrentlyVisible)
element.style.display = "none";
}
};
// 'click' is just a shorthand for the usual full-length event:{click:handler}
makeEventHandlerShortcut('click');
// If you want to make a custom template engine,
//
// [1] Inherit from this class (like ko.nativeTemplateEngine does)
// [2] Override 'renderTemplateSource', supplying a function with this signature:
//
// function (templateSource, bindingContext, options) {
// // - templateSource.text() is the text of the template you should render
// // - bindingContext.$data is the data you should pass into the template
// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
// // and bindingContext.$root available in the template too
// // - options gives you access to any other properties set on "data-bind: { template: options }"
// // - templateDocument is the document object of the template
// //
// // Return value: an array of DOM nodes
// }
//
// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
//
// function (script) {
// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
// }
//
// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
ko.templateEngine = function () { };
ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
throw new Error("Override renderTemplateSource");
};
ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
throw new Error("Override createJavaScriptEvaluatorBlock");
};
ko.templateEngine.prototype['makeTemplateSource'] = function (template, templateDocument) {
// Named template
if (typeof template == "string") {
templateDocument = templateDocument || document;
var elem = templateDocument.getElementById(template);
if (!elem)
throw new Error("Cannot find template with ID " + template);
return new ko.templateSources.domElement(elem);
} else if ((template.nodeType == 1) || (template.nodeType == 8)) {
// Anonymous template
return new ko.templateSources.anonymousTemplate(template);
} else
throw new Error("Unknown template type: " + template);
};
ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
var templateSource = this['makeTemplateSource'](template, templateDocument);
return this['renderTemplateSource'](templateSource, bindingContext, options, templateDocument);
};
ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
// Skip rewriting if requested
if (this['allowTemplateRewriting'] === false)
return true;
return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
};
ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
var templateSource = this['makeTemplateSource'](template, templateDocument);
var rewritten = rewriterCallback(templateSource['text']());
templateSource['text'](rewritten);
templateSource['data']("isRewritten", true);
};
ko.exportSymbol('templateEngine', ko.templateEngine);
ko.templateRewriting = (function () {
var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
function validateDataBindValuesForRewriting(keyValueArray) {
var allValidators = ko.expressionRewriting.bindingRewriteValidators;
for (var i = 0; i < keyValueArray.length; i++) {
var key = keyValueArray[i]['key'];
if (allValidators.hasOwnProperty(key)) {
var validator = allValidators[key];
if (typeof validator === "function") {
var possibleErrorMessage = validator(keyValueArray[i]['value']);
if (possibleErrorMessage)
throw new Error(possibleErrorMessage);
} else if (!validator) {
throw new Error("This template engine does not support the '" + key + "' binding within its templates");
}
}
}
}
function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
validateDataBindValuesForRewriting(dataBindKeyValueArray);
var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, { 'valueAccessors': true });
// For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
// anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
// extra indirection.
var applyBindingsToNextSiblingScript =
"ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
}
return {
ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
if (!templateEngine['isTemplateRewritten'](template, templateDocument))
templateEngine['rewriteTemplate'](template, function (htmlString) {
return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
}, templateDocument);
},
memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
}).replace(memoizeVirtualContainerBindingSyntaxRegex, function () {
return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
});
},
applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
return ko.memoization.memoize(function (domNode, bindingContext) {
var nodeToBind = domNode.nextSibling;
if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
}
});
}
}
})();
// Exported only because it has to be referenced by string lookup from within rewritten template
ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
(function () {
// A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
// logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
//
// Two are provided by default:
// 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
// 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
// without reading/writing the actual element text content, since it will be overwritten
// with the rendered template output.
// You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
// Template sources need to have the following functions:
// text() - returns the template text from your storage location
// text(value) - writes the supplied template text to your storage location
// data(key) - reads values stored using data(key, value) - see below
// data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
//
// Optionally, template sources can also have the following functions:
// nodes() - returns a DOM element containing the nodes of this template, where available
// nodes(value) - writes the given DOM element to your storage location
// If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
// for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
//
// Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
// using and overriding "makeTemplateSource" to return an instance of your custom template source.
ko.templateSources = {};
// ---- ko.templateSources.domElement -----
ko.templateSources.domElement = function (element) {
this.domElement = element;
}
ko.templateSources.domElement.prototype['text'] = function (/* valueToWrite */) {
var tagNameLower = ko.utils.tagNameLower(this.domElement),
elemContentsProperty = tagNameLower === "script" ? "text"
: tagNameLower === "textarea" ? "value"
: "innerHTML";
if (arguments.length == 0) {
return this.domElement[elemContentsProperty];
} else {
var valueToWrite = arguments[0];
if (elemContentsProperty === "innerHTML")
ko.utils.setHtml(this.domElement, valueToWrite);
else
this.domElement[elemContentsProperty] = valueToWrite;
}
};
var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
ko.templateSources.domElement.prototype['data'] = function (key /*, valueToWrite */) {
if (arguments.length === 1) {
return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
} else {
ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
}
};
// ---- ko.templateSources.anonymousTemplate -----
// Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
// For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
// Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
var anonymousTemplatesDomDataKey = ko.utils.domData.nextKey();
ko.templateSources.anonymousTemplate = function (element) {
this.domElement = element;
}
ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
ko.templateSources.anonymousTemplate.prototype['text'] = function (/* valueToWrite */) {
if (arguments.length == 0) {
var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
if (templateData.textData === undefined && templateData.containerData)
templateData.textData = templateData.containerData.innerHTML;
return templateData.textData;
} else {
var valueToWrite = arguments[0];
ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, { textData: valueToWrite });
}
};
ko.templateSources.domElement.prototype['nodes'] = function (/* valueToWrite */) {
if (arguments.length == 0) {
var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
return templateData.containerData;
} else {
var valueToWrite = arguments[0];
ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, { containerData: valueToWrite });
}
};
ko.exportSymbol('templateSources', ko.templateSources);
ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
})();
(function () {
var _templateEngine;
ko.setTemplateEngine = function (templateEngine) {
if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
throw new Error("templateEngine must inherit from ko.templateEngine");
_templateEngine = templateEngine;
}
function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
nextInQueue = ko.virtualElements.nextSibling(node);
action(node, nextInQueue);
}
}
function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
// To be used on any nodes that have been rendered by a template and have been inserted into some parent element
// Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
// the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
// (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
// (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
if (continuousNodeArray.length) {
var firstNode = continuousNodeArray[0],
lastNode = continuousNodeArray[continuousNodeArray.length - 1],
parentNode = firstNode.parentNode,
provider = ko.bindingProvider['instance'],
preprocessNode = provider['preprocessNode'];
if (preprocessNode) {
invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node, nextNodeInRange) {
var nodePreviousSibling = node.previousSibling;
var newNodes = preprocessNode.call(provider, node);
if (newNodes) {
if (node === firstNode)
firstNode = newNodes[0] || nextNodeInRange;
if (node === lastNode)
lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
}
});
// Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
// We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
// first node needs to be in the array).
continuousNodeArray.length = 0;
if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
return;
}
if (firstNode === lastNode) {
continuousNodeArray.push(firstNode);
} else {
continuousNodeArray.push(firstNode, lastNode);
ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
}
}
// Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
// whereas a regular applyBindings won't introduce new memoized nodes
invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node) {
if (node.nodeType === 1 || node.nodeType === 8)
ko.applyBindings(bindingContext, node);
});
invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node) {
if (node.nodeType === 1 || node.nodeType === 8)
ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
});
// Make sure any changes done by applyBindings or unmemoize are reflected in the array
ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
}
}
function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
return nodeOrNodeArray.nodeType ? nodeOrNodeArray
: nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
: null;
}
function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
options = options || {};
var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
var templateDocument = (firstTargetNode || template || {}).ownerDocument;
var templateEngineToUse = (options['templateEngine'] || _templateEngine);
ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
// Loosely check result is an array of DOM nodes
if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
throw new Error("Template engine must return an array of DOM nodes");
var haveAddedNodesToParent = false;
switch (renderMode) {
case "replaceChildren":
ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
haveAddedNodesToParent = true;
break;
case "replaceNode":
ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
haveAddedNodesToParent = true;
break;
case "ignoreTargetNode": break;
default:
throw new Error("Unknown renderMode: " + renderMode);
}
if (haveAddedNodesToParent) {
activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
if (options['afterRender'])
ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
}
return renderedNodesArray;
}
function resolveTemplateName(template, data, context) {
// The template can be specified as:
if (ko.isObservable(template)) {
// 1. An observable, with string value
return template();
} else if (typeof template === 'function') {
// 2. A function of (data, context) returning a string
return template(data, context);
} else {
// 3. A string
return template;
}
}
ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
options = options || {};
if ((options['templateEngine'] || _templateEngine) == undefined)
throw new Error("Set a template engine before calling renderTemplate");
renderMode = renderMode || "replaceChildren";
if (targetNodeOrNodeArray) {
var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
function () {
// Ensure we've got a proper binding context to work with
var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
? dataOrBindingContext
: new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext),
renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
if (renderMode == "replaceNode") {
targetNodeOrNodeArray = renderedNodesArray;
firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
}
},
null,
{ disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
);
} else {
// We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
return ko.memoization.memoize(function (domNode) {
ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
});
}
};
ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
// Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
// activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
var arrayItemContext;
// This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
var executeTemplateForArrayItem = function (arrayValue, index) {
// Support selecting template as a function of the data being rendered
arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function (context) {
context['$index'] = index;
});
var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
}
// This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
var activateBindingsCallback = function (arrayValue, addedNodesArray, index) {
activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
if (options['afterRender'])
options['afterRender'](addedNodesArray, arrayValue);
// release the "cache" variable, so that it can be collected by
// the GC when its value isn't used from within the bindings anymore.
arrayItemContext = null;
};
return ko.dependentObservable(function () {
var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
unwrappedArray = [unwrappedArray];
// Filter out any entries marked as destroyed
var filteredArray = ko.utils.arrayFilter(unwrappedArray, function (item) {
return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
});
// Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
// If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
}, null, { disposeWhenNodeIsRemoved: targetNode });
};
var templateComputedDomDataKey = ko.utils.domData.nextKey();
function disposeOldComputedAndStoreNewOne(element, newComputed) {
var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
if (oldComputed && (typeof (oldComputed.dispose) == 'function'))
oldComputed.dispose();
ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
}
ko.bindingHandlers['template'] = {
'init': function (element, valueAccessor) {
// Support anonymous templates
var bindingValue = ko.utils.unwrapObservable(valueAccessor());
if (typeof bindingValue == "string" || bindingValue['name']) {
// It's a named template - clear the element
ko.virtualElements.emptyNode(element);
} else if ('nodes' in bindingValue) {
// We've been given an array of DOM nodes. Save them as the template source.
// There is no known use case for the node array being an observable array (if the output
// varies, put that behavior *into* your template - that's what templates are for), and
// the implementation would be a mess, so assert that it's not observable.
var nodes = bindingValue['nodes'] || [];
if (ko.isObservable(nodes)) {
throw new Error('The "nodes" option must be a plain, non-observable array.');
}
var container = ko.utils.moveCleanedNodesToContainerElement(nodes); // This also removes the nodes from their current parent
new ko.templateSources.anonymousTemplate(element)['nodes'](container);
} else {
// It's an anonymous template - store the element contents, then clear the element
var templateNodes = ko.virtualElements.childNodes(element),
container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
new ko.templateSources.anonymousTemplate(element)['nodes'](container);
}
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor(),
dataValue,
options = ko.utils.unwrapObservable(value),
shouldDisplay = true,
templateComputed = null,
templateName;
if (typeof options == "string") {
templateName = value;
options = {};
} else {
templateName = options['name'];
// Support "if"/"ifnot" conditions
if ('if' in options)
shouldDisplay = ko.utils.unwrapObservable(options['if']);
if (shouldDisplay && 'ifnot' in options)
shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
dataValue = ko.utils.unwrapObservable(options['data']);
}
if ('foreach' in options) {
// Render once for each data point (treating data set as empty if shouldDisplay==false)
var dataArray = (shouldDisplay && options['foreach']) || [];
templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
} else if (!shouldDisplay) {
ko.virtualElements.emptyNode(element);
} else {
// Render once for this single data point (or use the viewModel if no data was provided)
var innerBindingContext = ('data' in options) ?
bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
bindingContext; // Given no explicit 'data' value, we retain the same binding context
templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
}
// It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
disposeOldComputedAndStoreNewOne(element, templateComputed);
}
};
// Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
ko.expressionRewriting.bindingRewriteValidators['template'] = function (bindingValue) {
var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
return null; // Named templates can be rewritten, so return "no error"
return "This template engine does not support anonymous templates nested within its templates";
};
ko.virtualElements.allowedBindings['template'] = true;
})();
ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
ko.exportSymbol('renderTemplate', ko.renderTemplate);
// Go through the items that have been added and deleted and try to find matches between them.
ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
if (left.length && right.length) {
var failedCompares, l, r, leftItem, rightItem;
for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]) ; ++l) {
for (r = 0; rightItem = right[r]; ++r) {
if (leftItem['value'] === rightItem['value']) {
leftItem['moved'] = rightItem['index'];
rightItem['moved'] = leftItem['index'];
right.splice(r, 1); // This item is marked as moved; so remove it from right list
failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
break;
}
}
failedCompares += r;
}
}
};
ko.utils.compareArrays = (function () {
var statusNotInOld = 'added', statusNotInNew = 'deleted';
// Simple calculation based on Levenshtein distance.
function compareArrays(oldArray, newArray, options) {
// For backward compatibility, if the third arg is actually a bool, interpret
// it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
oldArray = oldArray || [];
newArray = newArray || [];
if (oldArray.length <= newArray.length)
return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
else
return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
}
function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
var myMin = Math.min,
myMax = Math.max,
editDistanceMatrix = [],
smlIndex, smlIndexMax = smlArray.length,
bigIndex, bigIndexMax = bigArray.length,
compareRange = (bigIndexMax - smlIndexMax) || 1,
maxDistance = smlIndexMax + bigIndexMax + 1,
thisRow, lastRow,
bigIndexMaxForRow, bigIndexMinForRow;
for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
lastRow = thisRow;
editDistanceMatrix.push(thisRow = []);
bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
bigIndexMinForRow = myMax(0, smlIndex - 1);
for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
if (!bigIndex)
thisRow[bigIndex] = smlIndex + 1;
else if (!smlIndex) // Top row - transform empty array into new array via additions
thisRow[bigIndex] = bigIndex + 1;
else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
else {
var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
}
}
}
var editScript = [], meMinusOne, notInSml = [], notInBig = [];
for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex - 1]) {
notInSml.push(editScript[editScript.length] = { // added
'status': statusNotInSml,
'value': bigArray[--bigIndex],
'index': bigIndex
});
} else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
notInBig.push(editScript[editScript.length] = { // deleted
'status': statusNotInBig,
'value': smlArray[--smlIndex],
'index': smlIndex
});
} else {
--bigIndex;
--smlIndex;
if (!options['sparse']) {
editScript.push({
'status': "retained",
'value': bigArray[bigIndex]
});
}
}
}
// Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
// smlIndexMax keeps the time complexity of this algorithm linear.
ko.utils.findMovesInArrayComparison(notInSml, notInBig, smlIndexMax * 10);
return editScript.reverse();
}
return compareArrays;
})();
ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
(function () {
// Objective:
// * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
// map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
// * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
// so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
// previously mapped - retain those nodes, and just insert/delete other ones
// "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
// You can use this, for example, to activate bindings on those nodes.
function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
// Map this array value inside a dependentObservable so we re-map when any dependency changes
var mappedNodes = [];
var dependentObservable = ko.dependentObservable(function () {
var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
// On subsequent evaluations, just replace the previously-inserted DOM nodes
if (mappedNodes.length > 0) {
ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
if (callbackAfterAddingNodes)
ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
}
// Replace the contents of the mappedNodes array, thereby updating the record
// of which nodes would be deleted if valueToMap was itself later removed
mappedNodes.length = 0;
ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
}, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function () { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
return { mappedNodes: mappedNodes, dependentObservable: (dependentObservable.isActive() ? dependentObservable : undefined) };
}
var lastMappingResultDomDataKey = ko.utils.domData.nextKey();
ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
// Compare the provided array against the previous one
array = array || [];
options = options || {};
var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
// Build the new mapping result
var newMappingResult = [];
var lastMappingResultIndex = 0;
var newMappingResultIndex = 0;
var nodesToDelete = [];
var itemsToProcess = [];
var itemsForBeforeRemoveCallbacks = [];
var itemsForMoveCallbacks = [];
var itemsForAfterAddCallbacks = [];
var mapData;
function itemMovedOrRetained(editScriptIndex, oldPosition) {
mapData = lastMappingResult[oldPosition];
if (newMappingResultIndex !== oldPosition)
itemsForMoveCallbacks[editScriptIndex] = mapData;
// Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
mapData.indexObservable(newMappingResultIndex++);
ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
newMappingResult.push(mapData);
itemsToProcess.push(mapData);
}
function callCallback(callback, items) {
if (callback) {
for (var i = 0, n = items.length; i < n; i++) {
if (items[i]) {
ko.utils.arrayForEach(items[i].mappedNodes, function (node) {
callback(node, i, items[i].arrayEntry);
});
}
}
}
}
for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
movedIndex = editScriptItem['moved'];
switch (editScriptItem['status']) {
case "deleted":
if (movedIndex === undefined) {
mapData = lastMappingResult[lastMappingResultIndex];
// Stop tracking changes to the mapping for these nodes
if (mapData.dependentObservable)
mapData.dependentObservable.dispose();
// Queue these nodes for later removal
nodesToDelete.push.apply(nodesToDelete, ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode));
if (options['beforeRemove']) {
itemsForBeforeRemoveCallbacks[i] = mapData;
itemsToProcess.push(mapData);
}
}
lastMappingResultIndex++;
break;
case "retained":
itemMovedOrRetained(i, lastMappingResultIndex++);
break;
case "added":
if (movedIndex !== undefined) {
itemMovedOrRetained(i, movedIndex);
} else {
mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
newMappingResult.push(mapData);
itemsToProcess.push(mapData);
if (!isFirstExecution)
itemsForAfterAddCallbacks[i] = mapData;
}
break;
}
}
// Call beforeMove first before any changes have been made to the DOM
callCallback(options['beforeMove'], itemsForMoveCallbacks);
// Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
// Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
// Get nodes for newly added items
if (!mapData.mappedNodes)
ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
// Put nodes in the right place if they aren't there already
for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
if (node !== nextNode)
ko.virtualElements.insertAfter(domNode, node, lastNode);
}
// Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
if (!mapData.initialized && callbackAfterAddingNodes) {
callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
mapData.initialized = true;
}
}
// If there's a beforeRemove callback, call it after reordering.
// Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
// some sort of animation, which is why we first reorder the nodes that will be removed. If the
// callback instead removes the nodes right away, it would be more efficient to skip reordering them.
// Perhaps we'll make that change in the future if this scenario becomes more common.
callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
// Finally call afterMove and afterAdd callbacks
callCallback(options['afterMove'], itemsForMoveCallbacks);
callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
// Store a copy of the array items we just considered so we can difference it next time
ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
}
})();
ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
ko.nativeTemplateEngine = function () {
this['allowTemplateRewriting'] = false;
}
ko.nativeTemplateEngine.prototype = new ko.templateEngine();
ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
if (templateNodes) {
return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
} else {
var templateText = templateSource['text']();
return ko.utils.parseHtmlFragment(templateText, templateDocument);
}
};
ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
(function () {
ko.jqueryTmplTemplateEngine = function () {
// Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
// doesn't expose a version number, so we have to infer it.
// Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
// which KO internally refers to as version "2", so older versions are no longer detected.
var jQueryTmplVersion = this.jQueryTmplVersion = (function () {
if (!jQueryInstance || !(jQueryInstance['tmpl']))
return 0;
// Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
try {
if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
// Since 1.0.0pre, custom tags should append markup to an array called "__"
return 2; // Final version of jquery.tmpl
}
} catch (ex) { /* Apparently not the version we were looking for */ }
return 1; // Any older version that we don't support
})();
function ensureHasReferencedJQueryTemplates() {
if (jQueryTmplVersion < 2)
throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
}
function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
}
this['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
templateDocument = templateDocument || document;
options = options || {};
ensureHasReferencedJQueryTemplates();
// Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
var precompiled = templateSource['data']('precompiled');
if (!precompiled) {
var templateText = templateSource['text']() || "";
// Wrap in "with($whatever.koBindingContext) { ... }"
templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
precompiled = jQueryInstance['template'](null, templateText);
templateSource['data']('precompiled', precompiled);
}
var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
resultNodes['appendTo'](templateDocument.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
return resultNodes;
};
this['createJavaScriptEvaluatorBlock'] = function (script) {
return "{{ko_code ((function() { return " + script + " })()) }}";
};
this['addTemplate'] = function (templateName, templateMarkup) {
document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
};
if (jQueryTmplVersion > 0) {
jQueryInstance['tmpl']['tag']['ko_code'] = {
open: "__.push($1 || '');"
};
jQueryInstance['tmpl']['tag']['ko_with'] = {
open: "with($1) {",
close: "} "
};
}
};
ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
// Use this one by default *only if jquery.tmpl is referenced*
var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
})();
}));
}());
})(); |
'use strict';
var keyMirror = require('keymirror');
var PlayerConstants = keyMirror({
PLAYER_PLAY: null,
PLAYER_STOP: null,
PLAYER_SET_VOLUME: null,
PLAYER_RESET: null,
});
module.exports = PlayerConstants;
|
/*jslint unparam: true, browser: true, indent: 2 */
;(function ($, window, document, undefined) {
'use strict';
Foundation.libs.reveal = {
name : 'reveal',
version : '4.2.2',
locked : false,
settings : {
animation: 'fadeAndPop',
animationSpeed: 250,
closeOnBackgroundClick: true,
closeOnEsc: true,
dismissModalClass: 'close-reveal-modal',
bgClass: 'reveal-modal-bg',
open: function(){},
opened: function(){},
close: function(){},
closed: function(){},
bg : $('.reveal-modal-bg'),
css : {
open : {
'opacity': 0,
'visibility': 'visible',
'display' : 'block'
},
close : {
'opacity': 1,
'visibility': 'hidden',
'display': 'none'
}
}
},
init : function (scope, method, options) {
Foundation.inherit(this, 'data_options delay');
if (typeof method === 'object') {
$.extend(true, this.settings, method);
} else if (typeof options !== 'undefined') {
$.extend(true, this.settings, options);
}
if (typeof method !== 'string') {
this.events();
return this.settings.init;
} else {
return this[method].call(this, options);
}
},
events : function () {
var self = this;
$(this.scope)
.off('.fndtn.reveal')
.on('click.fndtn.reveal', '[data-reveal-id]', function (e) {
e.preventDefault();
if (!self.locked) {
var element = $(this),
ajax = element.data('reveal-ajax');
self.locked = true;
if (typeof ajax === 'undefined') {
self.open.call(self, element);
} else {
var url = ajax === true ? element.attr('href') : ajax;
self.open.call(self, element, {url: url});
}
}
})
.on('click.fndtn.reveal', this.close_targets(), function (e) {
e.preventDefault();
if (!self.locked) {
var settings = $.extend({}, self.settings, self.data_options($('.reveal-modal.open')));
if ($(e.target)[0] === $('.' + settings.bgClass)[0] && !settings.closeOnBackgroundClick) {
return;
}
self.locked = true;
self.close.call(self, $(this).closest('.reveal-modal'));
}
})
.on('open.fndtn.reveal', '.reveal-modal', this.settings.open)
.on('opened.fndtn.reveal', '.reveal-modal', this.settings.opened)
.on('opened.fndtn.reveal', '.reveal-modal', this.open_video)
.on('close.fndtn.reveal', '.reveal-modal', this.settings.close)
.on('closed.fndtn.reveal', '.reveal-modal', this.settings.closed)
.on('closed.fndtn.reveal', '.reveal-modal', this.close_video);
$( 'body' ).bind( 'keyup.reveal', function ( event ) {
var open_modal = $('.reveal-modal.open'),
settings = $.extend({}, self.settings, self.data_options(open_modal));
if ( event.which === 27 && settings.closeOnEsc) { // 27 is the keycode for the Escape key
open_modal.foundation('reveal', 'close');
}
});
return true;
},
open : function (target, ajax_settings) {
if (target) {
if (typeof target.selector !== 'undefined') {
var modal = $('#' + target.data('reveal-id'));
} else {
var modal = $(this.scope);
ajax_settings = target;
}
} else {
var modal = $(this.scope);
}
if (!modal.hasClass('open')) {
var open_modal = $('.reveal-modal.open');
if (typeof modal.data('css-top') === 'undefined') {
modal.data('css-top', parseInt(modal.css('top'), 10))
.data('offset', this.cache_offset(modal));
}
modal.trigger('open');
if (open_modal.length < 1) {
this.toggle_bg(modal);
}
if (typeof ajax_settings === 'undefined' || !ajax_settings.url) {
this.hide(open_modal, this.settings.css.close);
this.show(modal, this.settings.css.open);
} else {
var self = this,
old_success = typeof ajax_settings.success !== 'undefined' ? ajax_settings.success : null;
$.extend(ajax_settings, {
success: function (data, textStatus, jqXHR) {
if ( $.isFunction(old_success) ) {
old_success(data, textStatus, jqXHR);
}
modal.html(data);
$(modal).foundation('section', 'reflow');
self.hide(open_modal, self.settings.css.close);
self.show(modal, self.settings.css.open);
}
});
$.ajax(ajax_settings);
}
}
},
close : function (modal) {
var modal = modal && modal.length ? modal : $(this.scope),
open_modals = $('.reveal-modal.open');
if (open_modals.length > 0) {
this.locked = true;
modal.trigger('close');
this.toggle_bg(modal);
this.hide(open_modals, this.settings.css.close);
}
},
close_targets : function () {
var base = '.' + this.settings.dismissModalClass;
if (this.settings.closeOnBackgroundClick) {
return base + ', .' + this.settings.bgClass;
}
return base;
},
toggle_bg : function (modal) {
if ($('.reveal-modal-bg').length === 0) {
this.settings.bg = $('<div />', {'class': this.settings.bgClass})
.appendTo('body');
}
if (this.settings.bg.filter(':visible').length > 0) {
this.hide(this.settings.bg);
} else {
this.show(this.settings.bg);
}
},
show : function (el, css) {
// is modal
if (css) {
if (/pop/i.test(this.settings.animation)) {
css.top = $(window).scrollTop() - el.data('offset') + 'px';
var end_css = {
top: $(window).scrollTop() + el.data('css-top') + 'px',
opacity: 1
};
return this.delay(function () {
return el
.css(css)
.animate(end_css, this.settings.animationSpeed, 'linear', function () {
this.locked = false;
el.trigger('opened');
}.bind(this))
.addClass('open');
}.bind(this), this.settings.animationSpeed / 2);
}
if (/fade/i.test(this.settings.animation)) {
var end_css = {opacity: 1};
return this.delay(function () {
return el
.css(css)
.animate(end_css, this.settings.animationSpeed, 'linear', function () {
this.locked = false;
el.trigger('opened');
}.bind(this))
.addClass('open');
}.bind(this), this.settings.animationSpeed / 2);
}
return el.css(css).show().css({opacity: 1}).addClass('open').trigger('opened');
}
// should we animate the background?
if (/fade/i.test(this.settings.animation)) {
return el.fadeIn(this.settings.animationSpeed / 2);
}
return el.show();
},
hide : function (el, css) {
// is modal
if (css) {
if (/pop/i.test(this.settings.animation)) {
var end_css = {
top: - $(window).scrollTop() - el.data('offset') + 'px',
opacity: 0
};
return this.delay(function () {
return el
.animate(end_css, this.settings.animationSpeed, 'linear', function () {
this.locked = false;
el.css(css).trigger('closed');
}.bind(this))
.removeClass('open');
}.bind(this), this.settings.animationSpeed / 2);
}
if (/fade/i.test(this.settings.animation)) {
var end_css = {opacity: 0};
return this.delay(function () {
return el
.animate(end_css, this.settings.animationSpeed, 'linear', function () {
this.locked = false;
el.css(css).trigger('closed');
}.bind(this))
.removeClass('open');
}.bind(this), this.settings.animationSpeed / 2);
}
return el.hide().css(css).removeClass('open').trigger('closed');
}
// should we animate the background?
if (/fade/i.test(this.settings.animation)) {
return el.fadeOut(this.settings.animationSpeed / 2);
}
return el.hide();
},
close_video : function (e) {
var video = $(this).find('.flex-video'),
iframe = video.find('iframe');
if (iframe.length > 0) {
iframe.attr('data-src', iframe[0].src);
iframe.attr('src', 'about:blank');
video.hide();
}
},
open_video : function (e) {
var video = $(this).find('.flex-video'),
iframe = video.find('iframe');
if (iframe.length > 0) {
var data_src = iframe.attr('data-src');
if (typeof data_src === 'string') {
iframe[0].src = iframe.attr('data-src');
} else {
var src = iframe[0].src;
iframe[0].src = undefined;
iframe[0].src = src;
}
video.show();
}
},
cache_offset : function (modal) {
var offset = modal.show().height() + parseInt(modal.css('top'), 10);
modal.hide();
return offset;
},
off : function () {
$(this.scope).off('.fndtn.reveal');
},
reflow : function () {}
};
}(Foundation.zj, this, this.document)); |
/* global angular */
angular.module('afkl.lazyImage', []);
/* global angular */
angular.module('afkl.lazyImage')
.service('afklSrcSetService', ['$window', function($window) {
'use strict';
/**
* For other applications wanting the srccset/best image approach it is possible to use this module only
* Loosely based on https://raw.github.com/borismus/srcset-polyfill/master/js/srcset-info.js
*/
var INT_REGEXP = /^[0-9]+$/;
// SRCSET IMG OBJECT
function ImageInfo(options) {
this.src = options.src;
this.w = options.w || Infinity;
this.h = options.h || Infinity;
this.x = options.x || 1;
}
/**
* Parse srcset rules
* @param {string} descString Containing all srcset rules
* @return {object} Srcset rules
*/
var _parseDescriptors = function (descString) {
var descriptors = descString.split(/\s/);
var out = {};
for (var i = 0, l = descriptors.length; i < l; i++) {
var desc = descriptors[i];
if (desc.length > 0) {
var lastChar = desc.slice(-1);
var value = desc.substring(0, desc.length - 1);
var intVal = parseInt(value, 10);
var floatVal = parseFloat(value);
if (value.match(INT_REGEXP) && lastChar === 'w') {
out[lastChar] = intVal;
} else if (value.match(INT_REGEXP) && lastChar === 'h') {
out[lastChar] = intVal;
} else if (!isNaN(floatVal) && lastChar === 'x') {
out[lastChar] = floatVal;
}
}
}
return out;
};
/**
* Returns best candidate under given circumstances
* @param {object} images Candidate image
* @param {function} criteriaFn Rule
* @return {object} Returns best candidate under given criteria
*/
var _getBestCandidateIf = function (images, criteriaFn) {
var bestCandidate = images[0];
for (var i = 0, l = images.length; i < l; i++) {
var candidate = images[i];
if (criteriaFn(candidate, bestCandidate)) {
bestCandidate = candidate;
}
}
return bestCandidate;
};
/**
* Remove candidate under given circumstances
* @param {object} images Candidate image
* @param {function} criteriaFn Rule
* @return {object} Removes images from global image collection (candidates)
*/
var _removeCandidatesIf = function (images, criteriaFn) {
for (var i = images.length - 1; i >= 0; i--) {
var candidate = images[i];
if (criteriaFn(candidate)) {
images.splice(i, 1); // remove it
}
}
return images;
};
/**
* Direct implementation of "processing the image candidates":
* http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content-1.html#processing-the-image-candidates
*
* @param {array} imageCandidates (required)
* @param {object} view (optional)
* @returns {ImageInfo} The best image of the possible candidates.
*/
var getBestImage = function (imageCandidates, view) {
if (!imageCandidates) { return; }
if (!view) {
view = {
'w' : $window.innerWidth || document.documentElement.clientWidth,
'h' : $window.innerHeight || document.documentElement.clientHeight,
'x' : $window.devicePixelRatio || 1
};
}
var images = imageCandidates.slice(0);
/* LARGEST */
// Width
var largestWidth = _getBestCandidateIf(images, function (a, b) { return a.w > b.w; });
// Less than client width.
_removeCandidatesIf(images, (function () { return function (a) { return a.w < view.w; }; })(this));
// If none are left, keep the one with largest width.
if (images.length === 0) { images = [largestWidth]; }
// Height
var largestHeight = _getBestCandidateIf(images, function (a, b) { return a.h > b.h; });
// Less than client height.
_removeCandidatesIf(images, (function () { return function (a) { return a.h < view.h; }; })(this));
// If none are left, keep one with largest height.
if (images.length === 0) { images = [largestHeight]; }
// Pixel density.
var largestPxDensity = _getBestCandidateIf(images, function (a, b) { return a.x > b.x; });
// Remove all candidates with pxdensity less than client pxdensity.
_removeCandidatesIf(images, (function () { return function (a) { return a.x < view.x; }; })(this));
// If none are left, keep one with largest pixel density.
if (images.length === 0) { images = [largestPxDensity]; }
/* SMALLEST */
// Width
var smallestWidth = _getBestCandidateIf(images, function (a, b) { return a.w < b.w; });
// Remove all candidates with width greater than it.
_removeCandidatesIf(images, function (a) { return a.w > smallestWidth.w; });
// Height
var smallestHeight = _getBestCandidateIf(images, function (a, b) { return a.h < b.h; });
// Remove all candidates with height greater than it.
_removeCandidatesIf(images, function (a) { return a.h > smallestHeight.h; });
// Pixel density
var smallestPxDensity = _getBestCandidateIf(images, function (a, b) { return a.x < b.x; });
// Remove all candidates with pixel density less than smallest px density.
_removeCandidatesIf(images, function (a) { return a.x > smallestPxDensity.x; });
return images[0];
};
// options {src: null/string, srcset: string}
// options.src normal url or null
// options.srcset 997-s.jpg 480w, 997-m.jpg 768w, 997-xl.jpg 1x
var getSrcset = function (options) {
var imageCandidates = [];
var srcValue = options.src;
var srcsetValue = options.srcset;
if (!srcsetValue) { return; }
/* PUSH CANDIDATE [{src: _, x: _, w: _, h:_}, ...] */
var _addCandidate = function (img) {
for (var j = 0, ln = imageCandidates.length; j < ln; j++) {
var existingCandidate = imageCandidates[j];
// DUPLICATE
if (existingCandidate.x === img.x &&
existingCandidate.w === img.w &&
existingCandidate.h === img.h) { return; }
}
imageCandidates.push(img);
};
var _parse = function () {
var input = srcsetValue,
position = 0,
rawCandidates = [],
url,
descriptors;
while (input !== '') {
while (input.charAt(0) === ' ') {
input = input.slice(1);
}
position = input.indexOf(' ');
if (position !== -1) {
url = input.slice(0, position);
// if (url === '') { break; }
input = input.slice(position + 1);
position = input.indexOf(',');
if (position === -1) {
descriptors = input;
input = '';
} else {
descriptors = input.slice(0, position);
input = input.slice(position + 1);
}
rawCandidates.push({
url: url,
descriptors: descriptors
});
} else {
rawCandidates.push({
url: input,
descriptors: ''
});
input = '';
}
}
// FROM RAW CANDIDATES PUSH IMAGES TO COMPLETE SET
for (var i = 0, l = rawCandidates.length; i < l; i++) {
var candidate = rawCandidates[i],
desc = _parseDescriptors(candidate.descriptors);
_addCandidate(new ImageInfo({
src: candidate.url,
x: desc.x,
w: desc.w,
h: desc.h
}));
}
if (srcValue) {
_addCandidate(new ImageInfo({src: srcValue}));
}
};
_parse();
// Return best available image for current view based on our list of candidates
var bestImage = getBestImage(imageCandidates);
/**
* Object returning best match at moment, and total collection of candidates (so 'image' API can be used by consumer)
* @type {Object}
*/
var object = {
'best': bestImage, // IMAGE INFORMATION WHICH FITS BEST WHEN API IS REQUESTED
'candidates': imageCandidates // ALL IMAGE CANDIDATES BY GIVEN SRCSET ATTRIBUTES
};
// empty collection
imageCandidates = null;
// pass best match and candidates
return object;
};
/**
* PUBLIC API
*/
return {
get: getSrcset, // RETURNS BEST IMAGE AND IMAGE CANDIDATES
image: getBestImage // RETURNS BEST IMAGE WITH GIVEN CANDIDATES
};
}]);
/* global angular */
angular.module('afkl.lazyImage')
.directive('afklImageContainer', function () {
'use strict';
return {
restrict: 'A',
// We have to use controller instead of link here so that it will always run earlier than nested afklLazyImage directives
controller: ['$scope', '$element', function ($scope, $element) {
$element.data('afklImageContainer', $element);
}]
};
})
.directive('afklLazyImage', ['$window', '$timeout', 'afklSrcSetService', function ($window, $timeout, srcSetService) {
'use strict';
// Use srcSetService to find out our best available image
var bestImage = function (images) {
var image = srcSetService.get({srcset: images});
var sourceUrl;
if (image) {
sourceUrl = image.best.src;
}
return sourceUrl;
};
return {
restrict: 'A',
link: function (scope, element, attrs) {
// CONFIGURATION VARS
var $container = element.inheritedData('afklImageContainer');
if (!$container) {
$container = angular.element(attrs.afklLazyImageContainer || $window);
}
var loaded = false;
var timeout;
var images = attrs.afklLazyImage; // srcset attributes
var options = attrs.afklLazyImageOptions ? angular.fromJson(attrs.afklLazyImageOptions) : {
background:true
}; // options (background, offset)
var img; // Angular element to image which will be placed
var currentImage = null; // current image url
var offset = options.offset ? options.offset : 50; // default offset
var LOADING = 'afkl-lazy-image-loading';
var _containerScrollTop = function () {
// See if we can use jQuery, then extra check since directives like angular-scroll fuck this up as well
// TODO: check if number is returned
if ($container.scrollTop) {
var scrollTopPosition = $container.scrollTop();
if (scrollTopPosition) {
return scrollTopPosition;
}
}
var c = $container[0];
if (c.pageYOffset !== undefined) {
return c.pageYOffset;
}
else if (c.scrollTop !== undefined) {
return c.scrollTop;
}
return document.documentElement.scrollTop || 0;
};
var _containerInnerHeight = function () {
if ($container.innerHeight) {
return $container.innerHeight();
}
var c = $container[0];
if (c.innerHeight !== undefined) {
return c.innerHeight;
} else if (c.clientHeight !== undefined) {
return c.clientHeight;
}
return document.documentElement.clientHeight || 0;
};
// Begin with offset and update on resize
var _elementOffset = function () {
if (element.offset) {
return element.offset().top;
}
var box = element[0].getBoundingClientRect();
return box.top + _containerScrollTop() - document.documentElement.clientTop;
};
var _elementOffsetContainer = function () {
if (element.offset) {
return element.offset().top - $container.offset().top;
}
return element[0].getBoundingClientRect().top - $container[0].getBoundingClientRect().top;
};
// Update url of our image
var _setImage = function () {
if (options.background) {
element[0].style.backgroundImage = 'url("' + currentImage +'")';
} else {
img[0].src = currentImage;
}
};
// Append image to DOM
var _placeImage = function () {
loaded = true;
// What is my best image available
currentImage = bestImage(images);
if (currentImage) {
// we have to make an image if background is false (default)
if (!options.background) {
if (!img) {
element.addClass(LOADING);
img = angular.element('<img alt="" class="afkl-lazy-image" src=""/>');
// remove loading class when image is acually loaded
img.one('load', _loaded);
element.append(img);
}
}
// set correct src/url
_setImage();
}
// Element is added to dom, no need to listen to scroll anymore
$container.off('scroll', _onScroll);
};
// Check on resize if actually a new image is best fit, if so then apply it
var _checkIfNewImage = function () {
if (loaded) {
var newImage = bestImage(images);
if (newImage !== currentImage) {
// update current url
currentImage = newImage;
// update image url
_setImage();
}
}
};
// First update our begin offset
_checkIfNewImage();
var _loaded = function () {
element.removeClass(LOADING);
};
// EVENT: SCROLL. Check if our container is for first time in our view or not
var _onScroll = function () {
// Config vars
var remaining, shouldLoad, windowBottom;
var height = _containerInnerHeight();
/*var scroll = "scrollY" in $window[0] ?
$window[0].scrollY
: document.documentElement.scrollTop;*/
// https://developer.mozilla.org/en-US/docs/Web/API/window.scrollY
var scroll = _containerScrollTop();
var elOffset = $container[0] === $window ? _elementOffset() : _elementOffsetContainer();
windowBottom = $container[0] === $window ? height + scroll : height;
remaining = elOffset - windowBottom;
// Is our top of our image container in bottom of our viewport?
//console.log($container[0].className, _elementOffset(), _elementPosition(), height, scroll, remaining, elOffset);
shouldLoad = remaining <= offset;
// Append image first time when it comes into our view, after that only resizing can have influence
if (shouldLoad && !loaded) {
_placeImage();
}
};
// EVENT: RESIZE.
var _onResize = function () {
$timeout.cancel(timeout);
timeout = $timeout(_checkIfNewImage, 300);
};
// Remove events for total destroy
var _eventsOff = function() {
$timeout.cancel(timeout);
$container.off('scroll', _onScroll);
angular.element($window).off('resize', _onResize);
if ($container[0] !== $window) {
$container.off('resize', _onResize);
}
// remove image being placed
if (img) {
img.remove();
}
img = timeout = currentImage = undefined;
};
// Set events for scrolling and resizing
$container.on('scroll', _onScroll);
angular.element($window).on('resize', _onResize);
if ($container[0] !== $window) {
$container.on('resize', _onResize);
}
// events for image change
attrs.$observe('afklLazyImage', function () {
images = attrs.afklLazyImage;
if (loaded) {
_placeImage();
}
});
// Image should be directly placed
if (options.nolazy) {
_placeImage();
}
// Remove all events when destroy takes place
scope.$on('$destroy', function () {
return _eventsOff();
});
return _onScroll();
}
};
}]);
|
const fs = require('fs')
const path = require('path')
const readline = require('readline')
const envFile = path.join(process.argv[2], '..', process.env['ENVFILE'] || '.env')
const outDir = path.join(process.argv[3], 'Generated Files')
console.log(`Generating files in ${outDir} from ${envFile} env file`)
if (!fs.existsSync(outDir)) {
fs.mkdirSync(outDir)
}
if (fs.existsSync(envFile)) {
const vars = []
const regex = /^\s*(?:export\s+|)([\w\d\.\-_]+)\s*=\s*['"]?(.*?)?['"]?\s*$/
readline.createInterface({
input: fs.createReadStream(envFile),
console: false
}).on('line', (line)=>{
const matches = line.match(regex)
if (matches)
vars.push({key: matches[1], value: matches[2]})
}).on('close', ()=> {
generateFiles(vars)
});
} else {
console.warn(`waring: env file ${envFile} does not exit`)
generateFiles([])
}
function generateFiles(vars) {
// Native code
let nativeCode = '';
// React Native Module code
let rnCode = '';
nativeCode += '#include<string>\n'
nativeCode += 'namespace ReactNativeConfig {\n'
for (let {key, value} of vars) {
const escaped = escapeString(value)
nativeCode += ` inline static std::string ${key} = ${escaped};\n`
rnCode += `REACT_CONSTANT(${key});\n`
rnCode += `static inline const std::string ${key} = ${escaped};\n`;
}
nativeCode +='}\n'
updateFile(nativeCode, path.join(outDir, 'RNCConfigValues.h'))
updateFile(rnCode, path.join(outDir, 'RNCConfigValuesModule.inc.g.h'))
}
// Escape the string so it will work with C++
// assume the string is UTF-8
const escapeRegex = /[a-zA-Z0-9`~!@#$%^&*()_=\-\+\{\}\];:'|<,.>?/\ ]/
function escapeString(string) {
let escaped = '"';
for (let i = 0; i < string.length; ++i) {
if (!string.substr(i,1).match(escapeRegex))
escaped += `\\u${string.charCodeAt(i).toString(16)}`
else
escaped += string[i]
}
escaped += '"';
return escaped;
}
// Make sure to not alter mtime of a file if its content did not change
function updateFile(content, filename) {
if (!fs.existsSync(filename) || fs.readFileSync(filename) != content) {
fs.writeFileSync(filename, content)
console.log(`Written ${filename}`)
} else {
console.log(`Skipped ${filename} since content was not changed`)
}
}
|
if(!Date.now) Date.now = function(){ return (new Date).getTime()};
test('package',function() {
expect(7);
ok(Package,'has Package');
ok(Package('x'),'creation Package x');
ok(Package('x.yy'),'creation Package x.yy');
ok(Package('x.yy.zzz'),'creation Package x.yy.zzz');
ok(Package.classProvider.x,'Package x exists');
ok(Package.classProvider.x.yy,'Package x.yy exists');
ok(Package.classProvider.x.yy.zzz,'Package x.yy.zzz exists');
});
test('define',function() {
expect(1);
Package('x.yy.zzz')
.define('abc', {
some_function: function(v) {
ok(v, 'function run');
}
}).run(function(cc) {
cc.abc.some_function(true);
});
});
test('use',function() {
expect(1);
Package('x.yy.zzz')
.define('UseTest1', {
});
Package('x.yy.zzz')
.use('x.yy.zzz.UseTest1')
.run(function(cc) {
ok(cc.UseTest1, 'test use');
});
});
test('extend',function() {
expect(4);
Package('x.yy.zzz')
.define('Parent', function(cc) { return Package.Class.extend({
initialize: function(v) {
ok(v, 'parent initialize run');
},
some_function: function(v) {
ok(v, 'parent function run');
}
});});
Package('x.yy.zzz')
.define('Child', function(cc) { return Package.classProvider.x.yy.zzz.Parent.extend({
initialize: function(v) {
ok(v, 'child initialize run');
Package.classProvider.x.yy.zzz.Parent.prototype.initialize(v);
},
some_function: function(v) {
ok(v, 'child function run');
Package.classProvider.x.yy.zzz.Parent.prototype.some_function(v);
}
});}).run(function(cc) {
new cc.Child(true).some_function(true);
});
});
test('__class', function() {
expect(17);
Package('X').define('Root', function(cc) { return Package.Class.extend({
cry: 'Gyao',
Gyao: function() {
return 'Root ' + this.cry;
},
selfClass: function() {
return this.__class === Package.classProvider.X.Root;
},
parentClass: function() {
return this.__class.__super === Package.Class;
},
}); });
Package('X').define('Child', function(cc) { return Package.classProvider.X.Root.extend({
cry: 'Nyan',
Gyao: function() {
return 'Child ' + this.cry;
},
selfClass: function() {
return this.__class === Package.classProvider.X.Child;
},
parentClass: function() {
return this.__class.__super === Package.classProvider.X.Root;
},
}); });
Package('X').define('ChildChild', function(cc) { return Package.classProvider.X.Child.extend({
cry: 'Wan',
rootGyao: function() {
return this.__class.__super.__super.prototype.Gyao.apply(this, []);
},
selfClass: function() {
return this.__class === Package.classProvider.X.ChildChild;
},
parentClass: function() {
return this.__class.__super === Package.classProvider.X.Child;
},
}); });
var root = new Package.classProvider.X.Root();
var child = new Package.classProvider.X.Child();
var childchild = new Package.classProvider.X.ChildChild();
ok(root.__class.toString() === 'X.Root', 'X.Root');
ok(child.__class.toString() === 'X.Child', 'X.Child');
ok(child.__class.__super.toString() === 'X.Root', 'X.Root');
ok(childchild.__class.toString() === 'X.ChildChild', 'X.ChildChild');
ok(childchild.__class.__super.toString() === 'X.Child', 'X.Child');
ok(childchild.__class.__super.__super.toString() === 'X.Root', 'X.Root');
ok(childchild.__class.__super.__super.__super === Package.Class, 'Package.Class');
ok(root.Gyao() === 'Root Gyao', 'Root Gyao');
ok(child.Gyao() === 'Child Nyan', 'Child Nyan');
ok(childchild.Gyao() === 'Child Wan', 'Child Wan');
ok(childchild.rootGyao() === 'Root Wan', 'Root Wan');
ok(root.selfClass() === true, 'Root selfClass');
ok(child.selfClass() === true, 'Child selfClass');
ok(childchild.selfClass() === true, 'Child selfClass');
ok(root.parentClass() === true, 'Root parentClass');
ok(child.parentClass() === true, 'Child parentClass');
ok(childchild.parentClass() === true, 'Child parentClass');
});
|
import 'hidpi-canvas/dist/hidpi-canvas.min';
import config from 'src/config';
import Matrix from 'src/classes/Matrix';
import View from 'src/classes/View';
import Field from 'src/classes/Field';
import 'src/app.css';
const matrix = new Matrix();
const view = new View(document.querySelector('canvas').getContext('2d'));
const cellSize = config.cellSize.default;
const field = new Field(matrix, view, cellSize);
field.load();
field.render();
field.subscribe();
// for debugging only
window.field = field;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.