code stringlengths 2 1.05M |
|---|
import * as types from '../constants/favorites';
import { getExtendedCartList, getExtendedList } from 'utils/helpers';
const initialState = {
isFetching: false,
isFetched: false,
error: null,
added: []
};
export default function cart(state = initialState, action) {
switch (action.type) {
case types.ADD_TO_FAVORITES_START:
return {
...state,
isFetching: true
};
case types.ADD_TO_FAVORITES_SUCCESS:
const newList = getExtendedCartList(state.added, { ...action.product }, action.remove);
localStorage.setItem("favorites", JSON.stringify(newList));
return {
...state,
isFetching: false,
isFetched: true,
added: newList,
error: null
};
case types.SET_FAVORITES_SUCCESS:
return {
...state,
isFetching: false,
isFetched: true,
added: action.data,
error: null
};
case types.ADD_TO_FAVORITES_FAILURE:
return {
...state,
isFetching: false,
isFetched: false,
error: action.error
};
case types.REMOVE_FROM_FAVORITES_START:
return {
...state,
isFetching: true
};
case types.REMOVE_FROM_FAVORITES_SUCCESS:
const editedList = getExtendedList(state.added, action.product ,{}, false, true);
localStorage.setItem("favorites", JSON.stringify(editedList));
return {
...state,
isFetching: false,
isFetched: true,
added: editedList,
error: null
};
case types.REMOVE_FROM_FAILURE:
return {
...state,
isFetching: false,
isFetched: false,
error: action.error
};
case types.GET_FAVORITES_START:
return {
...state,
isFetching: true
};
case types.GET_FAVORITES_SUCCESS:
return {
...state,
isFetching: false,
isFetched: true,
added: action.product,
error: null
};
case types.GET_FAVORITES_FAILURE:
return {
...state,
isFetching: false,
isFetched: false,
};
default:
return state;
}
}
|
(function () {
'use strict';
var padding = 16;
var createChartConfig = function (container) {
var width = container.clientWidth;
var height = width * .5;
return {
height: height,
heightInner: height - padding * 2,
padding: padding,
width: width,
widthInner: width - padding * 2,
};
};
var fetchError = function (response) {
if (!response.ok) {
return Promise.reject(new Error(response.statusText));
}
return response;
};
var ascending = function(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
};
var bisector = function(compare) {
if (compare.length === 1) { compare = ascendingComparator(compare); }
return {
left: function(a, x, lo, hi) {
if (lo == null) { lo = 0; }
if (hi == null) { hi = a.length; }
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) < 0) { lo = mid + 1; }
else { hi = mid; }
}
return lo;
},
right: function(a, x, lo, hi) {
if (lo == null) { lo = 0; }
if (hi == null) { hi = a.length; }
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) > 0) { hi = mid; }
else { lo = mid + 1; }
}
return lo;
}
};
};
function ascendingComparator(f) {
return function(d, x) {
return ascending(f(d), x);
};
}
var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
function pair(a, b) {
return [a, b];
}
var number = function(x) {
return x === null ? NaN : +x;
};
var extent = function(values, valueof) {
var n = values.length,
i = -1,
value,
min,
max;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
min = max = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null) {
if (min > value) { min = value; }
if (max < value) { max = value; }
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
min = max = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null) {
if (min > value) { min = value; }
if (max < value) { max = value; }
}
}
}
}
}
return [min, max];
};
var identity = function(x) {
return x;
};
var sequence = function(start, stop, step) {
start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
var i = -1,
n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
range = new Array(n);
while (++i < n) {
range[i] = start + i * step;
}
return range;
};
var e10 = Math.sqrt(50);
var e5 = Math.sqrt(10);
var e2 = Math.sqrt(2);
var ticks = function(start, stop, count) {
var reverse = stop < start,
i = -1,
n,
ticks,
step;
if (reverse) { n = start, start = stop, stop = n; }
if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) { return []; }
if (step > 0) {
start = Math.ceil(start / step);
stop = Math.floor(stop / step);
ticks = new Array(n = Math.ceil(stop - start + 1));
while (++i < n) { ticks[i] = (start + i) * step; }
} else {
start = Math.floor(start * step);
stop = Math.ceil(stop * step);
ticks = new Array(n = Math.ceil(start - stop + 1));
while (++i < n) { ticks[i] = (start - i) / step; }
}
if (reverse) { ticks.reverse(); }
return ticks;
};
function tickIncrement(start, stop, count) {
var step = (stop - start) / Math.max(0, count),
power = Math.floor(Math.log(step) / Math.LN10),
error = step / Math.pow(10, power);
return power >= 0
? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
: -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}
function tickStep(start, stop, count) {
var step0 = Math.abs(stop - start) / Math.max(0, count),
step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
error = step0 / step1;
if (error >= e10) { step1 *= 10; }
else if (error >= e5) { step1 *= 5; }
else if (error >= e2) { step1 *= 2; }
return stop < start ? -step1 : step1;
}
var sturges = function(values) {
return Math.ceil(Math.log(values.length) / Math.LN2) + 1;
};
var threshold = function(values, p, valueof) {
if (valueof == null) { valueof = number; }
if (!(n = values.length)) { return; }
if ((p = +p) <= 0 || n < 2) { return +valueof(values[0], 0, values); }
if (p >= 1) { return +valueof(values[n - 1], n - 1, values); }
var n,
i = (n - 1) * p,
i0 = Math.floor(i),
value0 = +valueof(values[i0], i0, values),
value1 = +valueof(values[i0 + 1], i0 + 1, values);
return value0 + (value1 - value0) * (i - i0);
};
var max = function(values, valueof) {
var n = values.length,
i = -1,
value,
max;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null && value > max) {
max = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null && value > max) {
max = value;
}
}
}
}
}
return max;
};
var merge = function(arrays) {
var n = arrays.length,
m,
i = -1,
j = 0,
merged,
array;
while (++i < n) { j += arrays[i].length; }
merged = new Array(j);
while (--n >= 0) {
array = arrays[n];
m = array.length;
while (--m >= 0) {
merged[--j] = array[m];
}
}
return merged;
};
var min = function(values, valueof) {
var n = values.length,
i = -1,
value,
min;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
min = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null && min > value) {
min = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
min = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null && min > value) {
min = value;
}
}
}
}
}
return min;
};
function length(d) {
return d.length;
}
var noop = {value: function() {}};
function dispatch() {
var arguments$1 = arguments;
for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
if (!(t = arguments$1[i] + "") || (t in _)) { throw new Error("illegal type: " + t); }
_[t] = [];
}
return new Dispatch(_);
}
function Dispatch(_) {
this._ = _;
}
function parseTypenames(typenames, types) {
return typenames.trim().split(/^|\s+/).map(function(t) {
var name = "", i = t.indexOf(".");
if (i >= 0) { name = t.slice(i + 1), t = t.slice(0, i); }
if (t && !types.hasOwnProperty(t)) { throw new Error("unknown type: " + t); }
return {type: t, name: name};
});
}
Dispatch.prototype = dispatch.prototype = {
constructor: Dispatch,
on: function(typename, callback) {
var _ = this._,
T = parseTypenames(typename + "", _),
t,
i = -1,
n = T.length;
// If no callback was specified, return the callback of the given type and name.
if (arguments.length < 2) {
while (++i < n) { if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) { return t; } }
return;
}
// If a type was specified, set the callback for the given type and name.
// Otherwise, if a null callback was specified, remove callbacks of the given name.
if (callback != null && typeof callback !== "function") { throw new Error("invalid callback: " + callback); }
while (++i < n) {
if (t = (typename = T[i]).type) { _[t] = set(_[t], typename.name, callback); }
else if (callback == null) { for (t in _) { _[t] = set(_[t], typename.name, null); } }
}
return this;
},
copy: function() {
var copy = {}, _ = this._;
for (var t in _) { copy[t] = _[t].slice(); }
return new Dispatch(copy);
},
call: function(type, that) {
var arguments$1 = arguments;
if ((n = arguments.length - 2) > 0) { for (var args = new Array(n), i = 0, n, t; i < n; ++i) { args[i] = arguments$1[i + 2]; } }
if (!this._.hasOwnProperty(type)) { throw new Error("unknown type: " + type); }
for (t = this._[type], i = 0, n = t.length; i < n; ++i) { t[i].value.apply(that, args); }
},
apply: function(type, that, args) {
if (!this._.hasOwnProperty(type)) { throw new Error("unknown type: " + type); }
for (var t = this._[type], i = 0, n = t.length; i < n; ++i) { t[i].value.apply(that, args); }
}
};
function get(type, name) {
for (var i = 0, n = type.length, c; i < n; ++i) {
if ((c = type[i]).name === name) {
return c.value;
}
}
}
function set(type, name, callback) {
for (var i = 0, n = type.length; i < n; ++i) {
if (type[i].name === name) {
type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
break;
}
}
if (callback != null) { type.push({name: name, value: callback}); }
return type;
}
var xhtml = "http://www.w3.org/1999/xhtml";
var namespaces = {
svg: "http://www.w3.org/2000/svg",
xhtml: xhtml,
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
};
var namespace = function(name) {
var prefix = name += "", i = prefix.indexOf(":");
if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") { name = name.slice(i + 1); }
return namespaces.hasOwnProperty(prefix) ? {space: namespaces[prefix], local: name} : name;
};
function creatorInherit(name) {
return function() {
var document = this.ownerDocument,
uri = this.namespaceURI;
return uri === xhtml && document.documentElement.namespaceURI === xhtml
? document.createElement(name)
: document.createElementNS(uri, name);
};
}
function creatorFixed(fullname) {
return function() {
return this.ownerDocument.createElementNS(fullname.space, fullname.local);
};
}
var creator = function(name) {
var fullname = namespace(name);
return (fullname.local
? creatorFixed
: creatorInherit)(fullname);
};
var matcher = function(selector) {
return function() {
return this.matches(selector);
};
};
if (typeof document !== "undefined") {
var element = document.documentElement;
if (!element.matches) {
var vendorMatches = element.webkitMatchesSelector
|| element.msMatchesSelector
|| element.mozMatchesSelector
|| element.oMatchesSelector;
matcher = function(selector) {
return function() {
return vendorMatches.call(this, selector);
};
};
}
}
var matcher$1 = matcher;
var filterEvents = {};
var event = null;
if (typeof document !== "undefined") {
var element$1 = document.documentElement;
if (!("onmouseenter" in element$1)) {
filterEvents = {mouseenter: "mouseover", mouseleave: "mouseout"};
}
}
function filterContextListener(listener, index, group) {
listener = contextListener(listener, index, group);
return function(event) {
var related = event.relatedTarget;
if (!related || (related !== this && !(related.compareDocumentPosition(this) & 8))) {
listener.call(this, event);
}
};
}
function contextListener(listener, index, group) {
return function(event1) {
var event0 = event; // Events can be reentrant (e.g., focus).
event = event1;
try {
listener.call(this, this.__data__, index, group);
} finally {
event = event0;
}
};
}
function parseTypenames$1(typenames) {
return typenames.trim().split(/^|\s+/).map(function(t) {
var name = "", i = t.indexOf(".");
if (i >= 0) { name = t.slice(i + 1), t = t.slice(0, i); }
return {type: t, name: name};
});
}
function onRemove(typename) {
return function() {
var this$1 = this;
var on = this.__on;
if (!on) { return; }
for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
this$1.removeEventListener(o.type, o.listener, o.capture);
} else {
on[++i] = o;
}
}
if (++i) { on.length = i; }
else { delete this.__on; }
};
}
function onAdd(typename, value, capture) {
var wrap = filterEvents.hasOwnProperty(typename.type) ? filterContextListener : contextListener;
return function(d, i, group) {
var this$1 = this;
var on = this.__on, o, listener = wrap(value, i, group);
if (on) { for (var j = 0, m = on.length; j < m; ++j) {
if ((o = on[j]).type === typename.type && o.name === typename.name) {
this$1.removeEventListener(o.type, o.listener, o.capture);
this$1.addEventListener(o.type, o.listener = listener, o.capture = capture);
o.value = value;
return;
}
} }
this.addEventListener(typename.type, listener, capture);
o = {type: typename.type, name: typename.name, value: value, listener: listener, capture: capture};
if (!on) { this.__on = [o]; }
else { on.push(o); }
};
}
var selection_on = function(typename, value, capture) {
var this$1 = this;
var typenames = parseTypenames$1(typename + ""), i, n = typenames.length, t;
if (arguments.length < 2) {
var on = this.node().__on;
if (on) { for (var j = 0, m = on.length, o; j < m; ++j) {
for (i = 0, o = on[j]; i < n; ++i) {
if ((t = typenames[i]).type === o.type && t.name === o.name) {
return o.value;
}
}
} }
return;
}
on = value ? onAdd : onRemove;
if (capture == null) { capture = false; }
for (i = 0; i < n; ++i) { this$1.each(on(typenames[i], value, capture)); }
return this;
};
function none() {}
var selector = function(selector) {
return selector == null ? none : function() {
return this.querySelector(selector);
};
};
var selection_select = function(select) {
if (typeof select !== "function") { select = selector(select); }
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
if ("__data__" in node) { subnode.__data__ = node.__data__; }
subgroup[i] = subnode;
}
}
}
return new Selection(subgroups, this._parents);
};
function empty$1() {
return [];
}
var selectorAll = function(selector) {
return selector == null ? empty$1 : function() {
return this.querySelectorAll(selector);
};
};
var selection_selectAll = function(select) {
if (typeof select !== "function") { select = selectorAll(select); }
for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
if (node = group[i]) {
subgroups.push(select.call(node, node.__data__, i, group));
parents.push(node);
}
}
}
return new Selection(subgroups, parents);
};
var selection_filter = function(match) {
if (typeof match !== "function") { match = matcher$1(match); }
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
subgroup.push(node);
}
}
}
return new Selection(subgroups, this._parents);
};
var sparse = function(update) {
return new Array(update.length);
};
var selection_enter = function() {
return new Selection(this._enter || this._groups.map(sparse), this._parents);
};
function EnterNode(parent, datum) {
this.ownerDocument = parent.ownerDocument;
this.namespaceURI = parent.namespaceURI;
this._next = null;
this._parent = parent;
this.__data__ = datum;
}
EnterNode.prototype = {
constructor: EnterNode,
appendChild: function(child) { return this._parent.insertBefore(child, this._next); },
insertBefore: function(child, next) { return this._parent.insertBefore(child, next); },
querySelector: function(selector) { return this._parent.querySelector(selector); },
querySelectorAll: function(selector) { return this._parent.querySelectorAll(selector); }
};
var constant$1 = function(x) {
return function() {
return x;
};
};
var keyPrefix = "$"; // Protect against keys like “__proto__”.
function bindIndex(parent, group, enter, update, exit, data) {
var i = 0,
node,
groupLength = group.length,
dataLength = data.length;
// Put any non-null nodes that fit into update.
// Put any null nodes into enter.
// Put any remaining data into enter.
for (; i < dataLength; ++i) {
if (node = group[i]) {
node.__data__ = data[i];
update[i] = node;
} else {
enter[i] = new EnterNode(parent, data[i]);
}
}
// Put any non-null nodes that don’t fit into exit.
for (; i < groupLength; ++i) {
if (node = group[i]) {
exit[i] = node;
}
}
}
function bindKey(parent, group, enter, update, exit, data, key) {
var i,
node,
nodeByKeyValue = {},
groupLength = group.length,
dataLength = data.length,
keyValues = new Array(groupLength),
keyValue;
// Compute the key for each node.
// If multiple nodes have the same key, the duplicates are added to exit.
for (i = 0; i < groupLength; ++i) {
if (node = group[i]) {
keyValues[i] = keyValue = keyPrefix + key.call(node, node.__data__, i, group);
if (keyValue in nodeByKeyValue) {
exit[i] = node;
} else {
nodeByKeyValue[keyValue] = node;
}
}
}
// Compute the key for each datum.
// If there a node associated with this key, join and add it to update.
// If there is not (or the key is a duplicate), add it to enter.
for (i = 0; i < dataLength; ++i) {
keyValue = keyPrefix + key.call(parent, data[i], i, data);
if (node = nodeByKeyValue[keyValue]) {
update[i] = node;
node.__data__ = data[i];
nodeByKeyValue[keyValue] = null;
} else {
enter[i] = new EnterNode(parent, data[i]);
}
}
// Add any remaining nodes that were not bound to data to exit.
for (i = 0; i < groupLength; ++i) {
if ((node = group[i]) && (nodeByKeyValue[keyValues[i]] === node)) {
exit[i] = node;
}
}
}
var selection_data = function(value, key) {
if (!value) {
data = new Array(this.size()), j = -1;
this.each(function(d) { data[++j] = d; });
return data;
}
var bind = key ? bindKey : bindIndex,
parents = this._parents,
groups = this._groups;
if (typeof value !== "function") { value = constant$1(value); }
for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
var parent = parents[j],
group = groups[j],
groupLength = group.length,
data = value.call(parent, parent && parent.__data__, j, parents),
dataLength = data.length,
enterGroup = enter[j] = new Array(dataLength),
updateGroup = update[j] = new Array(dataLength),
exitGroup = exit[j] = new Array(groupLength);
bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);
// Now connect the enter nodes to their following update node, such that
// appendChild can insert the materialized enter node before this node,
// rather than at the end of the parent node.
for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
if (previous = enterGroup[i0]) {
if (i0 >= i1) { i1 = i0 + 1; }
while (!(next = updateGroup[i1]) && ++i1 < dataLength){ }
previous._next = next || null;
}
}
}
update = new Selection(update, parents);
update._enter = enter;
update._exit = exit;
return update;
};
var selection_exit = function() {
return new Selection(this._exit || this._groups.map(sparse), this._parents);
};
var selection_merge = function(selection$$1) {
for (var groups0 = this._groups, groups1 = selection$$1._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
if (node = group0[i] || group1[i]) {
merge[i] = node;
}
}
}
for (; j < m0; ++j) {
merges[j] = groups0[j];
}
return new Selection(merges, this._parents);
};
var selection_order = function() {
for (var groups = this._groups, j = -1, m = groups.length; ++j < m;) {
for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0;) {
if (node = group[i]) {
if (next && next !== node.nextSibling) { next.parentNode.insertBefore(node, next); }
next = node;
}
}
}
return this;
};
var selection_sort = function(compare) {
if (!compare) { compare = ascending$1; }
function compareNode(a, b) {
return a && b ? compare(a.__data__, b.__data__) : !a - !b;
}
for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
if (node = group[i]) {
sortgroup[i] = node;
}
}
sortgroup.sort(compareNode);
}
return new Selection(sortgroups, this._parents).order();
};
function ascending$1(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
var selection_call = function() {
var callback = arguments[0];
arguments[0] = this;
callback.apply(null, arguments);
return this;
};
var selection_nodes = function() {
var nodes = new Array(this.size()), i = -1;
this.each(function() { nodes[++i] = this; });
return nodes;
};
var selection_node = function() {
for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {
var node = group[i];
if (node) { return node; }
}
}
return null;
};
var selection_size = function() {
var size = 0;
this.each(function() { ++size; });
return size;
};
var selection_empty = function() {
return !this.node();
};
var selection_each = function(callback) {
for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
if (node = group[i]) { callback.call(node, node.__data__, i, group); }
}
}
return this;
};
function attrRemove(name) {
return function() {
this.removeAttribute(name);
};
}
function attrRemoveNS(fullname) {
return function() {
this.removeAttributeNS(fullname.space, fullname.local);
};
}
function attrConstant(name, value) {
return function() {
this.setAttribute(name, value);
};
}
function attrConstantNS(fullname, value) {
return function() {
this.setAttributeNS(fullname.space, fullname.local, value);
};
}
function attrFunction(name, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) { this.removeAttribute(name); }
else { this.setAttribute(name, v); }
};
}
function attrFunctionNS(fullname, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) { this.removeAttributeNS(fullname.space, fullname.local); }
else { this.setAttributeNS(fullname.space, fullname.local, v); }
};
}
var selection_attr = function(name, value) {
var fullname = namespace(name);
if (arguments.length < 2) {
var node = this.node();
return fullname.local
? node.getAttributeNS(fullname.space, fullname.local)
: node.getAttribute(fullname);
}
return this.each((value == null
? (fullname.local ? attrRemoveNS : attrRemove) : (typeof value === "function"
? (fullname.local ? attrFunctionNS : attrFunction)
: (fullname.local ? attrConstantNS : attrConstant)))(fullname, value));
};
var defaultView = function(node) {
return (node.ownerDocument && node.ownerDocument.defaultView) // node is a Node
|| (node.document && node) // node is a Window
|| node.defaultView; // node is a Document
};
function styleRemove(name) {
return function() {
this.style.removeProperty(name);
};
}
function styleConstant(name, value, priority) {
return function() {
this.style.setProperty(name, value, priority);
};
}
function styleFunction(name, value, priority) {
return function() {
var v = value.apply(this, arguments);
if (v == null) { this.style.removeProperty(name); }
else { this.style.setProperty(name, v, priority); }
};
}
var selection_style = function(name, value, priority) {
return arguments.length > 1
? this.each((value == null
? styleRemove : typeof value === "function"
? styleFunction
: styleConstant)(name, value, priority == null ? "" : priority))
: styleValue(this.node(), name);
};
function styleValue(node, name) {
return node.style.getPropertyValue(name)
|| defaultView(node).getComputedStyle(node, null).getPropertyValue(name);
}
function propertyRemove(name) {
return function() {
delete this[name];
};
}
function propertyConstant(name, value) {
return function() {
this[name] = value;
};
}
function propertyFunction(name, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) { delete this[name]; }
else { this[name] = v; }
};
}
var selection_property = function(name, value) {
return arguments.length > 1
? this.each((value == null
? propertyRemove : typeof value === "function"
? propertyFunction
: propertyConstant)(name, value))
: this.node()[name];
};
function classArray(string) {
return string.trim().split(/^|\s+/);
}
function classList(node) {
return node.classList || new ClassList(node);
}
function ClassList(node) {
this._node = node;
this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
add: function(name) {
var i = this._names.indexOf(name);
if (i < 0) {
this._names.push(name);
this._node.setAttribute("class", this._names.join(" "));
}
},
remove: function(name) {
var i = this._names.indexOf(name);
if (i >= 0) {
this._names.splice(i, 1);
this._node.setAttribute("class", this._names.join(" "));
}
},
contains: function(name) {
return this._names.indexOf(name) >= 0;
}
};
function classedAdd(node, names) {
var list = classList(node), i = -1, n = names.length;
while (++i < n) { list.add(names[i]); }
}
function classedRemove(node, names) {
var list = classList(node), i = -1, n = names.length;
while (++i < n) { list.remove(names[i]); }
}
function classedTrue(names) {
return function() {
classedAdd(this, names);
};
}
function classedFalse(names) {
return function() {
classedRemove(this, names);
};
}
function classedFunction(names, value) {
return function() {
(value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
};
}
var selection_classed = function(name, value) {
var names = classArray(name + "");
if (arguments.length < 2) {
var list = classList(this.node()), i = -1, n = names.length;
while (++i < n) { if (!list.contains(names[i])) { return false; } }
return true;
}
return this.each((typeof value === "function"
? classedFunction : value
? classedTrue
: classedFalse)(names, value));
};
function textRemove() {
this.textContent = "";
}
function textConstant(value) {
return function() {
this.textContent = value;
};
}
function textFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
};
}
var selection_text = function(value) {
return arguments.length
? this.each(value == null
? textRemove : (typeof value === "function"
? textFunction
: textConstant)(value))
: this.node().textContent;
};
function htmlRemove() {
this.innerHTML = "";
}
function htmlConstant(value) {
return function() {
this.innerHTML = value;
};
}
function htmlFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
};
}
var selection_html = function(value) {
return arguments.length
? this.each(value == null
? htmlRemove : (typeof value === "function"
? htmlFunction
: htmlConstant)(value))
: this.node().innerHTML;
};
function raise() {
if (this.nextSibling) { this.parentNode.appendChild(this); }
}
var selection_raise = function() {
return this.each(raise);
};
function lower() {
if (this.previousSibling) { this.parentNode.insertBefore(this, this.parentNode.firstChild); }
}
var selection_lower = function() {
return this.each(lower);
};
var selection_append = function(name) {
var create = typeof name === "function" ? name : creator(name);
return this.select(function() {
return this.appendChild(create.apply(this, arguments));
});
};
function constantNull() {
return null;
}
var selection_insert = function(name, before) {
var create = typeof name === "function" ? name : creator(name),
select = before == null ? constantNull : typeof before === "function" ? before : selector(before);
return this.select(function() {
return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
});
};
function remove() {
var parent = this.parentNode;
if (parent) { parent.removeChild(this); }
}
var selection_remove = function() {
return this.each(remove);
};
var selection_datum = function(value) {
return arguments.length
? this.property("__data__", value)
: this.node().__data__;
};
function dispatchEvent(node, type, params) {
var window = defaultView(node),
event = window.CustomEvent;
if (typeof event === "function") {
event = new event(type, params);
} else {
event = window.document.createEvent("Event");
if (params) { event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail; }
else { event.initEvent(type, false, false); }
}
node.dispatchEvent(event);
}
function dispatchConstant(type, params) {
return function() {
return dispatchEvent(this, type, params);
};
}
function dispatchFunction(type, params) {
return function() {
return dispatchEvent(this, type, params.apply(this, arguments));
};
}
var selection_dispatch = function(type, params) {
return this.each((typeof params === "function"
? dispatchFunction
: dispatchConstant)(type, params));
};
var root = [null];
function Selection(groups, parents) {
this._groups = groups;
this._parents = parents;
}
function selection() {
return new Selection([[document.documentElement]], root);
}
Selection.prototype = selection.prototype = {
constructor: Selection,
select: selection_select,
selectAll: selection_selectAll,
filter: selection_filter,
data: selection_data,
enter: selection_enter,
exit: selection_exit,
merge: selection_merge,
order: selection_order,
sort: selection_sort,
call: selection_call,
nodes: selection_nodes,
node: selection_node,
size: selection_size,
empty: selection_empty,
each: selection_each,
attr: selection_attr,
style: selection_style,
property: selection_property,
classed: selection_classed,
text: selection_text,
html: selection_html,
raise: selection_raise,
lower: selection_lower,
append: selection_append,
insert: selection_insert,
remove: selection_remove,
datum: selection_datum,
on: selection_on,
dispatch: selection_dispatch
};
var select = function(selector) {
return typeof selector === "string"
? new Selection([[document.querySelector(selector)]], [document.documentElement])
: new Selection([[selector]], root);
};
var define = function(constructor, factory, prototype) {
constructor.prototype = factory.prototype = prototype;
prototype.constructor = constructor;
};
function extend(parent, definition) {
var prototype = Object.create(parent.prototype);
for (var key in definition) { prototype[key] = definition[key]; }
return prototype;
}
function Color() {}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex3 = /^#([0-9a-f]{3})$/;
var reHex6 = /^#([0-9a-f]{6})$/;
var reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$");
var reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$");
var reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$");
var reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$");
var reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$");
var reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
var named = {
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,
rebeccapurple: 0x663399,
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
};
define(Color, color, {
displayable: function() {
return this.rgb().displayable();
},
toString: function() {
return this.rgb() + "";
}
});
function color(format) {
var m;
format = (format + "").trim().toLowerCase();
return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00
: (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000
: (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
: (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
: (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
: (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
: (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
: (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
: named.hasOwnProperty(format) ? rgbn(named[format])
: format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
: null;
}
function rgbn(n) {
return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}
function rgba(r, g, b, a) {
if (a <= 0) { r = g = b = NaN; }
return new Rgb(r, g, b, a);
}
function rgbConvert(o) {
if (!(o instanceof Color)) { o = color(o); }
if (!o) { return new Rgb; }
o = o.rgb();
return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r, g, b, opacity) {
return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}
function Rgb(r, g, b, opacity) {
this.r = +r;
this.g = +g;
this.b = +b;
this.opacity = +opacity;
}
define(Rgb, rgb, extend(Color, {
brighter: function(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
darker: function(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
rgb: function() {
return this;
},
displayable: function() {
return (0 <= this.r && this.r <= 255)
&& (0 <= this.g && this.g <= 255)
&& (0 <= this.b && this.b <= 255)
&& (0 <= this.opacity && this.opacity <= 1);
},
toString: function() {
var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
return (a === 1 ? "rgb(" : "rgba(")
+ Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
+ Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
+ Math.max(0, Math.min(255, Math.round(this.b) || 0))
+ (a === 1 ? ")" : ", " + a + ")");
}
}));
function hsla(h, s, l, a) {
if (a <= 0) { h = s = l = NaN; }
else if (l <= 0 || l >= 1) { h = s = NaN; }
else if (s <= 0) { h = NaN; }
return new Hsl(h, s, l, a);
}
function hslConvert(o) {
if (o instanceof Hsl) { return new Hsl(o.h, o.s, o.l, o.opacity); }
if (!(o instanceof Color)) { o = color(o); }
if (!o) { return new Hsl; }
if (o instanceof Hsl) { return o; }
o = o.rgb();
var r = o.r / 255,
g = o.g / 255,
b = o.b / 255,
min = Math.min(r, g, b),
max = Math.max(r, g, b),
h = NaN,
s = max - min,
l = (max + min) / 2;
if (s) {
if (r === max) { h = (g - b) / s + (g < b) * 6; }
else if (g === max) { h = (b - r) / s + 2; }
else { h = (r - g) / s + 4; }
s /= l < 0.5 ? max + min : 2 - max - min;
h *= 60;
} else {
s = l > 0 && l < 1 ? 0 : h;
}
return new Hsl(h, s, l, o.opacity);
}
function hsl(h, s, l, opacity) {
return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}
function Hsl(h, s, l, opacity) {
this.h = +h;
this.s = +s;
this.l = +l;
this.opacity = +opacity;
}
define(Hsl, hsl, extend(Color, {
brighter: function(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Hsl(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Hsl(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = this.h % 360 + (this.h < 0) * 360,
s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
l = this.l,
m2 = l + (l < 0.5 ? l : 1 - l) * s,
m1 = 2 * l - m2;
return new Rgb(
hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
hsl2rgb(h, m1, m2),
hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
this.opacity
);
},
displayable: function() {
return (0 <= this.s && this.s <= 1 || isNaN(this.s))
&& (0 <= this.l && this.l <= 1)
&& (0 <= this.opacity && this.opacity <= 1);
}
}));
/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
return (h < 60 ? m1 + (m2 - m1) * h / 60
: h < 180 ? m2
: h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
: m1) * 255;
}
var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;
var Kn = 18;
var Xn = 0.950470;
var Yn = 1;
var Zn = 1.088830;
var t0 = 4 / 29;
var t1 = 6 / 29;
var t2 = 3 * t1 * t1;
var t3 = t1 * t1 * t1;
function labConvert(o) {
if (o instanceof Lab) { return new Lab(o.l, o.a, o.b, o.opacity); }
if (o instanceof Hcl) {
var h = o.h * deg2rad;
return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
if (!(o instanceof Rgb)) { o = rgbConvert(o); }
var b = rgb2xyz(o.r),
a = rgb2xyz(o.g),
l = rgb2xyz(o.b),
x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn),
y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn),
z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn);
return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}
function lab(l, a, b, opacity) {
return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}
function Lab(l, a, b, opacity) {
this.l = +l;
this.a = +a;
this.b = +b;
this.opacity = +opacity;
}
define(Lab, lab, extend(Color, {
brighter: function(k) {
return new Lab(this.l + Kn * (k == null ? 1 : k), this.a, this.b, this.opacity);
},
darker: function(k) {
return new Lab(this.l - Kn * (k == null ? 1 : k), this.a, this.b, this.opacity);
},
rgb: function() {
var y = (this.l + 16) / 116,
x = isNaN(this.a) ? y : y + this.a / 500,
z = isNaN(this.b) ? y : y - this.b / 200;
y = Yn * lab2xyz(y);
x = Xn * lab2xyz(x);
z = Zn * lab2xyz(z);
return new Rgb(
xyz2rgb( 3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB
xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z),
xyz2rgb( 0.0556434 * x - 0.2040259 * y + 1.0572252 * z),
this.opacity
);
}
}));
function xyz2lab(t) {
return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}
function lab2xyz(t) {
return t > t1 ? t * t * t : t2 * (t - t0);
}
function xyz2rgb(x) {
return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}
function rgb2xyz(x) {
return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function hclConvert(o) {
if (o instanceof Hcl) { return new Hcl(o.h, o.c, o.l, o.opacity); }
if (!(o instanceof Lab)) { o = labConvert(o); }
var h = Math.atan2(o.b, o.a) * rad2deg;
return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function hcl(h, c, l, opacity) {
return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function Hcl(h, c, l, opacity) {
this.h = +h;
this.c = +c;
this.l = +l;
this.opacity = +opacity;
}
define(Hcl, hcl, extend(Color, {
brighter: function(k) {
return new Hcl(this.h, this.c, this.l + Kn * (k == null ? 1 : k), this.opacity);
},
darker: function(k) {
return new Hcl(this.h, this.c, this.l - Kn * (k == null ? 1 : k), this.opacity);
},
rgb: function() {
return labConvert(this).rgb();
}
}));
var A = -0.14861;
var B = +1.78277;
var C = -0.29227;
var D = -0.90649;
var E = +1.97294;
var ED = E * D;
var EB = E * B;
var BC_DA = B * C - D * A;
function cubehelixConvert(o) {
if (o instanceof Cubehelix) { return new Cubehelix(o.h, o.s, o.l, o.opacity); }
if (!(o instanceof Rgb)) { o = rgbConvert(o); }
var r = o.r / 255,
g = o.g / 255,
b = o.b / 255,
l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
bl = b - l,
k = (E * (g - l) - C * bl) / D,
s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}
function cubehelix(h, s, l, opacity) {
return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}
function Cubehelix(h, s, l, opacity) {
this.h = +h;
this.s = +s;
this.l = +l;
this.opacity = +opacity;
}
define(Cubehelix, cubehelix, extend(Color, {
brighter: function(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
l = +this.l,
a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
cosh = Math.cos(h),
sinh = Math.sin(h);
return new Rgb(
255 * (l + a * (A * cosh + B * sinh)),
255 * (l + a * (C * cosh + D * sinh)),
255 * (l + a * (E * cosh)),
this.opacity
);
}
}));
function basis(t1, v0, v1, v2, v3) {
var t2 = t1 * t1, t3 = t2 * t1;
return ((1 - 3 * t1 + 3 * t2 - t3) * v0
+ (4 - 6 * t2 + 3 * t3) * v1
+ (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
+ t3 * v3) / 6;
}
var constant$3 = function(x) {
return function() {
return x;
};
};
function linear(a, d) {
return function(t) {
return a + t * d;
};
}
function exponential(a, b, y) {
return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
return Math.pow(a + t * b, y);
};
}
function hue(a, b) {
var d = b - a;
return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant$3(isNaN(a) ? b : a);
}
function gamma(y) {
return (y = +y) === 1 ? nogamma : function(a, b) {
return b - a ? exponential(a, b, y) : constant$3(isNaN(a) ? b : a);
};
}
function nogamma(a, b) {
var d = b - a;
return d ? linear(a, d) : constant$3(isNaN(a) ? b : a);
}
var interpolateRgb = ((function rgbGamma(y) {
var color$$1 = gamma(y);
function rgb$$1(start, end) {
var r = color$$1((start = rgb(start)).r, (end = rgb(end)).r),
g = color$$1(start.g, end.g),
b = color$$1(start.b, end.b),
opacity = nogamma(start.opacity, end.opacity);
return function(t) {
start.r = r(t);
start.g = g(t);
start.b = b(t);
start.opacity = opacity(t);
return start + "";
};
}
rgb$$1.gamma = rgbGamma;
return rgb$$1;
}))(1);
var array$1 = function(a, b) {
var nb = b ? b.length : 0,
na = a ? Math.min(nb, a.length) : 0,
x = new Array(nb),
c = new Array(nb),
i;
for (i = 0; i < na; ++i) { x[i] = interpolateValue(a[i], b[i]); }
for (; i < nb; ++i) { c[i] = b[i]; }
return function(t) {
for (i = 0; i < na; ++i) { c[i] = x[i](t); }
return c;
};
};
var date = function(a, b) {
var d = new Date;
return a = +a, b -= a, function(t) {
return d.setTime(a + b * t), d;
};
};
var reinterpolate = function(a, b) {
return a = +a, b -= a, function(t) {
return a + b * t;
};
};
var object = function(a, b) {
var i = {},
c = {},
k;
if (a === null || typeof a !== "object") { a = {}; }
if (b === null || typeof b !== "object") { b = {}; }
for (k in b) {
if (k in a) {
i[k] = interpolateValue(a[k], b[k]);
} else {
c[k] = b[k];
}
}
return function(t) {
for (k in i) { c[k] = i[k](t); }
return c;
};
};
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var reB = new RegExp(reA.source, "g");
function zero(b) {
return function() {
return b;
};
}
function one(b) {
return function(t) {
return b(t) + "";
};
}
var interpolateString = function(a, b) {
var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
am, // current match in a
bm, // current match in b
bs, // string preceding current number in b, if any
i = -1, // index in s
s = [], // string constants and placeholders
q = []; // number interpolators
// Coerce inputs to strings.
a = a + "", b = b + "";
// Interpolate pairs of numbers in a & b.
while ((am = reA.exec(a))
&& (bm = reB.exec(b))) {
if ((bs = bm.index) > bi) { // a string precedes the next number in b
bs = b.slice(bi, bs);
if (s[i]) { s[i] += bs; } // coalesce with previous string
else { s[++i] = bs; }
}
if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
if (s[i]) { s[i] += bm; } // coalesce with previous string
else { s[++i] = bm; }
} else { // interpolate non-matching numbers
s[++i] = null;
q.push({i: i, x: reinterpolate(am, bm)});
}
bi = reB.lastIndex;
}
// Add remains of b.
if (bi < b.length) {
bs = b.slice(bi);
if (s[i]) { s[i] += bs; } // coalesce with previous string
else { s[++i] = bs; }
}
// Special optimization for only a single match.
// Otherwise, interpolate each of the numbers and rejoin the string.
return s.length < 2 ? (q[0]
? one(q[0].x)
: zero(b))
: (b = q.length, function(t) {
for (var i = 0, o; i < b; ++i) { s[(o = q[i]).i] = o.x(t); }
return s.join("");
});
};
var interpolateValue = function(a, b) {
var t = typeof b, c;
return b == null || t === "boolean" ? constant$3(b)
: (t === "number" ? reinterpolate
: t === "string" ? ((c = color(b)) ? (b = c, interpolateRgb) : interpolateString)
: b instanceof color ? interpolateRgb
: b instanceof Date ? date
: Array.isArray(b) ? array$1
: typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
: reinterpolate)(a, b);
};
var interpolateRound = function(a, b) {
return a = +a, b -= a, function(t) {
return Math.round(a + b * t);
};
};
var degrees = 180 / Math.PI;
var identity$2 = {
translateX: 0,
translateY: 0,
rotate: 0,
skewX: 0,
scaleX: 1,
scaleY: 1
};
var decompose = function(a, b, c, d, e, f) {
var scaleX, scaleY, skewX;
if (scaleX = Math.sqrt(a * a + b * b)) { a /= scaleX, b /= scaleX; }
if (skewX = a * c + b * d) { c -= a * skewX, d -= b * skewX; }
if (scaleY = Math.sqrt(c * c + d * d)) { c /= scaleY, d /= scaleY, skewX /= scaleY; }
if (a * d < b * c) { a = -a, b = -b, skewX = -skewX, scaleX = -scaleX; }
return {
translateX: e,
translateY: f,
rotate: Math.atan2(b, a) * degrees,
skewX: Math.atan(skewX) * degrees,
scaleX: scaleX,
scaleY: scaleY
};
};
var cssNode;
var cssRoot;
var cssView;
var svgNode;
function parseCss(value) {
if (value === "none") { return identity$2; }
if (!cssNode) { cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView; }
cssNode.style.transform = value;
value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue("transform");
cssRoot.removeChild(cssNode);
value = value.slice(7, -1).split(",");
return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);
}
function parseSvg(value) {
if (value == null) { return identity$2; }
if (!svgNode) { svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g"); }
svgNode.setAttribute("transform", value);
if (!(value = svgNode.transform.baseVal.consolidate())) { return identity$2; }
value = value.matrix;
return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}
function interpolateTransform(parse, pxComma, pxParen, degParen) {
function pop(s) {
return s.length ? s.pop() + " " : "";
}
function translate(xa, ya, xb, yb, s, q) {
if (xa !== xb || ya !== yb) {
var i = s.push("translate(", null, pxComma, null, pxParen);
q.push({i: i - 4, x: reinterpolate(xa, xb)}, {i: i - 2, x: reinterpolate(ya, yb)});
} else if (xb || yb) {
s.push("translate(" + xb + pxComma + yb + pxParen);
}
}
function rotate(a, b, s, q) {
if (a !== b) {
if (a - b > 180) { b += 360; } else if (b - a > 180) { a += 360; } // shortest path
q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: reinterpolate(a, b)});
} else if (b) {
s.push(pop(s) + "rotate(" + b + degParen);
}
}
function skewX(a, b, s, q) {
if (a !== b) {
q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: reinterpolate(a, b)});
} else if (b) {
s.push(pop(s) + "skewX(" + b + degParen);
}
}
function scale(xa, ya, xb, yb, s, q) {
if (xa !== xb || ya !== yb) {
var i = s.push(pop(s) + "scale(", null, ",", null, ")");
q.push({i: i - 4, x: reinterpolate(xa, xb)}, {i: i - 2, x: reinterpolate(ya, yb)});
} else if (xb !== 1 || yb !== 1) {
s.push(pop(s) + "scale(" + xb + "," + yb + ")");
}
}
return function(a, b) {
var s = [], // string constants and placeholders
q = []; // number interpolators
a = parse(a), b = parse(b);
translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
rotate(a.rotate, b.rotate, s, q);
skewX(a.skewX, b.skewX, s, q);
scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
a = b = null; // gc
return function(t) {
var i = -1, n = q.length, o;
while (++i < n) { s[(o = q[i]).i] = o.x(t); }
return s.join("");
};
};
}
var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");
// p0 = [ux0, uy0, w0]
// p1 = [ux1, uy1, w1]
function cubehelix$1(hue$$1) {
return (function cubehelixGamma(y) {
y = +y;
function cubehelix$$1(start, end) {
var h = hue$$1((start = cubehelix(start)).h, (end = cubehelix(end)).h),
s = nogamma(start.s, end.s),
l = nogamma(start.l, end.l),
opacity = nogamma(start.opacity, end.opacity);
return function(t) {
start.h = h(t);
start.s = s(t);
start.l = l(Math.pow(t, y));
start.opacity = opacity(t);
return start + "";
};
}
cubehelix$$1.gamma = cubehelixGamma;
return cubehelix$$1;
})(1);
}
cubehelix$1(hue);
var cubehelixLong = cubehelix$1(nogamma);
var frame = 0;
var timeout = 0;
var interval = 0;
var pokeDelay = 1000;
var taskHead;
var taskTail;
var clockLast = 0;
var clockNow = 0;
var clockSkew = 0;
var clock = typeof performance === "object" && performance.now ? performance : Date;
var setFrame = typeof requestAnimationFrame === "function" ? requestAnimationFrame : function(f) { setTimeout(f, 17); };
function now() {
return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}
function clearNow() {
clockNow = 0;
}
function Timer() {
this._call =
this._time =
this._next = null;
}
Timer.prototype = timer.prototype = {
constructor: Timer,
restart: function(callback, delay, time) {
if (typeof callback !== "function") { throw new TypeError("callback is not a function"); }
time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
if (!this._next && taskTail !== this) {
if (taskTail) { taskTail._next = this; }
else { taskHead = this; }
taskTail = this;
}
this._call = callback;
this._time = time;
sleep();
},
stop: function() {
if (this._call) {
this._call = null;
this._time = Infinity;
sleep();
}
}
};
function timer(callback, delay, time) {
var t = new Timer;
t.restart(callback, delay, time);
return t;
}
function timerFlush() {
now(); // Get the current time, if not already set.
++frame; // Pretend we’ve set an alarm, if we haven’t already.
var t = taskHead, e;
while (t) {
if ((e = clockNow - t._time) >= 0) { t._call.call(null, e); }
t = t._next;
}
--frame;
}
function wake() {
clockNow = (clockLast = clock.now()) + clockSkew;
frame = timeout = 0;
try {
timerFlush();
} finally {
frame = 0;
nap();
clockNow = 0;
}
}
function poke() {
var now = clock.now(), delay = now - clockLast;
if (delay > pokeDelay) { clockSkew -= delay, clockLast = now; }
}
function nap() {
var t0, t1 = taskHead, t2, time = Infinity;
while (t1) {
if (t1._call) {
if (time > t1._time) { time = t1._time; }
t0 = t1, t1 = t1._next;
} else {
t2 = t1._next, t1._next = null;
t1 = t0 ? t0._next = t2 : taskHead = t2;
}
}
taskTail = t0;
sleep(time);
}
function sleep(time) {
if (frame) { return; } // Soonest alarm already set, or will be.
if (timeout) { timeout = clearTimeout(timeout); }
var delay = time - clockNow;
if (delay > 24) {
if (time < Infinity) { timeout = setTimeout(wake, delay); }
if (interval) { interval = clearInterval(interval); }
} else {
if (!interval) { clockLast = clockNow, interval = setInterval(poke, pokeDelay); }
frame = 1, setFrame(wake);
}
}
var timeout$1 = function(callback, delay, time) {
var t = new Timer;
delay = delay == null ? 0 : +delay;
t.restart(function(elapsed) {
t.stop();
callback(elapsed + delay);
}, delay, time);
return t;
};
var emptyOn = dispatch("start", "end", "interrupt");
var emptyTween = [];
var CREATED = 0;
var SCHEDULED = 1;
var STARTING = 2;
var STARTED = 3;
var RUNNING = 4;
var ENDING = 5;
var ENDED = 6;
var schedule = function(node, name, id, index, group, timing) {
var schedules = node.__transition;
if (!schedules) { node.__transition = {}; }
else if (id in schedules) { return; }
create(node, id, {
name: name,
index: index, // For context during callback.
group: group, // For context during callback.
on: emptyOn,
tween: emptyTween,
time: timing.time,
delay: timing.delay,
duration: timing.duration,
ease: timing.ease,
timer: null,
state: CREATED
});
};
function init(node, id) {
var schedule = node.__transition;
if (!schedule || !(schedule = schedule[id]) || schedule.state > CREATED) { throw new Error("too late"); }
return schedule;
}
function set$1(node, id) {
var schedule = node.__transition;
if (!schedule || !(schedule = schedule[id]) || schedule.state > STARTING) { throw new Error("too late"); }
return schedule;
}
function get$1(node, id) {
var schedule = node.__transition;
if (!schedule || !(schedule = schedule[id])) { throw new Error("too late"); }
return schedule;
}
function create(node, id, self) {
var schedules = node.__transition,
tween;
// Initialize the self timer when the transition is created.
// Note the actual delay is not known until the first callback!
schedules[id] = self;
self.timer = timer(schedule, 0, self.time);
function schedule(elapsed) {
self.state = SCHEDULED;
self.timer.restart(start, self.delay, self.time);
// If the elapsed delay is less than our first sleep, start immediately.
if (self.delay <= elapsed) { start(elapsed - self.delay); }
}
function start(elapsed) {
var i, j, n, o;
// If the state is not SCHEDULED, then we previously errored on start.
if (self.state !== SCHEDULED) { return stop(); }
for (i in schedules) {
o = schedules[i];
if (o.name !== self.name) { continue; }
// While this element already has a starting transition during this frame,
// defer starting an interrupting transition until that transition has a
// chance to tick (and possibly end); see d3/d3-transition#54!
if (o.state === STARTED) { return timeout$1(start); }
// Interrupt the active transition, if any.
// Dispatch the interrupt event.
if (o.state === RUNNING) {
o.state = ENDED;
o.timer.stop();
o.on.call("interrupt", node, node.__data__, o.index, o.group);
delete schedules[i];
}
// Cancel any pre-empted transitions. No interrupt event is dispatched
// because the cancelled transitions never started. Note that this also
// removes this transition from the pending list!
else if (+i < id) {
o.state = ENDED;
o.timer.stop();
delete schedules[i];
}
}
// Defer the first tick to end of the current frame; see d3/d3#1576.
// Note the transition may be canceled after start and before the first tick!
// Note this must be scheduled before the start event; see d3/d3-transition#16!
// Assuming this is successful, subsequent callbacks go straight to tick.
timeout$1(function() {
if (self.state === STARTED) {
self.state = RUNNING;
self.timer.restart(tick, self.delay, self.time);
tick(elapsed);
}
});
// Dispatch the start event.
// Note this must be done before the tween are initialized.
self.state = STARTING;
self.on.call("start", node, node.__data__, self.index, self.group);
if (self.state !== STARTING) { return; } // interrupted
self.state = STARTED;
// Initialize the tween, deleting null tween.
tween = new Array(n = self.tween.length);
for (i = 0, j = -1; i < n; ++i) {
if (o = self.tween[i].value.call(node, node.__data__, self.index, self.group)) {
tween[++j] = o;
}
}
tween.length = j + 1;
}
function tick(elapsed) {
var t = elapsed < self.duration ? self.ease.call(null, elapsed / self.duration) : (self.timer.restart(stop), self.state = ENDING, 1),
i = -1,
n = tween.length;
while (++i < n) {
tween[i].call(null, t);
}
// Dispatch the end event.
if (self.state === ENDING) {
self.on.call("end", node, node.__data__, self.index, self.group);
stop();
}
}
function stop() {
self.state = ENDED;
self.timer.stop();
delete schedules[id];
for (var i in schedules) { return; } // eslint-disable-line no-unused-vars
delete node.__transition;
}
}
var interrupt = function(node, name) {
var schedules = node.__transition,
schedule$$1,
active,
empty = true,
i;
if (!schedules) { return; }
name = name == null ? null : name + "";
for (i in schedules) {
if ((schedule$$1 = schedules[i]).name !== name) { empty = false; continue; }
active = schedule$$1.state > STARTING && schedule$$1.state < ENDING;
schedule$$1.state = ENDED;
schedule$$1.timer.stop();
if (active) { schedule$$1.on.call("interrupt", node, node.__data__, schedule$$1.index, schedule$$1.group); }
delete schedules[i];
}
if (empty) { delete node.__transition; }
};
var selection_interrupt = function(name) {
return this.each(function() {
interrupt(this, name);
});
};
function tweenRemove(id, name) {
var tween0, tween1;
return function() {
var schedule$$1 = set$1(this, id),
tween = schedule$$1.tween;
// If this node shared tween with the previous node,
// just assign the updated shared tween and we’re done!
// Otherwise, copy-on-write.
if (tween !== tween0) {
tween1 = tween0 = tween;
for (var i = 0, n = tween1.length; i < n; ++i) {
if (tween1[i].name === name) {
tween1 = tween1.slice();
tween1.splice(i, 1);
break;
}
}
}
schedule$$1.tween = tween1;
};
}
function tweenFunction(id, name, value) {
var tween0, tween1;
if (typeof value !== "function") { throw new Error; }
return function() {
var schedule$$1 = set$1(this, id),
tween = schedule$$1.tween;
// If this node shared tween with the previous node,
// just assign the updated shared tween and we’re done!
// Otherwise, copy-on-write.
if (tween !== tween0) {
tween1 = (tween0 = tween).slice();
for (var t = {name: name, value: value}, i = 0, n = tween1.length; i < n; ++i) {
if (tween1[i].name === name) {
tween1[i] = t;
break;
}
}
if (i === n) { tween1.push(t); }
}
schedule$$1.tween = tween1;
};
}
var transition_tween = function(name, value) {
var id = this._id;
name += "";
if (arguments.length < 2) {
var tween = get$1(this.node(), id).tween;
for (var i = 0, n = tween.length, t; i < n; ++i) {
if ((t = tween[i]).name === name) {
return t.value;
}
}
return null;
}
return this.each((value == null ? tweenRemove : tweenFunction)(id, name, value));
};
function tweenValue(transition, name, value) {
var id = transition._id;
transition.each(function() {
var schedule$$1 = set$1(this, id);
(schedule$$1.value || (schedule$$1.value = {}))[name] = value.apply(this, arguments);
});
return function(node) {
return get$1(node, id).value[name];
};
}
var interpolate = function(a, b) {
var c;
return (typeof b === "number" ? reinterpolate
: b instanceof color ? interpolateRgb
: (c = color(b)) ? (b = c, interpolateRgb)
: interpolateString)(a, b);
};
function attrRemove$1(name) {
return function() {
this.removeAttribute(name);
};
}
function attrRemoveNS$1(fullname) {
return function() {
this.removeAttributeNS(fullname.space, fullname.local);
};
}
function attrConstant$1(name, interpolate$$1, value1) {
var value00,
interpolate0;
return function() {
var value0 = this.getAttribute(name);
return value0 === value1 ? null
: value0 === value00 ? interpolate0
: interpolate0 = interpolate$$1(value00 = value0, value1);
};
}
function attrConstantNS$1(fullname, interpolate$$1, value1) {
var value00,
interpolate0;
return function() {
var value0 = this.getAttributeNS(fullname.space, fullname.local);
return value0 === value1 ? null
: value0 === value00 ? interpolate0
: interpolate0 = interpolate$$1(value00 = value0, value1);
};
}
function attrFunction$1(name, interpolate$$1, value) {
var value00,
value10,
interpolate0;
return function() {
var value0, value1 = value(this);
if (value1 == null) { return void this.removeAttribute(name); }
value0 = this.getAttribute(name);
return value0 === value1 ? null
: value0 === value00 && value1 === value10 ? interpolate0
: interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
};
}
function attrFunctionNS$1(fullname, interpolate$$1, value) {
var value00,
value10,
interpolate0;
return function() {
var value0, value1 = value(this);
if (value1 == null) { return void this.removeAttributeNS(fullname.space, fullname.local); }
value0 = this.getAttributeNS(fullname.space, fullname.local);
return value0 === value1 ? null
: value0 === value00 && value1 === value10 ? interpolate0
: interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
};
}
var transition_attr = function(name, value) {
var fullname = namespace(name), i = fullname === "transform" ? interpolateTransformSvg : interpolate;
return this.attrTween(name, typeof value === "function"
? (fullname.local ? attrFunctionNS$1 : attrFunction$1)(fullname, i, tweenValue(this, "attr." + name, value))
: value == null ? (fullname.local ? attrRemoveNS$1 : attrRemove$1)(fullname)
: (fullname.local ? attrConstantNS$1 : attrConstant$1)(fullname, i, value + ""));
};
function attrTweenNS(fullname, value) {
function tween() {
var node = this, i = value.apply(node, arguments);
return i && function(t) {
node.setAttributeNS(fullname.space, fullname.local, i(t));
};
}
tween._value = value;
return tween;
}
function attrTween(name, value) {
function tween() {
var node = this, i = value.apply(node, arguments);
return i && function(t) {
node.setAttribute(name, i(t));
};
}
tween._value = value;
return tween;
}
var transition_attrTween = function(name, value) {
var key = "attr." + name;
if (arguments.length < 2) { return (key = this.tween(key)) && key._value; }
if (value == null) { return this.tween(key, null); }
if (typeof value !== "function") { throw new Error; }
var fullname = namespace(name);
return this.tween(key, (fullname.local ? attrTweenNS : attrTween)(fullname, value));
};
function delayFunction(id, value) {
return function() {
init(this, id).delay = +value.apply(this, arguments);
};
}
function delayConstant(id, value) {
return value = +value, function() {
init(this, id).delay = value;
};
}
var transition_delay = function(value) {
var id = this._id;
return arguments.length
? this.each((typeof value === "function"
? delayFunction
: delayConstant)(id, value))
: get$1(this.node(), id).delay;
};
function durationFunction(id, value) {
return function() {
set$1(this, id).duration = +value.apply(this, arguments);
};
}
function durationConstant(id, value) {
return value = +value, function() {
set$1(this, id).duration = value;
};
}
var transition_duration = function(value) {
var id = this._id;
return arguments.length
? this.each((typeof value === "function"
? durationFunction
: durationConstant)(id, value))
: get$1(this.node(), id).duration;
};
function easeConstant(id, value) {
if (typeof value !== "function") { throw new Error; }
return function() {
set$1(this, id).ease = value;
};
}
var transition_ease = function(value) {
var id = this._id;
return arguments.length
? this.each(easeConstant(id, value))
: get$1(this.node(), id).ease;
};
var transition_filter = function(match) {
if (typeof match !== "function") { match = matcher$1(match); }
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
subgroup.push(node);
}
}
}
return new Transition(subgroups, this._parents, this._name, this._id);
};
var transition_merge = function(transition$$1) {
if (transition$$1._id !== this._id) { throw new Error; }
for (var groups0 = this._groups, groups1 = transition$$1._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
if (node = group0[i] || group1[i]) {
merge[i] = node;
}
}
}
for (; j < m0; ++j) {
merges[j] = groups0[j];
}
return new Transition(merges, this._parents, this._name, this._id);
};
function start(name) {
return (name + "").trim().split(/^|\s+/).every(function(t) {
var i = t.indexOf(".");
if (i >= 0) { t = t.slice(0, i); }
return !t || t === "start";
});
}
function onFunction(id, name, listener) {
var on0, on1, sit = start(name) ? init : set$1;
return function() {
var schedule$$1 = sit(this, id),
on = schedule$$1.on;
// If this node shared a dispatch with the previous node,
// just assign the updated shared dispatch and we’re done!
// Otherwise, copy-on-write.
if (on !== on0) { (on1 = (on0 = on).copy()).on(name, listener); }
schedule$$1.on = on1;
};
}
var transition_on = function(name, listener) {
var id = this._id;
return arguments.length < 2
? get$1(this.node(), id).on.on(name)
: this.each(onFunction(id, name, listener));
};
function removeFunction(id) {
return function() {
var this$1 = this;
var parent = this.parentNode;
for (var i in this$1.__transition) { if (+i !== id) { return; } }
if (parent) { parent.removeChild(this); }
};
}
var transition_remove = function() {
return this.on("end.remove", removeFunction(this._id));
};
var transition_select = function(select$$1) {
var name = this._name,
id = this._id;
if (typeof select$$1 !== "function") { select$$1 = selector(select$$1); }
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
if ((node = group[i]) && (subnode = select$$1.call(node, node.__data__, i, group))) {
if ("__data__" in node) { subnode.__data__ = node.__data__; }
subgroup[i] = subnode;
schedule(subgroup[i], name, id, i, subgroup, get$1(node, id));
}
}
}
return new Transition(subgroups, this._parents, name, id);
};
var transition_selectAll = function(select$$1) {
var name = this._name,
id = this._id;
if (typeof select$$1 !== "function") { select$$1 = selectorAll(select$$1); }
for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
if (node = group[i]) {
for (var children = select$$1.call(node, node.__data__, i, group), child, inherit = get$1(node, id), k = 0, l = children.length; k < l; ++k) {
if (child = children[k]) {
schedule(child, name, id, k, children, inherit);
}
}
subgroups.push(children);
parents.push(node);
}
}
}
return new Transition(subgroups, parents, name, id);
};
var Selection$1 = selection.prototype.constructor;
var transition_selection = function() {
return new Selection$1(this._groups, this._parents);
};
function styleRemove$1(name, interpolate$$1) {
var value00,
value10,
interpolate0;
return function() {
var value0 = styleValue(this, name),
value1 = (this.style.removeProperty(name), styleValue(this, name));
return value0 === value1 ? null
: value0 === value00 && value1 === value10 ? interpolate0
: interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
};
}
function styleRemoveEnd(name) {
return function() {
this.style.removeProperty(name);
};
}
function styleConstant$1(name, interpolate$$1, value1) {
var value00,
interpolate0;
return function() {
var value0 = styleValue(this, name);
return value0 === value1 ? null
: value0 === value00 ? interpolate0
: interpolate0 = interpolate$$1(value00 = value0, value1);
};
}
function styleFunction$1(name, interpolate$$1, value) {
var value00,
value10,
interpolate0;
return function() {
var value0 = styleValue(this, name),
value1 = value(this);
if (value1 == null) { value1 = (this.style.removeProperty(name), styleValue(this, name)); }
return value0 === value1 ? null
: value0 === value00 && value1 === value10 ? interpolate0
: interpolate0 = interpolate$$1(value00 = value0, value10 = value1);
};
}
var transition_style = function(name, value, priority) {
var i = (name += "") === "transform" ? interpolateTransformCss : interpolate;
return value == null ? this
.styleTween(name, styleRemove$1(name, i))
.on("end.style." + name, styleRemoveEnd(name))
: this.styleTween(name, typeof value === "function"
? styleFunction$1(name, i, tweenValue(this, "style." + name, value))
: styleConstant$1(name, i, value + ""), priority);
};
function styleTween(name, value, priority) {
function tween() {
var node = this, i = value.apply(node, arguments);
return i && function(t) {
node.style.setProperty(name, i(t), priority);
};
}
tween._value = value;
return tween;
}
var transition_styleTween = function(name, value, priority) {
var key = "style." + (name += "");
if (arguments.length < 2) { return (key = this.tween(key)) && key._value; }
if (value == null) { return this.tween(key, null); }
if (typeof value !== "function") { throw new Error; }
return this.tween(key, styleTween(name, value, priority == null ? "" : priority));
};
function textConstant$1(value) {
return function() {
this.textContent = value;
};
}
function textFunction$1(value) {
return function() {
var value1 = value(this);
this.textContent = value1 == null ? "" : value1;
};
}
var transition_text = function(value) {
return this.tween("text", typeof value === "function"
? textFunction$1(tweenValue(this, "text", value))
: textConstant$1(value == null ? "" : value + ""));
};
var transition_transition = function() {
var name = this._name,
id0 = this._id,
id1 = newId();
for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
if (node = group[i]) {
var inherit = get$1(node, id0);
schedule(node, name, id1, i, group, {
time: inherit.time + inherit.delay + inherit.duration,
delay: 0,
duration: inherit.duration,
ease: inherit.ease
});
}
}
}
return new Transition(groups, this._parents, name, id1);
};
var id = 0;
function Transition(groups, parents, name, id) {
this._groups = groups;
this._parents = parents;
this._name = name;
this._id = id;
}
function transition(name) {
return selection().transition(name);
}
function newId() {
return ++id;
}
var selection_prototype = selection.prototype;
Transition.prototype = transition.prototype = {
constructor: Transition,
select: transition_select,
selectAll: transition_selectAll,
filter: transition_filter,
merge: transition_merge,
selection: transition_selection,
transition: transition_transition,
call: selection_prototype.call,
nodes: selection_prototype.nodes,
node: selection_prototype.node,
size: selection_prototype.size,
empty: selection_prototype.empty,
each: selection_prototype.each,
on: transition_on,
attr: transition_attr,
attrTween: transition_attrTween,
style: transition_style,
styleTween: transition_styleTween,
text: transition_text,
remove: transition_remove,
tween: transition_tween,
delay: transition_delay,
duration: transition_duration,
ease: transition_ease
};
function cubicInOut(t) {
return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}
var exponent = 3;
var polyIn = (function custom(e) {
e = +e;
function polyIn(t) {
return Math.pow(t, e);
}
polyIn.exponent = custom;
return polyIn;
})(exponent);
var polyOut = (function custom(e) {
e = +e;
function polyOut(t) {
return 1 - Math.pow(1 - t, e);
}
polyOut.exponent = custom;
return polyOut;
})(exponent);
var polyInOut = (function custom(e) {
e = +e;
function polyInOut(t) {
return ((t *= 2) <= 1 ? Math.pow(t, e) : 2 - Math.pow(2 - t, e)) / 2;
}
polyInOut.exponent = custom;
return polyInOut;
})(exponent);
var overshoot = 1.70158;
var backIn = (function custom(s) {
s = +s;
function backIn(t) {
return t * t * ((s + 1) * t - s);
}
backIn.overshoot = custom;
return backIn;
})(overshoot);
var backOut = (function custom(s) {
s = +s;
function backOut(t) {
return --t * t * ((s + 1) * t + s) + 1;
}
backOut.overshoot = custom;
return backOut;
})(overshoot);
var backInOut = (function custom(s) {
s = +s;
function backInOut(t) {
return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2;
}
backInOut.overshoot = custom;
return backInOut;
})(overshoot);
var tau = 2 * Math.PI;
var amplitude = 1;
var period = 0.3;
var elasticIn = (function custom(a, p) {
var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
function elasticIn(t) {
return a * Math.pow(2, 10 * --t) * Math.sin((s - t) / p);
}
elasticIn.amplitude = function(a) { return custom(a, p * tau); };
elasticIn.period = function(p) { return custom(a, p); };
return elasticIn;
})(amplitude, period);
var elasticOut = (function custom(a, p) {
var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
function elasticOut(t) {
return 1 - a * Math.pow(2, -10 * (t = +t)) * Math.sin((t + s) / p);
}
elasticOut.amplitude = function(a) { return custom(a, p * tau); };
elasticOut.period = function(p) { return custom(a, p); };
return elasticOut;
})(amplitude, period);
var elasticInOut = (function custom(a, p) {
var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
function elasticInOut(t) {
return ((t = t * 2 - 1) < 0
? a * Math.pow(2, 10 * t) * Math.sin((s - t) / p)
: 2 - a * Math.pow(2, -10 * t) * Math.sin((s + t) / p)) / 2;
}
elasticInOut.amplitude = function(a) { return custom(a, p * tau); };
elasticInOut.period = function(p) { return custom(a, p); };
return elasticInOut;
})(amplitude, period);
var defaultTiming = {
time: null, // Set on use.
delay: 0,
duration: 250,
ease: cubicInOut
};
function inherit(node, id) {
var timing;
while (!(timing = node.__transition) || !(timing = timing[id])) {
if (!(node = node.parentNode)) {
return defaultTiming.time = now(), defaultTiming;
}
}
return timing;
}
var selection_transition = function(name) {
var id,
timing;
if (name instanceof Transition) {
id = name._id, name = name._name;
} else {
id = newId(), (timing = defaultTiming).time = now(), name = name == null ? null : name + "";
}
for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
if (node = group[i]) {
schedule(node, name, id, i, group, timing || inherit(node, id));
}
}
}
return new Transition(groups, this._parents, name, id);
};
selection.prototype.interrupt = selection_interrupt;
selection.prototype.transition = selection_transition;
var X = {
name: "x",
handles: ["e", "w"].map(type),
input: function(x, e) { return x && [[x[0], e[0][1]], [x[1], e[1][1]]]; },
output: function(xy) { return xy && [xy[0][0], xy[1][0]]; }
};
var Y = {
name: "y",
handles: ["n", "s"].map(type),
input: function(y, e) { return y && [[e[0][0], y[0]], [e[1][0], y[1]]]; },
output: function(xy) { return xy && [xy[0][1], xy[1][1]]; }
};
var XY = {
name: "xy",
handles: ["n", "e", "s", "w", "nw", "ne", "se", "sw"].map(type),
input: function(xy) { return xy; },
output: function(xy) { return xy; }
};
function type(t) {
return {type: t};
}
var pi$1 = Math.PI;
var tau$1 = pi$1 * 2;
var max$1 = Math.max;
var pi$2 = Math.PI;
var tau$2 = 2 * pi$2;
var epsilon$1 = 1e-6;
var tauEpsilon = tau$2 - epsilon$1;
function Path() {
this._x0 = this._y0 = // start of current subpath
this._x1 = this._y1 = null; // end of current subpath
this._ = "";
}
function path() {
return new Path;
}
Path.prototype = path.prototype = {
constructor: Path,
moveTo: function(x, y) {
this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
},
closePath: function() {
if (this._x1 !== null) {
this._x1 = this._x0, this._y1 = this._y0;
this._ += "Z";
}
},
lineTo: function(x, y) {
this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
},
quadraticCurveTo: function(x1, y1, x, y) {
this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
},
bezierCurveTo: function(x1, y1, x2, y2, x, y) {
this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
},
arcTo: function(x1, y1, x2, y2, r) {
x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
var x0 = this._x1,
y0 = this._y1,
x21 = x2 - x1,
y21 = y2 - y1,
x01 = x0 - x1,
y01 = y0 - y1,
l01_2 = x01 * x01 + y01 * y01;
// Is the radius negative? Error.
if (r < 0) { throw new Error("negative radius: " + r); }
// Is this path empty? Move to (x1,y1).
if (this._x1 === null) {
this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
}
// Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
else if (!(l01_2 > epsilon$1)) {}
// Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
// Equivalently, is (x1,y1) coincident with (x2,y2)?
// Or, is the radius zero? Line to (x1,y1).
else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon$1) || !r) {
this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
}
// Otherwise, draw an arc!
else {
var x20 = x2 - x0,
y20 = y2 - y0,
l21_2 = x21 * x21 + y21 * y21,
l20_2 = x20 * x20 + y20 * y20,
l21 = Math.sqrt(l21_2),
l01 = Math.sqrt(l01_2),
l = r * Math.tan((pi$2 - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
t01 = l / l01,
t21 = l / l21;
// If the start tangent is not coincident with (x0,y0), line to.
if (Math.abs(t01 - 1) > epsilon$1) {
this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
}
this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
}
},
arc: function(x, y, r, a0, a1, ccw) {
x = +x, y = +y, r = +r;
var dx = r * Math.cos(a0),
dy = r * Math.sin(a0),
x0 = x + dx,
y0 = y + dy,
cw = 1 ^ ccw,
da = ccw ? a0 - a1 : a1 - a0;
// Is the radius negative? Error.
if (r < 0) { throw new Error("negative radius: " + r); }
// Is this path empty? Move to (x0,y0).
if (this._x1 === null) {
this._ += "M" + x0 + "," + y0;
}
// Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
else if (Math.abs(this._x1 - x0) > epsilon$1 || Math.abs(this._y1 - y0) > epsilon$1) {
this._ += "L" + x0 + "," + y0;
}
// Is this arc empty? We’re done.
if (!r) { return; }
// Does the angle go the wrong way? Flip the direction.
if (da < 0) { da = da % tau$2 + tau$2; }
// Is this a complete circle? Draw two arcs to complete the circle.
if (da > tauEpsilon) {
this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
}
// Is this arc non-empty? Draw an arc!
else if (da > epsilon$1) {
this._ += "A" + r + "," + r + ",0," + (+(da >= pi$2)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1));
}
},
rect: function(x, y, w, h) {
this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z";
},
toString: function() {
return this._;
}
};
var prefix = "$";
function Map() {}
Map.prototype = map$1.prototype = {
constructor: Map,
has: function(key) {
return (prefix + key) in this;
},
get: function(key) {
return this[prefix + key];
},
set: function(key, value) {
this[prefix + key] = value;
return this;
},
remove: function(key) {
var property = prefix + key;
return property in this && delete this[property];
},
clear: function() {
var this$1 = this;
for (var property in this$1) { if (property[0] === prefix) { delete this$1[property]; } }
},
keys: function() {
var this$1 = this;
var keys = [];
for (var property in this$1) { if (property[0] === prefix) { keys.push(property.slice(1)); } }
return keys;
},
values: function() {
var this$1 = this;
var values = [];
for (var property in this$1) { if (property[0] === prefix) { values.push(this$1[property]); } }
return values;
},
entries: function() {
var this$1 = this;
var entries = [];
for (var property in this$1) { if (property[0] === prefix) { entries.push({key: property.slice(1), value: this$1[property]}); } }
return entries;
},
size: function() {
var this$1 = this;
var size = 0;
for (var property in this$1) { if (property[0] === prefix) { ++size; } }
return size;
},
empty: function() {
var this$1 = this;
for (var property in this$1) { if (property[0] === prefix) { return false; } }
return true;
},
each: function(f) {
var this$1 = this;
for (var property in this$1) { if (property[0] === prefix) { f(this$1[property], property.slice(1), this$1); } }
}
};
function map$1(object, f) {
var map = new Map;
// Copy constructor.
if (object instanceof Map) { object.each(function(value, key) { map.set(key, value); }); }
// Index array by numeric index or specified key function.
else if (Array.isArray(object)) {
var i = -1,
n = object.length,
o;
if (f == null) { while (++i < n) { map.set(i, object[i]); } }
else { while (++i < n) { map.set(f(o = object[i], i, object), o); } }
}
// Convert object to map.
else if (object) { for (var key in object) { map.set(key, object[key]); } }
return map;
}
function Set() {}
var proto = map$1.prototype;
Set.prototype = set$2.prototype = {
constructor: Set,
has: proto.has,
add: function(value) {
value += "";
this[prefix + value] = value;
return this;
},
remove: proto.remove,
clear: proto.clear,
values: proto.keys,
size: proto.size,
empty: proto.empty,
each: proto.each
};
function set$2(object, f) {
var set = new Set;
// Copy constructor.
if (object instanceof Set) { object.each(function(value) { set.add(value); }); }
// Otherwise, assume it’s an array.
else if (object) {
var i = -1, n = object.length;
if (f == null) { while (++i < n) { set.add(object[i]); } }
else { while (++i < n) { set.add(f(object[i], i, object)); } }
}
return set;
}
var entries = function(map) {
var entries = [];
for (var key in map) { entries.push({key: key, value: map[key]}); }
return entries;
};
function objectConverter(columns) {
return new Function("d", "return {" + columns.map(function(name, i) {
return JSON.stringify(name) + ": d[" + i + "]";
}).join(",") + "}");
}
function customConverter(columns, f) {
var object = objectConverter(columns);
return function(row, i) {
return f(object(row), i, columns);
};
}
// Compute unique columns in order of discovery.
function inferColumns(rows) {
var columnSet = Object.create(null),
columns = [];
rows.forEach(function(row) {
for (var column in row) {
if (!(column in columnSet)) {
columns.push(columnSet[column] = column);
}
}
});
return columns;
}
var dsv = function(delimiter) {
var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),
delimiterCode = delimiter.charCodeAt(0);
function parse(text, f) {
var convert, columns, rows = parseRows(text, function(row, i) {
if (convert) { return convert(row, i - 1); }
columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
});
rows.columns = columns;
return rows;
}
function parseRows(text, f) {
var EOL = {}, // sentinel value for end-of-line
EOF = {}, // sentinel value for end-of-file
rows = [], // output rows
N = text.length,
I = 0, // current character index
n = 0, // the current line number
t, // the current token
eol; // is the current token followed by EOL?
function token() {
if (I >= N) { return EOF; } // special case: end of file
if (eol) { return eol = false, EOL; } // special case: end of line
// special case: quotes
var j = I, c;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < N) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) { break; }
++i;
}
}
I = i + 2;
c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) { ++I; }
} else if (c === 10) {
eol = true;
}
return text.slice(j + 1, i).replace(/""/g, "\"");
}
// common case: find next delimiter or newline
while (I < N) {
var k = 1;
c = text.charCodeAt(I++);
if (c === 10) { eol = true; } // \n
else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) { ++I, ++k; } } // \r|\r\n
else if (c !== delimiterCode) { continue; }
return text.slice(j, I - k);
}
// special case: last token before EOF
return text.slice(j);
}
while ((t = token()) !== EOF) {
var a = [];
while (t !== EOL && t !== EOF) {
a.push(t);
t = token();
}
if (f && (a = f(a, n++)) == null) { continue; }
rows.push(a);
}
return rows;
}
function format(rows, columns) {
if (columns == null) { columns = inferColumns(rows); }
return [columns.map(formatValue).join(delimiter)].concat(rows.map(function(row) {
return columns.map(function(column) {
return formatValue(row[column]);
}).join(delimiter);
})).join("\n");
}
function formatRows(rows) {
return rows.map(formatRow).join("\n");
}
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(text) {
return text == null ? ""
: reFormat.test(text += "") ? "\"" + text.replace(/\"/g, "\"\"") + "\""
: text;
}
return {
parse: parse,
parseRows: parseRows,
format: format,
formatRows: formatRows
};
};
var csv = dsv(",");
var csvParse = csv.parse;
var tsv = dsv("\t");
var tsvParse = tsv.parse;
var tree_add = function(d) {
var x = +this._x.call(null, d),
y = +this._y.call(null, d);
return add(this.cover(x, y), x, y, d);
};
function add(tree, x, y, d) {
if (isNaN(x) || isNaN(y)) { return tree; } // ignore invalid points
var parent,
node = tree._root,
leaf = {data: d},
x0 = tree._x0,
y0 = tree._y0,
x1 = tree._x1,
y1 = tree._y1,
xm,
ym,
xp,
yp,
right,
bottom,
i,
j;
// If the tree is empty, initialize the root as a leaf.
if (!node) { return tree._root = leaf, tree; }
// Find the existing leaf for the new point, or add it.
while (node.length) {
if (right = x >= (xm = (x0 + x1) / 2)) { x0 = xm; } else { x1 = xm; }
if (bottom = y >= (ym = (y0 + y1) / 2)) { y0 = ym; } else { y1 = ym; }
if (parent = node, !(node = node[i = bottom << 1 | right])) { return parent[i] = leaf, tree; }
}
// Is the new point is exactly coincident with the existing point?
xp = +tree._x.call(null, node.data);
yp = +tree._y.call(null, node.data);
if (x === xp && y === yp) { return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree; }
// Otherwise, split the leaf node until the old and new point are separated.
do {
parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
if (right = x >= (xm = (x0 + x1) / 2)) { x0 = xm; } else { x1 = xm; }
if (bottom = y >= (ym = (y0 + y1) / 2)) { y0 = ym; } else { y1 = ym; }
} while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));
return parent[j] = node, parent[i] = leaf, tree;
}
function addAll(data) {
var this$1 = this;
var d, i, n = data.length,
x,
y,
xz = new Array(n),
yz = new Array(n),
x0 = Infinity,
y0 = Infinity,
x1 = -Infinity,
y1 = -Infinity;
// Compute the points and their extent.
for (i = 0; i < n; ++i) {
if (isNaN(x = +this$1._x.call(null, d = data[i])) || isNaN(y = +this$1._y.call(null, d))) { continue; }
xz[i] = x;
yz[i] = y;
if (x < x0) { x0 = x; }
if (x > x1) { x1 = x; }
if (y < y0) { y0 = y; }
if (y > y1) { y1 = y; }
}
// If there were no (valid) points, inherit the existing extent.
if (x1 < x0) { x0 = this._x0, x1 = this._x1; }
if (y1 < y0) { y0 = this._y0, y1 = this._y1; }
// Expand the tree to cover the new points.
this.cover(x0, y0).cover(x1, y1);
// Add the new points.
for (i = 0; i < n; ++i) {
add(this$1, xz[i], yz[i], data[i]);
}
return this;
}
var tree_cover = function(x, y) {
if (isNaN(x = +x) || isNaN(y = +y)) { return this; } // ignore invalid points
var x0 = this._x0,
y0 = this._y0,
x1 = this._x1,
y1 = this._y1;
// If the quadtree has no extent, initialize them.
// Integer extent are necessary so that if we later double the extent,
// the existing quadrant boundaries don’t change due to floating point error!
if (isNaN(x0)) {
x1 = (x0 = Math.floor(x)) + 1;
y1 = (y0 = Math.floor(y)) + 1;
}
// Otherwise, double repeatedly to cover.
else if (x0 > x || x > x1 || y0 > y || y > y1) {
var z = x1 - x0,
node = this._root,
parent,
i;
switch (i = (y < (y0 + y1) / 2) << 1 | (x < (x0 + x1) / 2)) {
case 0: {
do { parent = new Array(4), parent[i] = node, node = parent; }
while (z *= 2, x1 = x0 + z, y1 = y0 + z, x > x1 || y > y1);
break;
}
case 1: {
do { parent = new Array(4), parent[i] = node, node = parent; }
while (z *= 2, x0 = x1 - z, y1 = y0 + z, x0 > x || y > y1);
break;
}
case 2: {
do { parent = new Array(4), parent[i] = node, node = parent; }
while (z *= 2, x1 = x0 + z, y0 = y1 - z, x > x1 || y0 > y);
break;
}
case 3: {
do { parent = new Array(4), parent[i] = node, node = parent; }
while (z *= 2, x0 = x1 - z, y0 = y1 - z, x0 > x || y0 > y);
break;
}
}
if (this._root && this._root.length) { this._root = node; }
}
// If the quadtree covers the point already, just return.
else { return this; }
this._x0 = x0;
this._y0 = y0;
this._x1 = x1;
this._y1 = y1;
return this;
};
var tree_data = function() {
var data = [];
this.visit(function(node) {
if (!node.length) { do { data.push(node.data); } while (node = node.next) }
});
return data;
};
var tree_extent = function(_) {
return arguments.length
? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])
: isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];
};
var Quad = function(node, x0, y0, x1, y1) {
this.node = node;
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
};
var tree_find = function(x, y, radius) {
var this$1 = this;
var data,
x0 = this._x0,
y0 = this._y0,
x1,
y1,
x2,
y2,
x3 = this._x1,
y3 = this._y1,
quads = [],
node = this._root,
q,
i;
if (node) { quads.push(new Quad(node, x0, y0, x3, y3)); }
if (radius == null) { radius = Infinity; }
else {
x0 = x - radius, y0 = y - radius;
x3 = x + radius, y3 = y + radius;
radius *= radius;
}
while (q = quads.pop()) {
// Stop searching if this quadrant can’t contain a closer node.
if (!(node = q.node)
|| (x1 = q.x0) > x3
|| (y1 = q.y0) > y3
|| (x2 = q.x1) < x0
|| (y2 = q.y1) < y0) { continue; }
// Bisect the current quadrant.
if (node.length) {
var xm = (x1 + x2) / 2,
ym = (y1 + y2) / 2;
quads.push(
new Quad(node[3], xm, ym, x2, y2),
new Quad(node[2], x1, ym, xm, y2),
new Quad(node[1], xm, y1, x2, ym),
new Quad(node[0], x1, y1, xm, ym)
);
// Visit the closest quadrant first.
if (i = (y >= ym) << 1 | (x >= xm)) {
q = quads[quads.length - 1];
quads[quads.length - 1] = quads[quads.length - 1 - i];
quads[quads.length - 1 - i] = q;
}
}
// Visit this point. (Visiting coincident points isn’t necessary!)
else {
var dx = x - +this$1._x.call(null, node.data),
dy = y - +this$1._y.call(null, node.data),
d2 = dx * dx + dy * dy;
if (d2 < radius) {
var d = Math.sqrt(radius = d2);
x0 = x - d, y0 = y - d;
x3 = x + d, y3 = y + d;
data = node.data;
}
}
}
return data;
};
var tree_remove = function(d) {
var this$1 = this;
if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) { return this; } // ignore invalid points
var parent,
node = this._root,
retainer,
previous,
next,
x0 = this._x0,
y0 = this._y0,
x1 = this._x1,
y1 = this._y1,
x,
y,
xm,
ym,
right,
bottom,
i,
j;
// If the tree is empty, initialize the root as a leaf.
if (!node) { return this; }
// Find the leaf node for the point.
// While descending, also retain the deepest parent with a non-removed sibling.
if (node.length) { while (true) {
if (right = x >= (xm = (x0 + x1) / 2)) { x0 = xm; } else { x1 = xm; }
if (bottom = y >= (ym = (y0 + y1) / 2)) { y0 = ym; } else { y1 = ym; }
if (!(parent = node, node = node[i = bottom << 1 | right])) { return this$1; }
if (!node.length) { break; }
if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) { retainer = parent, j = i; }
} }
// Find the point to remove.
while (node.data !== d) { if (!(previous = node, node = node.next)) { return this$1; } }
if (next = node.next) { delete node.next; }
// If there are multiple coincident points, remove just the point.
if (previous) { return (next ? previous.next = next : delete previous.next), this; }
// If this is the root point, remove it.
if (!parent) { return this._root = next, this; }
// Remove this leaf.
next ? parent[i] = next : delete parent[i];
// If the parent now contains exactly one leaf, collapse superfluous parents.
if ((node = parent[0] || parent[1] || parent[2] || parent[3])
&& node === (parent[3] || parent[2] || parent[1] || parent[0])
&& !node.length) {
if (retainer) { retainer[j] = node; }
else { this._root = node; }
}
return this;
};
function removeAll(data) {
var this$1 = this;
for (var i = 0, n = data.length; i < n; ++i) { this$1.remove(data[i]); }
return this;
}
var tree_root = function() {
return this._root;
};
var tree_size = function() {
var size = 0;
this.visit(function(node) {
if (!node.length) { do { ++size; } while (node = node.next) }
});
return size;
};
var tree_visit = function(callback) {
var quads = [], q, node = this._root, child, x0, y0, x1, y1;
if (node) { quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1)); }
while (q = quads.pop()) {
if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
if (child = node[3]) { quads.push(new Quad(child, xm, ym, x1, y1)); }
if (child = node[2]) { quads.push(new Quad(child, x0, ym, xm, y1)); }
if (child = node[1]) { quads.push(new Quad(child, xm, y0, x1, ym)); }
if (child = node[0]) { quads.push(new Quad(child, x0, y0, xm, ym)); }
}
}
return this;
};
var tree_visitAfter = function(callback) {
var quads = [], next = [], q;
if (this._root) { quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1)); }
while (q = quads.pop()) {
var node = q.node;
if (node.length) {
var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
if (child = node[0]) { quads.push(new Quad(child, x0, y0, xm, ym)); }
if (child = node[1]) { quads.push(new Quad(child, xm, y0, x1, ym)); }
if (child = node[2]) { quads.push(new Quad(child, x0, ym, xm, y1)); }
if (child = node[3]) { quads.push(new Quad(child, xm, ym, x1, y1)); }
}
next.push(q);
}
while (q = next.pop()) {
callback(q.node, q.x0, q.y0, q.x1, q.y1);
}
return this;
};
function defaultX(d) {
return d[0];
}
var tree_x = function(_) {
return arguments.length ? (this._x = _, this) : this._x;
};
function defaultY(d) {
return d[1];
}
var tree_y = function(_) {
return arguments.length ? (this._y = _, this) : this._y;
};
function quadtree(nodes, x, y) {
var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);
return nodes == null ? tree : tree.addAll(nodes);
}
function Quadtree(x, y, x0, y0, x1, y1) {
this._x = x;
this._y = y;
this._x0 = x0;
this._y0 = y0;
this._x1 = x1;
this._y1 = y1;
this._root = undefined;
}
function leaf_copy(leaf) {
var copy = {data: leaf.data}, next = copy;
while (leaf = leaf.next) { next = next.next = {data: leaf.data}; }
return copy;
}
var treeProto = quadtree.prototype = Quadtree.prototype;
treeProto.copy = function() {
var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),
node = this._root,
nodes,
child;
if (!node) { return copy; }
if (!node.length) { return copy._root = leaf_copy(node), copy; }
nodes = [{source: node, target: copy._root = new Array(4)}];
while (node = nodes.pop()) {
for (var i = 0; i < 4; ++i) {
if (child = node.source[i]) {
if (child.length) { nodes.push({source: child, target: node.target[i] = new Array(4)}); }
else { node.target[i] = leaf_copy(child); }
}
}
}
return copy;
};
treeProto.add = tree_add;
treeProto.addAll = addAll;
treeProto.cover = tree_cover;
treeProto.data = tree_data;
treeProto.extent = tree_extent;
treeProto.find = tree_find;
treeProto.remove = tree_remove;
treeProto.removeAll = removeAll;
treeProto.root = tree_root;
treeProto.size = tree_size;
treeProto.visit = tree_visit;
treeProto.visitAfter = tree_visitAfter;
treeProto.x = tree_x;
treeProto.y = tree_y;
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
var formatDecimal = function(x, p) {
if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) { return null; } // NaN, ±Infinity
var i, coefficient = x.slice(0, i);
// The string returned by toExponential either has the form \d\.\d+e[-+]\d+
// (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
return [
coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
+x.slice(i + 1)
];
};
var exponent$1 = function(x) {
return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;
};
var formatGroup = function(grouping, thousands) {
return function(value, width) {
var i = value.length,
t = [],
j = 0,
g = grouping[0],
length = 0;
while (i > 0 && g > 0) {
if (length + g + 1 > width) { g = Math.max(1, width - length); }
t.push(value.substring(i -= g, i + g));
if ((length += g + 1) > width) { break; }
g = grouping[j = (j + 1) % grouping.length];
}
return t.reverse().join(thousands);
};
};
var formatNumerals = function(numerals) {
return function(value) {
return value.replace(/[0-9]/g, function(i) {
return numerals[+i];
});
};
};
var formatDefault = function(x, p) {
x = x.toPrecision(p);
out: for (var n = x.length, i = 1, i0 = -1, i1; i < n; ++i) {
switch (x[i]) {
case ".": i0 = i1 = i; break;
case "0": if (i0 === 0) { i0 = i; } i1 = i; break;
case "e": break out;
default: if (i0 > 0) { i0 = 0; } break;
}
}
return i0 > 0 ? x.slice(0, i0) + x.slice(i1 + 1) : x;
};
var prefixExponent;
var formatPrefixAuto = function(x, p) {
var d = formatDecimal(x, p);
if (!d) { return x + ""; }
var coefficient = d[0],
exponent = d[1],
i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
n = coefficient.length;
return i === n ? coefficient
: i > n ? coefficient + new Array(i - n + 1).join("0")
: i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
: "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
};
var formatRounded = function(x, p) {
var d = formatDecimal(x, p);
if (!d) { return x + ""; }
var coefficient = d[0],
exponent = d[1];
return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
: coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
: coefficient + new Array(exponent - coefficient.length + 2).join("0");
};
var formatTypes = {
"": formatDefault,
"%": function(x, p) { return (x * 100).toFixed(p); },
"b": function(x) { return Math.round(x).toString(2); },
"c": function(x) { return x + ""; },
"d": function(x) { return Math.round(x).toString(10); },
"e": function(x, p) { return x.toExponential(p); },
"f": function(x, p) { return x.toFixed(p); },
"g": function(x, p) { return x.toPrecision(p); },
"o": function(x) { return Math.round(x).toString(8); },
"p": function(x, p) { return formatRounded(x * 100, p); },
"r": formatRounded,
"s": formatPrefixAuto,
"X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
"x": function(x) { return Math.round(x).toString(16); }
};
// [[fill]align][sign][symbol][0][width][,][.precision][type]
var re = /^(?:(.)?([<>=^]))?([+\-\( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([a-z%])?$/i;
function formatSpecifier(specifier) {
return new FormatSpecifier(specifier);
}
formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
function FormatSpecifier(specifier) {
if (!(match = re.exec(specifier))) { throw new Error("invalid format: " + specifier); }
var match,
fill = match[1] || " ",
align = match[2] || ">",
sign = match[3] || "-",
symbol = match[4] || "",
zero = !!match[5],
width = match[6] && +match[6],
comma = !!match[7],
precision = match[8] && +match[8].slice(1),
type = match[9] || "";
// The "n" type is an alias for ",g".
if (type === "n") { comma = true, type = "g"; }
// Map invalid types to the default format.
else if (!formatTypes[type]) { type = ""; }
// If zero fill is specified, padding goes after sign and before digits.
if (zero || (fill === "0" && align === "=")) { zero = true, fill = "0", align = "="; }
this.fill = fill;
this.align = align;
this.sign = sign;
this.symbol = symbol;
this.zero = zero;
this.width = width;
this.comma = comma;
this.precision = precision;
this.type = type;
}
FormatSpecifier.prototype.toString = function() {
return this.fill
+ this.align
+ this.sign
+ this.symbol
+ (this.zero ? "0" : "")
+ (this.width == null ? "" : Math.max(1, this.width | 0))
+ (this.comma ? "," : "")
+ (this.precision == null ? "" : "." + Math.max(0, this.precision | 0))
+ this.type;
};
var identity$3 = function(x) {
return x;
};
var prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
var formatLocale = function(locale) {
var group = locale.grouping && locale.thousands ? formatGroup(locale.grouping, locale.thousands) : identity$3,
currency = locale.currency,
decimal = locale.decimal,
numerals = locale.numerals ? formatNumerals(locale.numerals) : identity$3,
percent = locale.percent || "%";
function newFormat(specifier) {
specifier = formatSpecifier(specifier);
var fill = specifier.fill,
align = specifier.align,
sign = specifier.sign,
symbol = specifier.symbol,
zero = specifier.zero,
width = specifier.width,
comma = specifier.comma,
precision = specifier.precision,
type = specifier.type;
// Compute the prefix and suffix.
// For SI-prefix, the suffix is lazily computed.
var prefix = symbol === "$" ? currency[0] : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
suffix = symbol === "$" ? currency[1] : /[%p]/.test(type) ? percent : "";
// What format function should we use?
// Is this an integer type?
// Can this type generate exponential notation?
var formatType = formatTypes[type],
maybeSuffix = !type || /[defgprs%]/.test(type);
// Set the default precision if not specified,
// or clamp the specified precision to the supported range.
// For significant precision, it must be in [1, 21].
// For fixed precision, it must be in [0, 20].
precision = precision == null ? (type ? 6 : 12)
: /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
: Math.max(0, Math.min(20, precision));
function format(value) {
var valuePrefix = prefix,
valueSuffix = suffix,
i, n, c;
if (type === "c") {
valueSuffix = formatType(value) + valueSuffix;
value = "";
} else {
value = +value;
// Perform the initial formatting.
var valueNegative = value < 0;
value = formatType(Math.abs(value), precision);
// If a negative value rounds to zero during formatting, treat as positive.
if (valueNegative && +value === 0) { valueNegative = false; }
// Compute the prefix and suffix.
valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
valueSuffix = valueSuffix + (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + (valueNegative && sign === "(" ? ")" : "");
// Break the formatted value into the integer “value” part that can be
// grouped, and fractional or exponential “suffix” part that is not.
if (maybeSuffix) {
i = -1, n = value.length;
while (++i < n) {
if (c = value.charCodeAt(i), 48 > c || c > 57) {
valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
value = value.slice(0, i);
break;
}
}
}
}
// If the fill character is not "0", grouping is applied before padding.
if (comma && !zero) { value = group(value, Infinity); }
// Compute the padding.
var length = valuePrefix.length + value.length + valueSuffix.length,
padding = length < width ? new Array(width - length + 1).join(fill) : "";
// If the fill character is "0", grouping is applied after padding.
if (comma && zero) { value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = ""; }
// Reconstruct the final output based on the desired alignment.
switch (align) {
case "<": value = valuePrefix + value + valueSuffix + padding; break;
case "=": value = valuePrefix + padding + value + valueSuffix; break;
case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
default: value = padding + valuePrefix + value + valueSuffix; break;
}
return numerals(value);
}
format.toString = function() {
return specifier + "";
};
return format;
}
function formatPrefix(specifier, value) {
var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
e = Math.max(-8, Math.min(8, Math.floor(exponent$1(value) / 3))) * 3,
k = Math.pow(10, -e),
prefix = prefixes[8 + e / 3];
return function(value) {
return f(k * value) + prefix;
};
}
return {
format: newFormat,
formatPrefix: formatPrefix
};
};
var locale$1;
var format;
var formatPrefix;
defaultLocale({
decimal: ".",
thousands: ",",
grouping: [3],
currency: ["$", ""]
});
function defaultLocale(definition) {
locale$1 = formatLocale(definition);
format = locale$1.format;
formatPrefix = locale$1.formatPrefix;
return locale$1;
}
var precisionFixed = function(step) {
return Math.max(0, -exponent$1(Math.abs(step)));
};
var precisionPrefix = function(step, value) {
return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent$1(value) / 3))) * 3 - exponent$1(Math.abs(step)));
};
var precisionRound = function(step, max) {
step = Math.abs(step), max = Math.abs(max) - step;
return Math.max(0, exponent$1(max) - exponent$1(step)) + 1;
};
// Adds floating point numbers with twice the normal precision.
// Reference: J. R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and
// Fast Robust Geometric Predicates, Discrete & Computational Geometry 18(3)
// 305–363 (1997).
// Code adapted from GeographicLib by Charles F. F. Karney,
// http://geographiclib.sourceforge.net/
var adder = function() {
return new Adder;
};
function Adder() {
this.reset();
}
Adder.prototype = {
constructor: Adder,
reset: function() {
this.s = // rounded value
this.t = 0; // exact error
},
add: function(y) {
add$1(temp, y, this.t);
add$1(this, temp.s, this.s);
if (this.s) { this.t += temp.t; }
else { this.s = temp.t; }
},
valueOf: function() {
return this.s;
}
};
var temp = new Adder;
function add$1(adder, a, b) {
var x = adder.s = a + b,
bv = x - a,
av = x - bv;
adder.t = (a - av) + (b - bv);
}
var epsilon$2 = 1e-6;
var pi$3 = Math.PI;
var halfPi$2 = pi$3 / 2;
var quarterPi = pi$3 / 4;
var tau$3 = pi$3 * 2;
var radians = pi$3 / 180;
var abs = Math.abs;
var atan = Math.atan;
var atan2 = Math.atan2;
var cos$1 = Math.cos;
var sin$1 = Math.sin;
var sqrt = Math.sqrt;
function acos(x) {
return x > 1 ? 0 : x < -1 ? pi$3 : Math.acos(x);
}
function asin(x) {
return x > 1 ? halfPi$2 : x < -1 ? -halfPi$2 : Math.asin(x);
}
function noop$1() {}
function streamGeometry(geometry, stream) {
if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {
streamGeometryType[geometry.type](geometry, stream);
}
}
var streamObjectType = {
Feature: function(object, stream) {
streamGeometry(object.geometry, stream);
},
FeatureCollection: function(object, stream) {
var features = object.features, i = -1, n = features.length;
while (++i < n) { streamGeometry(features[i].geometry, stream); }
}
};
var streamGeometryType = {
Sphere: function(object, stream) {
stream.sphere();
},
Point: function(object, stream) {
object = object.coordinates;
stream.point(object[0], object[1], object[2]);
},
MultiPoint: function(object, stream) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) { object = coordinates[i], stream.point(object[0], object[1], object[2]); }
},
LineString: function(object, stream) {
streamLine(object.coordinates, stream, 0);
},
MultiLineString: function(object, stream) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) { streamLine(coordinates[i], stream, 0); }
},
Polygon: function(object, stream) {
streamPolygon(object.coordinates, stream);
},
MultiPolygon: function(object, stream) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) { streamPolygon(coordinates[i], stream); }
},
GeometryCollection: function(object, stream) {
var geometries = object.geometries, i = -1, n = geometries.length;
while (++i < n) { streamGeometry(geometries[i], stream); }
}
};
function streamLine(coordinates, stream, closed) {
var i = -1, n = coordinates.length - closed, coordinate;
stream.lineStart();
while (++i < n) { coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]); }
stream.lineEnd();
}
function streamPolygon(coordinates, stream) {
var i = -1, n = coordinates.length;
stream.polygonStart();
while (++i < n) { streamLine(coordinates[i], stream, 1); }
stream.polygonEnd();
}
var geoStream = function(object, stream) {
if (object && streamObjectType.hasOwnProperty(object.type)) {
streamObjectType[object.type](object, stream);
} else {
streamGeometry(object, stream);
}
};
var areaRingSum = adder();
var areaSum = adder();
var lambda00;
var phi00;
var lambda0;
var cosPhi0;
var sinPhi0;
function cartesian(spherical) {
var lambda = spherical[0], phi = spherical[1], cosPhi = cos$1(phi);
return [cosPhi * cos$1(lambda), cosPhi * sin$1(lambda), sin$1(phi)];
}
function cartesianCross(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]];
}
// TODO return a
// TODO return d
function cartesianNormalizeInPlace(d) {
var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
d[0] /= l, d[1] /= l, d[2] /= l;
}
var lambda0$1;
var phi0;
var lambda1;
var phi1;
var lambda2;
var lambda00$1;
var phi00$1;
var p0;
var deltaSum = adder();
var ranges;
var range;
var W0;
var X0;
var Y0;
var Z0; // previous point
// Generates a circle centered at [0°, 0°], with a given radius and precision.
var clipBuffer = function() {
var lines = [],
line;
return {
point: function(x, y) {
line.push([x, y]);
},
lineStart: function() {
lines.push(line = []);
},
lineEnd: noop$1,
rejoin: function() {
if (lines.length > 1) { lines.push(lines.pop().concat(lines.shift())); }
},
result: function() {
var result = lines;
lines = [];
line = null;
return result;
}
};
};
var pointEqual = function(a, b) {
return abs(a[0] - b[0]) < epsilon$2 && abs(a[1] - b[1]) < epsilon$2;
};
function Intersection(point, points, other, entry) {
this.x = point;
this.z = points;
this.o = other; // another intersection
this.e = entry; // is an entry?
this.v = false; // visited
this.n = this.p = null; // next & previous
}
// A generalized polygon clipping algorithm: given a polygon that has been cut
// into its visible line segments, and rejoins the segments by interpolating
// along the clip edge.
var clipPolygon = function(segments, compareIntersection, startInside, interpolate, stream) {
var subject = [],
clip = [],
i,
n;
segments.forEach(function(segment) {
if ((n = segment.length - 1) <= 0) { return; }
var n, p0 = segment[0], p1 = segment[n], x;
// If the first and last points of a segment are coincident, then treat as a
// closed ring. TODO if all rings are closed, then the winding order of the
// exterior ring should be checked.
if (pointEqual(p0, p1)) {
stream.lineStart();
for (i = 0; i < n; ++i) { stream.point((p0 = segment[i])[0], p0[1]); }
stream.lineEnd();
return;
}
subject.push(x = new Intersection(p0, segment, null, true));
clip.push(x.o = new Intersection(p0, null, x, false));
subject.push(x = new Intersection(p1, segment, null, false));
clip.push(x.o = new Intersection(p1, null, x, true));
});
if (!subject.length) { return; }
clip.sort(compareIntersection);
link$1(subject);
link$1(clip);
for (i = 0, n = clip.length; i < n; ++i) {
clip[i].e = startInside = !startInside;
}
var start = subject[0],
points,
point;
while (1) {
// Find first unvisited intersection.
var current = start,
isSubject = true;
while (current.v) { if ((current = current.n) === start) { return; } }
points = current.z;
stream.lineStart();
do {
current.v = current.o.v = true;
if (current.e) {
if (isSubject) {
for (i = 0, n = points.length; i < n; ++i) { stream.point((point = points[i])[0], point[1]); }
} else {
interpolate(current.x, current.n.x, 1, stream);
}
current = current.n;
} else {
if (isSubject) {
points = current.p.z;
for (i = points.length - 1; i >= 0; --i) { stream.point((point = points[i])[0], point[1]); }
} else {
interpolate(current.x, current.p.x, -1, stream);
}
current = current.p;
}
current = current.o;
points = current.z;
isSubject = !isSubject;
} while (!current.v);
stream.lineEnd();
}
};
function link$1(array) {
if (!(n = array.length)) { return; }
var n,
i = 0,
a = array[0],
b;
while (++i < n) {
a.n = b = array[i];
b.p = a;
a = b;
}
a.n = b = array[0];
b.p = a;
}
// TODO Use d3-polygon’s polygonContains here for the ring check?
// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?
var sum$1 = adder();
var polygonContains = function(polygon, point) {
var lambda = point[0],
phi = point[1],
normal = [sin$1(lambda), -cos$1(lambda), 0],
angle = 0,
winding = 0;
sum$1.reset();
for (var i = 0, n = polygon.length; i < n; ++i) {
if (!(m = (ring = polygon[i]).length)) { continue; }
var ring,
m,
point0 = ring[m - 1],
lambda0 = point0[0],
phi0 = point0[1] / 2 + quarterPi,
sinPhi0 = sin$1(phi0),
cosPhi0 = cos$1(phi0);
for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {
var point1 = ring[j],
lambda1 = point1[0],
phi1 = point1[1] / 2 + quarterPi,
sinPhi1 = sin$1(phi1),
cosPhi1 = cos$1(phi1),
delta = lambda1 - lambda0,
sign$$1 = delta >= 0 ? 1 : -1,
absDelta = sign$$1 * delta,
antimeridian = absDelta > pi$3,
k = sinPhi0 * sinPhi1;
sum$1.add(atan2(k * sign$$1 * sin$1(absDelta), cosPhi0 * cosPhi1 + k * cos$1(absDelta)));
angle += antimeridian ? delta + sign$$1 * tau$3 : delta;
// Are the longitudes either side of the point’s meridian (lambda),
// and are the latitudes smaller than the parallel (phi)?
if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {
var arc = cartesianCross(cartesian(point0), cartesian(point1));
cartesianNormalizeInPlace(arc);
var intersection = cartesianCross(normal, arc);
cartesianNormalizeInPlace(intersection);
var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);
if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {
winding += antimeridian ^ delta >= 0 ? 1 : -1;
}
}
}
}
// First, determine whether the South pole is inside or outside:
//
// It is inside if:
// * the polygon winds around it in a clockwise direction.
// * the polygon does not (cumulatively) wind around it, but has a negative
// (counter-clockwise) area.
//
// Second, count the (signed) number of times a segment crosses a lambda
// from the point to the South pole. If it is zero, then the point is the
// same side as the South pole.
return (angle < -epsilon$2 || angle < epsilon$2 && sum$1 < -epsilon$2) ^ (winding & 1);
};
var lengthSum = adder();
var lambda0$2;
var sinPhi0$1;
var cosPhi0$1;
var lengthStream = {
sphere: noop$1,
point: noop$1,
lineStart: lengthLineStart,
lineEnd: noop$1,
polygonStart: noop$1,
polygonEnd: noop$1
};
function lengthLineStart() {
lengthStream.point = lengthPointFirst;
lengthStream.lineEnd = lengthLineEnd;
}
function lengthLineEnd() {
lengthStream.point = lengthStream.lineEnd = noop$1;
}
function lengthPointFirst(lambda, phi) {
lambda *= radians, phi *= radians;
lambda0$2 = lambda, sinPhi0$1 = sin$1(phi), cosPhi0$1 = cos$1(phi);
lengthStream.point = lengthPoint;
}
function lengthPoint(lambda, phi) {
lambda *= radians, phi *= radians;
var sinPhi = sin$1(phi),
cosPhi = cos$1(phi),
delta = abs(lambda - lambda0$2),
cosDelta = cos$1(delta),
sinDelta = sin$1(delta),
x = cosPhi * sinDelta,
y = cosPhi0$1 * sinPhi - sinPhi0$1 * cosPhi * cosDelta,
z = sinPhi0$1 * sinPhi + cosPhi0$1 * cosPhi * cosDelta;
lengthSum.add(atan2(sqrt(x * x + y * y), z));
lambda0$2 = lambda, sinPhi0$1 = sinPhi, cosPhi0$1 = cosPhi;
}
var length$1 = function(object) {
lengthSum.reset();
geoStream(object, lengthStream);
return +lengthSum;
};
var coordinates = [null, null];
var object$1 = {type: "LineString", coordinates: coordinates};
var distance = function(a, b) {
coordinates[0] = a;
coordinates[1] = b;
return length$1(object$1);
};
var containsGeometryType = {
Sphere: function() {
return true;
},
Point: function(object, point) {
return containsPoint(object.coordinates, point);
},
MultiPoint: function(object, point) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) { if (containsPoint(coordinates[i], point)) { return true; } }
return false;
},
LineString: function(object, point) {
return containsLine(object.coordinates, point);
},
MultiLineString: function(object, point) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) { if (containsLine(coordinates[i], point)) { return true; } }
return false;
},
Polygon: function(object, point) {
return containsPolygon(object.coordinates, point);
},
MultiPolygon: function(object, point) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) { if (containsPolygon(coordinates[i], point)) { return true; } }
return false;
},
GeometryCollection: function(object, point) {
var geometries = object.geometries, i = -1, n = geometries.length;
while (++i < n) { if (containsGeometry(geometries[i], point)) { return true; } }
return false;
}
};
function containsGeometry(geometry, point) {
return geometry && containsGeometryType.hasOwnProperty(geometry.type)
? containsGeometryType[geometry.type](geometry, point)
: false;
}
function containsPoint(coordinates, point) {
return distance(coordinates, point) === 0;
}
function containsLine(coordinates, point) {
var ab = distance(coordinates[0], coordinates[1]),
ao = distance(coordinates[0], point),
ob = distance(point, coordinates[1]);
return ao + ob <= ab + epsilon$2;
}
function containsPolygon(coordinates, point) {
return !!polygonContains(coordinates.map(ringRadians), pointRadians(point));
}
function ringRadians(ring) {
return ring = ring.map(pointRadians), ring.pop(), ring;
}
function pointRadians(point) {
return [point[0] * radians, point[1] * radians];
}
var areaSum$1 = adder();
var areaRingSum$1 = adder();
var x00;
var y00;
var x0$1;
var y0$1;
// TODO Enforce positive area for exterior, negative area for interior?
var X0$1 = 0;
var Y0$1 = 0;
var Z0$1 = 0;
var lengthSum$1 = adder();
var lengthRing;
var x00$2;
var y00$2;
var x0$4;
var y0$4;
var clip = function(pointVisible, clipLine, interpolate, start) {
return function(rotate, sink) {
var line = clipLine(sink),
rotatedStart = rotate.invert(start[0], start[1]),
ringBuffer = clipBuffer(),
ringSink = clipLine(ringBuffer),
polygonStarted = false,
polygon,
segments,
ring;
var clip = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
clip.point = pointRing;
clip.lineStart = ringStart;
clip.lineEnd = ringEnd;
segments = [];
polygon = [];
},
polygonEnd: function() {
clip.point = point;
clip.lineStart = lineStart;
clip.lineEnd = lineEnd;
segments = merge(segments);
var startInside = polygonContains(polygon, rotatedStart);
if (segments.length) {
if (!polygonStarted) { sink.polygonStart(), polygonStarted = true; }
clipPolygon(segments, compareIntersection, startInside, interpolate, sink);
} else if (startInside) {
if (!polygonStarted) { sink.polygonStart(), polygonStarted = true; }
sink.lineStart();
interpolate(null, null, 1, sink);
sink.lineEnd();
}
if (polygonStarted) { sink.polygonEnd(), polygonStarted = false; }
segments = polygon = null;
},
sphere: function() {
sink.polygonStart();
sink.lineStart();
interpolate(null, null, 1, sink);
sink.lineEnd();
sink.polygonEnd();
}
};
function point(lambda, phi) {
var point = rotate(lambda, phi);
if (pointVisible(lambda = point[0], phi = point[1])) { sink.point(lambda, phi); }
}
function pointLine(lambda, phi) {
var point = rotate(lambda, phi);
line.point(point[0], point[1]);
}
function lineStart() {
clip.point = pointLine;
line.lineStart();
}
function lineEnd() {
clip.point = point;
line.lineEnd();
}
function pointRing(lambda, phi) {
ring.push([lambda, phi]);
var point = rotate(lambda, phi);
ringSink.point(point[0], point[1]);
}
function ringStart() {
ringSink.lineStart();
ring = [];
}
function ringEnd() {
pointRing(ring[0][0], ring[0][1]);
ringSink.lineEnd();
var clean = ringSink.clean(),
ringSegments = ringBuffer.result(),
i, n = ringSegments.length, m,
segment,
point;
ring.pop();
polygon.push(ring);
ring = null;
if (!n) { return; }
// No intersections.
if (clean & 1) {
segment = ringSegments[0];
if ((m = segment.length - 1) > 0) {
if (!polygonStarted) { sink.polygonStart(), polygonStarted = true; }
sink.lineStart();
for (i = 0; i < m; ++i) { sink.point((point = segment[i])[0], point[1]); }
sink.lineEnd();
}
return;
}
// Rejoin connected segments.
// TODO reuse ringBuffer.rejoin()?
if (n > 1 && clean & 2) { ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); }
segments.push(ringSegments.filter(validSegment));
}
return clip;
};
};
function validSegment(segment) {
return segment.length > 1;
}
// Intersections are sorted along the clip edge. For both antimeridian cutting
// and circle clipping, the same comparison is used.
function compareIntersection(a, b) {
return ((a = a.x)[0] < 0 ? a[1] - halfPi$2 - epsilon$2 : halfPi$2 - a[1])
- ((b = b.x)[0] < 0 ? b[1] - halfPi$2 - epsilon$2 : halfPi$2 - b[1]);
}
clip(
function() { return true; },
clipAntimeridianLine,
clipAntimeridianInterpolate,
[-pi$3, -halfPi$2]
);
// Takes a line and cuts into visible segments. Return values: 0 - there were
// intersections or the line was empty; 1 - no intersections; 2 - there were
// intersections, and the first and last segments should be rejoined.
function clipAntimeridianLine(stream) {
var lambda0 = NaN,
phi0 = NaN,
sign0 = NaN,
clean; // no intersections
return {
lineStart: function() {
stream.lineStart();
clean = 1;
},
point: function(lambda1, phi1) {
var sign1 = lambda1 > 0 ? pi$3 : -pi$3,
delta = abs(lambda1 - lambda0);
if (abs(delta - pi$3) < epsilon$2) { // line crosses a pole
stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi$2 : -halfPi$2);
stream.point(sign0, phi0);
stream.lineEnd();
stream.lineStart();
stream.point(sign1, phi0);
stream.point(lambda1, phi0);
clean = 0;
} else if (sign0 !== sign1 && delta >= pi$3) { // line crosses antimeridian
if (abs(lambda0 - sign0) < epsilon$2) { lambda0 -= sign0 * epsilon$2; } // handle degeneracies
if (abs(lambda1 - sign1) < epsilon$2) { lambda1 -= sign1 * epsilon$2; }
phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);
stream.point(sign0, phi0);
stream.lineEnd();
stream.lineStart();
stream.point(sign1, phi0);
clean = 0;
}
stream.point(lambda0 = lambda1, phi0 = phi1);
sign0 = sign1;
},
lineEnd: function() {
stream.lineEnd();
lambda0 = phi0 = NaN;
},
clean: function() {
return 2 - clean; // if intersections, rejoin first and last segments
}
};
}
function clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {
var cosPhi0,
cosPhi1,
sinLambda0Lambda1 = sin$1(lambda0 - lambda1);
return abs(sinLambda0Lambda1) > epsilon$2
? atan((sin$1(phi0) * (cosPhi1 = cos$1(phi1)) * sin$1(lambda1)
- sin$1(phi1) * (cosPhi0 = cos$1(phi0)) * sin$1(lambda0))
/ (cosPhi0 * cosPhi1 * sinLambda0Lambda1))
: (phi0 + phi1) / 2;
}
function clipAntimeridianInterpolate(from, to, direction, stream) {
var phi;
if (from == null) {
phi = direction * halfPi$2;
stream.point(-pi$3, phi);
stream.point(0, phi);
stream.point(pi$3, phi);
stream.point(pi$3, 0);
stream.point(pi$3, -phi);
stream.point(0, -phi);
stream.point(-pi$3, -phi);
stream.point(-pi$3, 0);
stream.point(-pi$3, phi);
} else if (abs(from[0] - to[0]) > epsilon$2) {
var lambda = from[0] < to[0] ? pi$3 : -pi$3;
phi = direction * lambda / 2;
stream.point(-lambda, phi);
stream.point(0, phi);
stream.point(lambda, phi);
} else {
stream.point(to[0], to[1]);
}
}
var cosMinDistance = cos$1(30 * radians); // cos(minimum angular distance)
// A composite projection for the United States, configured by default for
// 960×500. The projection also works quite well at 960×600 if you change the
// scale to 1285 and adjust the translate accordingly. The set of standard
// parallels for each region comes from USGS, which is published here:
// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers
function azimuthalRaw(scale) {
return function(x, y) {
var cx = cos$1(x),
cy = cos$1(y),
k = scale(cx * cy);
return [
k * cy * sin$1(x),
k * sin$1(y)
];
}
}
function azimuthalInvert(angle) {
return function(x, y) {
var z = sqrt(x * x + y * y),
c = angle(z),
sc = sin$1(c),
cc = cos$1(c);
return [
atan2(x * sc, z * cc),
asin(z && y * sc / z)
];
}
}
var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {
return sqrt(2 / (1 + cxcy));
});
azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {
return 2 * asin(z / 2);
});
var azimuthalEquidistantRaw = azimuthalRaw(function(c) {
return (c = acos(c)) && c / sin$1(c);
});
azimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {
return z;
});
function count(node) {
var sum = 0,
children = node.children,
i = children && children.length;
if (!i) { sum = 1; }
else { while (--i >= 0) { sum += children[i].value; } }
node.value = sum;
}
var node_count = function() {
return this.eachAfter(count);
};
var node_each = function(callback) {
var node = this, current, next = [node], children, i, n;
do {
current = next.reverse(), next = [];
while (node = current.pop()) {
callback(node), children = node.children;
if (children) { for (i = 0, n = children.length; i < n; ++i) {
next.push(children[i]);
} }
}
} while (next.length);
return this;
};
var node_eachBefore = function(callback) {
var node = this, nodes = [node], children, i;
while (node = nodes.pop()) {
callback(node), children = node.children;
if (children) { for (i = children.length - 1; i >= 0; --i) {
nodes.push(children[i]);
} }
}
return this;
};
var node_eachAfter = function(callback) {
var node = this, nodes = [node], next = [], children, i, n;
while (node = nodes.pop()) {
next.push(node), children = node.children;
if (children) { for (i = 0, n = children.length; i < n; ++i) {
nodes.push(children[i]);
} }
}
while (node = next.pop()) {
callback(node);
}
return this;
};
var node_sum = function(value) {
return this.eachAfter(function(node) {
var sum = +value(node.data) || 0,
children = node.children,
i = children && children.length;
while (--i >= 0) { sum += children[i].value; }
node.value = sum;
});
};
var node_sort = function(compare) {
return this.eachBefore(function(node) {
if (node.children) {
node.children.sort(compare);
}
});
};
var node_path = function(end) {
var start = this,
ancestor = leastCommonAncestor(start, end),
nodes = [start];
while (start !== ancestor) {
start = start.parent;
nodes.push(start);
}
var k = nodes.length;
while (end !== ancestor) {
nodes.splice(k, 0, end);
end = end.parent;
}
return nodes;
};
function leastCommonAncestor(a, b) {
if (a === b) { return a; }
var aNodes = a.ancestors(),
bNodes = b.ancestors(),
c = null;
a = aNodes.pop();
b = bNodes.pop();
while (a === b) {
c = a;
a = aNodes.pop();
b = bNodes.pop();
}
return c;
}
var node_ancestors = function() {
var node = this, nodes = [node];
while (node = node.parent) {
nodes.push(node);
}
return nodes;
};
var node_descendants = function() {
var nodes = [];
this.each(function(node) {
nodes.push(node);
});
return nodes;
};
var node_leaves = function() {
var leaves = [];
this.eachBefore(function(node) {
if (!node.children) {
leaves.push(node);
}
});
return leaves;
};
var node_links = function() {
var root = this, links = [];
root.each(function(node) {
if (node !== root) { // Don’t include the root’s parent, if any.
links.push({source: node.parent, target: node});
}
});
return links;
};
function hierarchy(data, children) {
var root = new Node(data),
valued = +data.value && (root.value = data.value),
node,
nodes = [root],
child,
childs,
i,
n;
if (children == null) { children = defaultChildren; }
while (node = nodes.pop()) {
if (valued) { node.value = +node.data.value; }
if ((childs = children(node.data)) && (n = childs.length)) {
node.children = new Array(n);
for (i = n - 1; i >= 0; --i) {
nodes.push(child = node.children[i] = new Node(childs[i]));
child.parent = node;
child.depth = node.depth + 1;
}
}
}
return root.eachBefore(computeHeight);
}
function node_copy() {
return hierarchy(this).eachBefore(copyData);
}
function defaultChildren(d) {
return d.children;
}
function copyData(node) {
node.data = node.data.data;
}
function computeHeight(node) {
var height = 0;
do { node.height = height; }
while ((node = node.parent) && (node.height < ++height));
}
function Node(data) {
this.data = data;
this.depth =
this.height = 0;
this.parent = null;
}
Node.prototype = hierarchy.prototype = {
constructor: Node,
count: node_count,
each: node_each,
eachAfter: node_eachAfter,
eachBefore: node_eachBefore,
sum: node_sum,
sort: node_sort,
path: node_path,
ancestors: node_ancestors,
descendants: node_descendants,
leaves: node_leaves,
links: node_links,
copy: node_copy
};
function Node$2(value) {
this._ = value;
this.next = null;
}
var treemapDice = function(parent, x0, y0, x1, y1) {
var nodes = parent.children,
node,
i = -1,
n = nodes.length,
k = parent.value && (x1 - x0) / parent.value;
while (++i < n) {
node = nodes[i], node.y0 = y0, node.y1 = y1;
node.x0 = x0, node.x1 = x0 += node.value * k;
}
};
function TreeNode(node, i) {
this._ = node;
this.parent = null;
this.children = null;
this.A = null; // default ancestor
this.a = this; // ancestor
this.z = 0; // prelim
this.m = 0; // mod
this.c = 0; // change
this.s = 0; // shift
this.t = null; // thread
this.i = i; // number
}
TreeNode.prototype = Object.create(Node.prototype);
// Node-link tree diagram using the Reingold-Tilford "tidy" algorithm
var treemapSlice = function(parent, x0, y0, x1, y1) {
var nodes = parent.children,
node,
i = -1,
n = nodes.length,
k = parent.value && (y1 - y0) / parent.value;
while (++i < n) {
node = nodes[i], node.x0 = x0, node.x1 = x1;
node.y0 = y0, node.y1 = y0 += node.value * k;
}
};
function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
var rows = [],
nodes = parent.children,
row,
nodeValue,
i0 = 0,
i1 = 0,
n = nodes.length,
dx, dy,
value = parent.value,
sumValue,
minValue,
maxValue,
newRatio,
minRatio,
alpha,
beta;
while (i0 < n) {
dx = x1 - x0, dy = y1 - y0;
// Find the next non-empty node.
do { sumValue = nodes[i1++].value; } while (!sumValue && i1 < n);
minValue = maxValue = sumValue;
alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
beta = sumValue * sumValue * alpha;
minRatio = Math.max(maxValue / beta, beta / minValue);
// Keep adding nodes while the aspect ratio maintains or improves.
for (; i1 < n; ++i1) {
sumValue += nodeValue = nodes[i1].value;
if (nodeValue < minValue) { minValue = nodeValue; }
if (nodeValue > maxValue) { maxValue = nodeValue; }
beta = sumValue * sumValue * alpha;
newRatio = Math.max(maxValue / beta, beta / minValue);
if (newRatio > minRatio) { sumValue -= nodeValue; break; }
minRatio = newRatio;
}
// Position and record the row orientation.
rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)});
if (row.dice) { treemapDice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1); }
else { treemapSlice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1); }
value -= sumValue, i0 = i1;
}
return rows;
}
// Returns the 2D cross product of AB and AC vectors, i.e., the z-component of
// the 3D cross product in a quadrant I Cartesian coordinate system (+x is
// right, +y is up). Returns a positive value if ABC is counter-clockwise,
// negative if clockwise, and zero if the points are collinear.
var cross$1 = function(a, b, c) {
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
};
function lexicographicOrder(a, b) {
return a[0] - b[0] || a[1] - b[1];
}
// Computes the upper convex hull per the monotone chain algorithm.
// Assumes points.length >= 3, is sorted by x, unique in y.
// Returns an array of indices into points in left-to-right order.
function computeUpperHullIndexes(points) {
var n = points.length,
indexes = [0, 1],
size = 2;
for (var i = 2; i < n; ++i) {
while (size > 1 && cross$1(points[indexes[size - 2]], points[indexes[size - 1]], points[i]) <= 0) { --size; }
indexes[size++] = i;
}
return indexes.slice(0, size); // remove popped points
}
var slice$3 = [].slice;
var noabort = {};
function poke$1(q) {
if (!q._start) {
try { start$1(q); } // let the current task complete
catch (e) {
if (q._tasks[q._ended + q._active - 1]) { abort(q, e); } // task errored synchronously
else if (!q._data) { throw e; } // await callback errored synchronously
}
}
}
function start$1(q) {
while (q._start = q._waiting && q._active < q._size) {
var i = q._ended + q._active,
t = q._tasks[i],
j = t.length - 1,
c = t[j];
t[j] = end(q, i);
--q._waiting, ++q._active;
t = c.apply(null, t);
if (!q._tasks[i]) { continue; } // task finished synchronously
q._tasks[i] = t || noabort;
}
}
function end(q, i) {
return function(e, r) {
if (!q._tasks[i]) { return; } // ignore multiple callbacks
--q._active, ++q._ended;
q._tasks[i] = null;
if (q._error != null) { return; } // ignore secondary errors
if (e != null) {
abort(q, e);
} else {
q._data[i] = r;
if (q._waiting) { poke$1(q); }
else { maybeNotify(q); }
}
};
}
function abort(q, e) {
var i = q._tasks.length, t;
q._error = e; // ignore active callbacks
q._data = undefined; // allow gc
q._waiting = NaN; // prevent starting
while (--i >= 0) {
if (t = q._tasks[i]) {
q._tasks[i] = null;
if (t.abort) {
try { t.abort(); }
catch (e) { /* ignore */ }
}
}
}
q._active = NaN; // allow notification
maybeNotify(q);
}
function maybeNotify(q) {
if (!q._active && q._call) {
var d = q._data;
q._data = undefined; // allow gc
q._call(q._error, d);
}
}
var request = function(url, callback) {
var request,
event = dispatch("beforesend", "progress", "load", "error"),
mimeType,
headers = map$1(),
xhr = new XMLHttpRequest,
user = null,
password = null,
response,
responseType,
timeout = 0;
// If IE does not support CORS, use XDomainRequest.
if (typeof XDomainRequest !== "undefined"
&& !("withCredentials" in xhr)
&& /^(http(s)?:)?\/\//.test(url)) { xhr = new XDomainRequest; }
"onload" in xhr
? xhr.onload = xhr.onerror = xhr.ontimeout = respond
: xhr.onreadystatechange = function(o) { xhr.readyState > 3 && respond(o); };
function respond(o) {
var status = xhr.status, result;
if (!status && hasResponse(xhr)
|| status >= 200 && status < 300
|| status === 304) {
if (response) {
try {
result = response.call(request, xhr);
} catch (e) {
event.call("error", request, e);
return;
}
} else {
result = xhr;
}
event.call("load", request, result);
} else {
event.call("error", request, o);
}
}
xhr.onprogress = function(e) {
event.call("progress", request, e);
};
request = {
header: function(name, value) {
name = (name + "").toLowerCase();
if (arguments.length < 2) { return headers.get(name); }
if (value == null) { headers.remove(name); }
else { headers.set(name, value + ""); }
return request;
},
// If mimeType is non-null and no Accept header is set, a default is used.
mimeType: function(value) {
if (!arguments.length) { return mimeType; }
mimeType = value == null ? null : value + "";
return request;
},
// Specifies what type the response value should take;
// for instance, arraybuffer, blob, document, or text.
responseType: function(value) {
if (!arguments.length) { return responseType; }
responseType = value;
return request;
},
timeout: function(value) {
if (!arguments.length) { return timeout; }
timeout = +value;
return request;
},
user: function(value) {
return arguments.length < 1 ? user : (user = value == null ? null : value + "", request);
},
password: function(value) {
return arguments.length < 1 ? password : (password = value == null ? null : value + "", request);
},
// Specify how to convert the response content to a specific type;
// changes the callback value on "load" events.
response: function(value) {
response = value;
return request;
},
// Alias for send("GET", …).
get: function(data, callback) {
return request.send("GET", data, callback);
},
// Alias for send("POST", …).
post: function(data, callback) {
return request.send("POST", data, callback);
},
// If callback is non-null, it will be used for error and load events.
send: function(method, data, callback) {
xhr.open(method, url, true, user, password);
if (mimeType != null && !headers.has("accept")) { headers.set("accept", mimeType + ",*/*"); }
if (xhr.setRequestHeader) { headers.each(function(value, name) { xhr.setRequestHeader(name, value); }); }
if (mimeType != null && xhr.overrideMimeType) { xhr.overrideMimeType(mimeType); }
if (responseType != null) { xhr.responseType = responseType; }
if (timeout > 0) { xhr.timeout = timeout; }
if (callback == null && typeof data === "function") { callback = data, data = null; }
if (callback != null && callback.length === 1) { callback = fixCallback(callback); }
if (callback != null) { request.on("error", callback).on("load", function(xhr) { callback(null, xhr); }); }
event.call("beforesend", request, xhr);
xhr.send(data == null ? null : data);
return request;
},
abort: function() {
xhr.abort();
return request;
},
on: function() {
var value = event.on.apply(event, arguments);
return value === event ? request : value;
}
};
if (callback != null) {
if (typeof callback !== "function") { throw new Error("invalid callback: " + callback); }
return request.get(callback);
}
return request;
};
function fixCallback(callback) {
return function(error, xhr) {
callback(error == null ? xhr : null);
};
}
function hasResponse(xhr) {
var type = xhr.responseType;
return type && type !== "text"
? xhr.response // null on error
: xhr.responseText; // "" on error
}
var type$1 = function(defaultMimeType, response) {
return function(url, callback) {
var r = request(url).mimeType(defaultMimeType).response(response);
if (callback != null) {
if (typeof callback !== "function") { throw new Error("invalid callback: " + callback); }
return r.get(callback);
}
return r;
};
};
type$1("text/html", function(xhr) {
return document.createRange().createContextualFragment(xhr.responseText);
});
type$1("application/json", function(xhr) {
return JSON.parse(xhr.responseText);
});
type$1("text/plain", function(xhr) {
return xhr.responseText;
});
type$1("application/xml", function(xhr) {
var xml = xhr.responseXML;
if (!xml) { throw new Error("parse error"); }
return xml;
});
var dsv$1 = function(defaultMimeType, parse) {
return function(url, row, callback) {
if (arguments.length < 3) { callback = row, row = null; }
var r = request(url).mimeType(defaultMimeType);
r.row = function(_) { return arguments.length ? r.response(responseOf(parse, row = _)) : row; };
r.row(row);
return callback ? r.get(callback) : r;
};
};
function responseOf(parse, row) {
return function(request$$1) {
return parse(request$$1.responseText, row);
};
}
dsv$1("text/csv", csvParse);
dsv$1("text/tab-separated-values", tsvParse);
var array$2 = Array.prototype;
var map$3 = array$2.map;
var slice$4 = array$2.slice;
var implicit = {name: "implicit"};
var constant$9 = function(x) {
return function() {
return x;
};
};
var number$1 = function(x) {
return +x;
};
var unit = [0, 1];
function deinterpolateLinear(a, b) {
return (b -= (a = +a))
? function(x) { return (x - a) / b; }
: constant$9(b);
}
function deinterpolateClamp(deinterpolate) {
return function(a, b) {
var d = deinterpolate(a = +a, b = +b);
return function(x) { return x <= a ? 0 : x >= b ? 1 : d(x); };
};
}
function reinterpolateClamp(reinterpolate$$1) {
return function(a, b) {
var r = reinterpolate$$1(a = +a, b = +b);
return function(t) { return t <= 0 ? a : t >= 1 ? b : r(t); };
};
}
function bimap(domain, range, deinterpolate, reinterpolate$$1) {
var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
if (d1 < d0) { d0 = deinterpolate(d1, d0), r0 = reinterpolate$$1(r1, r0); }
else { d0 = deinterpolate(d0, d1), r0 = reinterpolate$$1(r0, r1); }
return function(x) { return r0(d0(x)); };
}
function polymap(domain, range, deinterpolate, reinterpolate$$1) {
var j = Math.min(domain.length, range.length) - 1,
d = new Array(j),
r = new Array(j),
i = -1;
// Reverse descending domains.
if (domain[j] < domain[0]) {
domain = domain.slice().reverse();
range = range.slice().reverse();
}
while (++i < j) {
d[i] = deinterpolate(domain[i], domain[i + 1]);
r[i] = reinterpolate$$1(range[i], range[i + 1]);
}
return function(x) {
var i = bisectRight(domain, x, 1, j) - 1;
return r[i](d[i](x));
};
}
function copy(source, target) {
return target
.domain(source.domain())
.range(source.range())
.interpolate(source.interpolate())
.clamp(source.clamp());
}
// deinterpolate(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// reinterpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding domain value x in [a,b].
function continuous(deinterpolate, reinterpolate$$1) {
var domain = unit,
range = unit,
interpolate = interpolateValue,
clamp = false,
piecewise,
output,
input;
function rescale() {
piecewise = Math.min(domain.length, range.length) > 2 ? polymap : bimap;
output = input = null;
return scale;
}
function scale(x) {
return (output || (output = piecewise(domain, range, clamp ? deinterpolateClamp(deinterpolate) : deinterpolate, interpolate)))(+x);
}
scale.invert = function(y) {
return (input || (input = piecewise(range, domain, deinterpolateLinear, clamp ? reinterpolateClamp(reinterpolate$$1) : reinterpolate$$1)))(+y);
};
scale.domain = function(_) {
return arguments.length ? (domain = map$3.call(_, number$1), rescale()) : domain.slice();
};
scale.range = function(_) {
return arguments.length ? (range = slice$4.call(_), rescale()) : range.slice();
};
scale.rangeRound = function(_) {
return range = slice$4.call(_), interpolate = interpolateRound, rescale();
};
scale.clamp = function(_) {
return arguments.length ? (clamp = !!_, rescale()) : clamp;
};
scale.interpolate = function(_) {
return arguments.length ? (interpolate = _, rescale()) : interpolate;
};
return rescale();
}
var tickFormat = function(domain, count, specifier) {
var start = domain[0],
stop = domain[domain.length - 1],
step = tickStep(start, stop, count == null ? 10 : count),
precision;
specifier = formatSpecifier(specifier == null ? ",f" : specifier);
switch (specifier.type) {
case "s": {
var value = Math.max(Math.abs(start), Math.abs(stop));
if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) { specifier.precision = precision; }
return formatPrefix(specifier, value);
}
case "":
case "e":
case "g":
case "p":
case "r": {
if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) { specifier.precision = precision - (specifier.type === "e"); }
break;
}
case "f":
case "%": {
if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) { specifier.precision = precision - (specifier.type === "%") * 2; }
break;
}
}
return format(specifier);
};
function linearish(scale) {
var domain = scale.domain;
scale.ticks = function(count) {
var d = domain();
return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
};
scale.tickFormat = function(count, specifier) {
return tickFormat(domain(), count, specifier);
};
scale.nice = function(count) {
if (count == null) { count = 10; }
var d = domain(),
i0 = 0,
i1 = d.length - 1,
start = d[i0],
stop = d[i1],
step;
if (stop < start) {
step = start, start = stop, stop = step;
step = i0, i0 = i1, i1 = step;
}
step = tickIncrement(start, stop, count);
if (step > 0) {
start = Math.floor(start / step) * step;
stop = Math.ceil(stop / step) * step;
step = tickIncrement(start, stop, count);
} else if (step < 0) {
start = Math.ceil(start * step) / step;
stop = Math.floor(stop * step) / step;
step = tickIncrement(start, stop, count);
}
if (step > 0) {
d[i0] = Math.floor(start / step) * step;
d[i1] = Math.ceil(stop / step) * step;
domain(d);
} else if (step < 0) {
d[i0] = Math.ceil(start * step) / step;
d[i1] = Math.floor(stop * step) / step;
domain(d);
}
return scale;
};
return scale;
}
function linear$2() {
var scale = continuous(deinterpolateLinear, reinterpolate);
scale.copy = function() {
return copy(scale, linear$2());
};
return linearish(scale);
}
function deinterpolate(a, b) {
return (b = Math.log(b / a))
? function(x) { return Math.log(x / a) / b; }
: constant$9(b);
}
function reinterpolate$1(a, b) {
return a < 0
? function(t) { return -Math.pow(-b, t) * Math.pow(-a, 1 - t); }
: function(t) { return Math.pow(b, t) * Math.pow(a, 1 - t); };
}
function pow10(x) {
return isFinite(x) ? +("1e" + x) : x < 0 ? 0 : x;
}
function powp(base) {
return base === 10 ? pow10
: base === Math.E ? Math.exp
: function(x) { return Math.pow(base, x); };
}
function logp(base) {
return base === Math.E ? Math.log
: base === 10 && Math.log10
|| base === 2 && Math.log2
|| (base = Math.log(base), function(x) { return Math.log(x) / base; });
}
var t0$1 = new Date;
var t1$1 = new Date;
function newInterval(floori, offseti, count, field) {
function interval(date) {
return floori(date = new Date(+date)), date;
}
interval.floor = interval;
interval.ceil = function(date) {
return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
};
interval.round = function(date) {
var d0 = interval(date),
d1 = interval.ceil(date);
return date - d0 < d1 - date ? d0 : d1;
};
interval.offset = function(date, step) {
return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;
};
interval.range = function(start, stop, step) {
var range = [];
start = interval.ceil(start);
step = step == null ? 1 : Math.floor(step);
if (!(start < stop) || !(step > 0)) { return range; } // also handles Invalid Date
do { range.push(new Date(+start)); } while (offseti(start, step), floori(start), start < stop)
return range;
};
interval.filter = function(test) {
return newInterval(function(date) {
if (date >= date) { while (floori(date), !test(date)) { date.setTime(date - 1); } }
}, function(date, step) {
if (date >= date) { while (--step >= 0) { while (offseti(date, 1), !test(date)) {} } } // eslint-disable-line no-empty
});
};
if (count) {
interval.count = function(start, end) {
t0$1.setTime(+start), t1$1.setTime(+end);
floori(t0$1), floori(t1$1);
return Math.floor(count(t0$1, t1$1));
};
interval.every = function(step) {
step = Math.floor(step);
return !isFinite(step) || !(step > 0) ? null
: !(step > 1) ? interval
: interval.filter(field
? function(d) { return field(d) % step === 0; }
: function(d) { return interval.count(0, d) % step === 0; });
};
}
return interval;
}
var millisecond = newInterval(function() {
// noop
}, function(date, step) {
date.setTime(+date + step);
}, function(start, end) {
return end - start;
});
// An optimized implementation for this simple case.
millisecond.every = function(k) {
k = Math.floor(k);
if (!isFinite(k) || !(k > 0)) { return null; }
if (!(k > 1)) { return millisecond; }
return newInterval(function(date) {
date.setTime(Math.floor(date / k) * k);
}, function(date, step) {
date.setTime(+date + step * k);
}, function(start, end) {
return (end - start) / k;
});
};
var durationSecond$1 = 1e3;
var durationMinute$1 = 6e4;
var durationHour$1 = 36e5;
var durationDay$1 = 864e5;
var durationWeek$1 = 6048e5;
var second = newInterval(function(date) {
date.setTime(Math.floor(date / durationSecond$1) * durationSecond$1);
}, function(date, step) {
date.setTime(+date + step * durationSecond$1);
}, function(start, end) {
return (end - start) / durationSecond$1;
}, function(date) {
return date.getUTCSeconds();
});
var minute = newInterval(function(date) {
date.setTime(Math.floor(date / durationMinute$1) * durationMinute$1);
}, function(date, step) {
date.setTime(+date + step * durationMinute$1);
}, function(start, end) {
return (end - start) / durationMinute$1;
}, function(date) {
return date.getMinutes();
});
var hour = newInterval(function(date) {
var offset = date.getTimezoneOffset() * durationMinute$1 % durationHour$1;
if (offset < 0) { offset += durationHour$1; }
date.setTime(Math.floor((+date - offset) / durationHour$1) * durationHour$1 + offset);
}, function(date, step) {
date.setTime(+date + step * durationHour$1);
}, function(start, end) {
return (end - start) / durationHour$1;
}, function(date) {
return date.getHours();
});
var day = newInterval(function(date) {
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + step);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute$1) / durationDay$1;
}, function(date) {
return date.getDate() - 1;
});
function weekday(i) {
return newInterval(function(date) {
date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + step * 7);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute$1) / durationWeek$1;
});
}
var sunday = weekday(0);
var monday = weekday(1);
var tuesday = weekday(2);
var wednesday = weekday(3);
var thursday = weekday(4);
var friday = weekday(5);
var saturday = weekday(6);
var month = newInterval(function(date) {
date.setDate(1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setMonth(date.getMonth() + step);
}, function(start, end) {
return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date) {
return date.getMonth();
});
var year = newInterval(function(date) {
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step);
}, function(start, end) {
return end.getFullYear() - start.getFullYear();
}, function(date) {
return date.getFullYear();
});
// An optimized implementation for this simple case.
year.every = function(k) {
return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
date.setFullYear(Math.floor(date.getFullYear() / k) * k);
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step * k);
});
};
var utcMinute = newInterval(function(date) {
date.setUTCSeconds(0, 0);
}, function(date, step) {
date.setTime(+date + step * durationMinute$1);
}, function(start, end) {
return (end - start) / durationMinute$1;
}, function(date) {
return date.getUTCMinutes();
});
var utcHour = newInterval(function(date) {
date.setUTCMinutes(0, 0, 0);
}, function(date, step) {
date.setTime(+date + step * durationHour$1);
}, function(start, end) {
return (end - start) / durationHour$1;
}, function(date) {
return date.getUTCHours();
});
var utcDay = newInterval(function(date) {
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step);
}, function(start, end) {
return (end - start) / durationDay$1;
}, function(date) {
return date.getUTCDate() - 1;
});
function utcWeekday(i) {
return newInterval(function(date) {
date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step * 7);
}, function(start, end) {
return (end - start) / durationWeek$1;
});
}
var utcSunday = utcWeekday(0);
var utcMonday = utcWeekday(1);
var utcTuesday = utcWeekday(2);
var utcWednesday = utcWeekday(3);
var utcThursday = utcWeekday(4);
var utcFriday = utcWeekday(5);
var utcSaturday = utcWeekday(6);
var utcMonth = newInterval(function(date) {
date.setUTCDate(1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCMonth(date.getUTCMonth() + step);
}, function(start, end) {
return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date) {
return date.getUTCMonth();
});
var utcYear = newInterval(function(date) {
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step);
}, function(start, end) {
return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date) {
return date.getUTCFullYear();
});
// An optimized implementation for this simple case.
utcYear.every = function(k) {
return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step * k);
});
};
function localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
date.setFullYear(d.y);
return date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
date.setUTCFullYear(d.y);
return date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newYear(y) {
return {y: y, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0};
}
function formatLocale$1(locale) {
var locale_dateTime = locale.dateTime,
locale_date = locale.date,
locale_time = locale.time,
locale_periods = locale.periods,
locale_weekdays = locale.days,
locale_shortWeekdays = locale.shortDays,
locale_months = locale.months,
locale_shortMonths = locale.shortMonths;
var periodRe = formatRe(locale_periods),
periodLookup = formatLookup(locale_periods),
weekdayRe = formatRe(locale_weekdays),
weekdayLookup = formatLookup(locale_weekdays),
shortWeekdayRe = formatRe(locale_shortWeekdays),
shortWeekdayLookup = formatLookup(locale_shortWeekdays),
monthRe = formatRe(locale_months),
monthLookup = formatLookup(locale_months),
shortMonthRe = formatRe(locale_shortMonths),
shortMonthLookup = formatLookup(locale_shortMonths);
var formats = {
"a": formatShortWeekday,
"A": formatWeekday,
"b": formatShortMonth,
"B": formatMonth,
"c": null,
"d": formatDayOfMonth,
"e": formatDayOfMonth,
"H": formatHour24,
"I": formatHour12,
"j": formatDayOfYear,
"L": formatMilliseconds,
"m": formatMonthNumber,
"M": formatMinutes,
"p": formatPeriod,
"S": formatSeconds,
"U": formatWeekNumberSunday,
"w": formatWeekdayNumber,
"W": formatWeekNumberMonday,
"x": null,
"X": null,
"y": formatYear,
"Y": formatFullYear,
"Z": formatZone,
"%": formatLiteralPercent
};
var utcFormats = {
"a": formatUTCShortWeekday,
"A": formatUTCWeekday,
"b": formatUTCShortMonth,
"B": formatUTCMonth,
"c": null,
"d": formatUTCDayOfMonth,
"e": formatUTCDayOfMonth,
"H": formatUTCHour24,
"I": formatUTCHour12,
"j": formatUTCDayOfYear,
"L": formatUTCMilliseconds,
"m": formatUTCMonthNumber,
"M": formatUTCMinutes,
"p": formatUTCPeriod,
"S": formatUTCSeconds,
"U": formatUTCWeekNumberSunday,
"w": formatUTCWeekdayNumber,
"W": formatUTCWeekNumberMonday,
"x": null,
"X": null,
"y": formatUTCYear,
"Y": formatUTCFullYear,
"Z": formatUTCZone,
"%": formatLiteralPercent
};
var parses = {
"a": parseShortWeekday,
"A": parseWeekday,
"b": parseShortMonth,
"B": parseMonth,
"c": parseLocaleDateTime,
"d": parseDayOfMonth,
"e": parseDayOfMonth,
"H": parseHour24,
"I": parseHour24,
"j": parseDayOfYear,
"L": parseMilliseconds,
"m": parseMonthNumber,
"M": parseMinutes,
"p": parsePeriod,
"S": parseSeconds,
"U": parseWeekNumberSunday,
"w": parseWeekdayNumber,
"W": parseWeekNumberMonday,
"x": parseLocaleDate,
"X": parseLocaleTime,
"y": parseYear,
"Y": parseFullYear,
"Z": parseZone,
"%": parseLiteralPercent
};
// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats);
formats.X = newFormat(locale_time, formats);
formats.c = newFormat(locale_dateTime, formats);
utcFormats.x = newFormat(locale_date, utcFormats);
utcFormats.X = newFormat(locale_time, utcFormats);
utcFormats.c = newFormat(locale_dateTime, utcFormats);
function newFormat(specifier, formats) {
return function(date) {
var string = [],
i = -1,
j = 0,
n = specifier.length,
c,
pad,
format;
if (!(date instanceof Date)) { date = new Date(+date); }
while (++i < n) {
if (specifier.charCodeAt(i) === 37) {
string.push(specifier.slice(j, i));
if ((pad = pads[c = specifier.charAt(++i)]) != null) { c = specifier.charAt(++i); }
else { pad = c === "e" ? " " : "0"; }
if (format = formats[c]) { c = format(date, pad); }
string.push(c);
j = i + 1;
}
}
string.push(specifier.slice(j, i));
return string.join("");
};
}
function newParse(specifier, newDate) {
return function(string) {
var d = newYear(1900),
i = parseSpecifier(d, specifier, string += "", 0);
if (i != string.length) { return null; }
// The am-pm flag is 0 for AM, and 1 for PM.
if ("p" in d) { d.H = d.H % 12 + d.p * 12; }
// Convert day-of-week and week-of-year to day-of-year.
if ("W" in d || "U" in d) {
if (!("w" in d)) { d.w = "W" in d ? 1 : 0; }
var day$$1 = "Z" in d ? utcDate(newYear(d.y)).getUTCDay() : newDate(newYear(d.y)).getDay();
d.m = 0;
d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day$$1 + 5) % 7 : d.w + d.U * 7 - (day$$1 + 6) % 7;
}
// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
if ("Z" in d) {
d.H += d.Z / 100 | 0;
d.M += d.Z % 100;
return utcDate(d);
}
// Otherwise, all fields are in local time.
return newDate(d);
};
}
function parseSpecifier(d, specifier, string, j) {
var i = 0,
n = specifier.length,
m = string.length,
c,
parse;
while (i < n) {
if (j >= m) { return -1; }
c = specifier.charCodeAt(i++);
if (c === 37) {
c = specifier.charAt(i++);
parse = parses[c in pads ? specifier.charAt(i++) : c];
if (!parse || ((j = parse(d, string, j)) < 0)) { return -1; }
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
function parsePeriod(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseShortWeekday(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseWeekday(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseShortMonth(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseMonth(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseLocaleDateTime(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
}
function parseLocaleDate(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
}
function parseLocaleTime(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
}
function formatShortWeekday(d) {
return locale_shortWeekdays[d.getDay()];
}
function formatWeekday(d) {
return locale_weekdays[d.getDay()];
}
function formatShortMonth(d) {
return locale_shortMonths[d.getMonth()];
}
function formatMonth(d) {
return locale_months[d.getMonth()];
}
function formatPeriod(d) {
return locale_periods[+(d.getHours() >= 12)];
}
function formatUTCShortWeekday(d) {
return locale_shortWeekdays[d.getUTCDay()];
}
function formatUTCWeekday(d) {
return locale_weekdays[d.getUTCDay()];
}
function formatUTCShortMonth(d) {
return locale_shortMonths[d.getUTCMonth()];
}
function formatUTCMonth(d) {
return locale_months[d.getUTCMonth()];
}
function formatUTCPeriod(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
}
return {
format: function(specifier) {
var f = newFormat(specifier += "", formats);
f.toString = function() { return specifier; };
return f;
},
parse: function(specifier) {
var p = newParse(specifier += "", localDate);
p.toString = function() { return specifier; };
return p;
},
utcFormat: function(specifier) {
var f = newFormat(specifier += "", utcFormats);
f.toString = function() { return specifier; };
return f;
},
utcParse: function(specifier) {
var p = newParse(specifier, utcDate);
p.toString = function() { return specifier; };
return p;
}
};
}
var pads = {"-": "", "_": " ", "0": "0"};
var numberRe = /^\s*\d+/;
var percentRe = /^%/;
var requoteRe = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
function pad(value, fill, width) {
var sign = value < 0 ? "-" : "",
string = (sign ? -value : value) + "",
length = string.length;
return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}
function requote(s) {
return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
var map = {}, i = -1, n = names.length;
while (++i < n) { map[names[i].toLowerCase()] = i; }
return map;
}
function parseWeekdayNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 4));
return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}
function parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?:\:?(\d\d))?/.exec(string.slice(i, i + 6));
return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseMonthNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseLiteralPercent(d, string, i) {
var n = percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function formatDayOfMonth(d, p) {
return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
return pad(1 + day.count(year(d), d), p, 3);
}
function formatMilliseconds(d, p) {
return pad(d.getMilliseconds(), p, 3);
}
function formatMonthNumber(d, p) {
return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
return pad(d.getSeconds(), p, 2);
}
function formatWeekNumberSunday(d, p) {
return pad(sunday.count(year(d), d), p, 2);
}
function formatWeekdayNumber(d) {
return d.getDay();
}
function formatWeekNumberMonday(d, p) {
return pad(monday.count(year(d), d), p, 2);
}
function formatYear(d, p) {
return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
return pad(d.getFullYear() % 10000, p, 4);
}
function formatZone(d) {
var z = d.getTimezoneOffset();
return (z > 0 ? "-" : (z *= -1, "+"))
+ pad(z / 60 | 0, "0", 2)
+ pad(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
return pad(1 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMonthNumber(d, p) {
return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekNumberSunday(d, p) {
return pad(utcSunday.count(utcYear(d), d), p, 2);
}
function formatUTCWeekdayNumber(d) {
return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
return pad(utcMonday.count(utcYear(d), d), p, 2);
}
function formatUTCYear(d, p) {
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCZone() {
return "+0000";
}
function formatLiteralPercent() {
return "%";
}
var locale$2;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;
defaultLocale$1({
dateTime: "%x, %X",
date: "%-m/%-d/%Y",
time: "%-I:%M:%S %p",
periods: ["AM", "PM"],
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
function defaultLocale$1(definition) {
locale$2 = formatLocale$1(definition);
timeFormat = locale$2.format;
timeParse = locale$2.parse;
utcFormat = locale$2.utcFormat;
utcParse = locale$2.utcParse;
return locale$2;
}
var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ";
function formatIsoNative(date) {
return date.toISOString();
}
var formatIso = Date.prototype.toISOString
? formatIsoNative
: utcFormat(isoSpecifier);
function parseIsoNative(string) {
var date = new Date(string);
return isNaN(date) ? null : date;
}
var parseIso = +new Date("2000-01-01T00:00:00.000Z")
? parseIsoNative
: utcParse(isoSpecifier);
var colors = function(s) {
return s.match(/.{6}/g).map(function(x) {
return "#" + x;
});
};
colors("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf");
colors("393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6");
colors("3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9");
colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5");
cubehelixLong(cubehelix(300, 0.5, 0.0), cubehelix(-240, 0.5, 1.0));
var warm = cubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.50, 0.8));
var cool = cubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.50, 0.8));
var rainbow = cubehelix();
var constant$10 = function(x) {
return function constant() {
return x;
};
};
function Linear(context) {
this._context = context;
}
Linear.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
if (this._line || (this._line !== 0 && this._point === 1)) { this._context.closePath(); }
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; // proceed
default: this._context.lineTo(x, y); break;
}
}
};
var curveLinear = function(context) {
return new Linear(context);
};
function x$3(p) {
return p[0];
}
function y$3(p) {
return p[1];
}
var line = function() {
var x = x$3,
y = y$3,
defined = constant$10(true),
context = null,
curve = curveLinear,
output = null;
function line(data) {
var i,
n = data.length,
d,
defined0 = false,
buffer;
if (context == null) { output = curve(buffer = path()); }
for (i = 0; i <= n; ++i) {
if (!(i < n && defined(d = data[i], i, data)) === defined0) {
if (defined0 = !defined0) { output.lineStart(); }
else { output.lineEnd(); }
}
if (defined0) { output.point(+x(d, i, data), +y(d, i, data)); }
}
if (buffer) { return output = null, buffer + "" || null; }
}
line.x = function(_) {
return arguments.length ? (x = typeof _ === "function" ? _ : constant$10(+_), line) : x;
};
line.y = function(_) {
return arguments.length ? (y = typeof _ === "function" ? _ : constant$10(+_), line) : y;
};
line.defined = function(_) {
return arguments.length ? (defined = typeof _ === "function" ? _ : constant$10(!!_), line) : defined;
};
line.curve = function(_) {
return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
};
line.context = function(_) {
return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
};
return line;
};
function sign$1(x) {
return x < 0 ? -1 : 1;
}
// Calculate the slopes of the tangents (Hermite-type interpolation) based on
// the following paper: Steffen, M. 1990. A Simple Method for Monotonic
// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.
// NOV(II), P. 443, 1990.
function slope3(that, x2, y2) {
var h0 = that._x1 - that._x0,
h1 = x2 - that._x1,
s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),
s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),
p = (s0 * h1 + s1 * h0) / (h0 + h1);
return (sign$1(s0) + sign$1(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}
// Calculate a one-sided slope.
function slope2(that, t) {
var h = that._x1 - that._x0;
return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}
// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations
// "you can express cubic Hermite interpolation in terms of cubic Bézier curves
// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1".
function point$5(that, t0, t1) {
var x0 = that._x0,
y0 = that._y0,
x1 = that._x1,
y1 = that._y1,
dx = (x1 - x0) / 3;
that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
}
function MonotoneX(context) {
this._context = context;
}
MonotoneX.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 =
this._y0 = this._y1 =
this._t0 = NaN;
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 2: this._context.lineTo(this._x1, this._y1); break;
case 3: point$5(this, this._t0, slope2(this, this._t0)); break;
}
if (this._line || (this._line !== 0 && this._point === 1)) { this._context.closePath(); }
this._line = 1 - this._line;
},
point: function(x, y) {
var t1 = NaN;
x = +x, y = +y;
if (x === this._x1 && y === this._y1) { return; } // Ignore coincident points.
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; break;
case 2: this._point = 3; point$5(this, slope2(this, t1 = slope3(this, x, y)), t1); break;
default: point$5(this, this._t0, t1 = slope3(this, x, y)); break;
}
this._x0 = this._x1, this._x1 = x;
this._y0 = this._y1, this._y1 = y;
this._t0 = t1;
}
};
function MonotoneY(context) {
this._context = new ReflectContext(context);
}
(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {
MonotoneX.prototype.point.call(this, y, x);
};
function ReflectContext(context) {
this._context = context;
}
ReflectContext.prototype = {
moveTo: function(x, y) { this._context.moveTo(y, x); },
closePath: function() { this._context.closePath(); },
lineTo: function(x, y) { this._context.lineTo(y, x); },
bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }
};
function createBorderEdge(left, v0, v1) {
var edge = [v0, v1];
edge.left = left;
return edge;
}
// Liang–Barsky line clipping.
function clipEdge(edge, x0, y0, x1, y1) {
var a = edge[0],
b = edge[1],
ax = a[0],
ay = a[1],
bx = b[0],
by = b[1],
t0 = 0,
t1 = 1,
dx = bx - ax,
dy = by - ay,
r;
r = x0 - ax;
if (!dx && r > 0) { return; }
r /= dx;
if (dx < 0) {
if (r < t0) { return; }
if (r < t1) { t1 = r; }
} else if (dx > 0) {
if (r > t1) { return; }
if (r > t0) { t0 = r; }
}
r = x1 - ax;
if (!dx && r < 0) { return; }
r /= dx;
if (dx < 0) {
if (r > t1) { return; }
if (r > t0) { t0 = r; }
} else if (dx > 0) {
if (r < t0) { return; }
if (r < t1) { t1 = r; }
}
r = y0 - ay;
if (!dy && r > 0) { return; }
r /= dy;
if (dy < 0) {
if (r < t0) { return; }
if (r < t1) { t1 = r; }
} else if (dy > 0) {
if (r > t1) { return; }
if (r > t0) { t0 = r; }
}
r = y1 - ay;
if (!dy && r < 0) { return; }
r /= dy;
if (dy < 0) {
if (r > t1) { return; }
if (r > t0) { t0 = r; }
} else if (dy > 0) {
if (r < t0) { return; }
if (r < t1) { t1 = r; }
}
if (!(t0 > 0) && !(t1 < 1)) { return true; } // TODO Better check?
if (t0 > 0) { edge[0] = [ax + t0 * dx, ay + t0 * dy]; }
if (t1 < 1) { edge[1] = [ax + t1 * dx, ay + t1 * dy]; }
return true;
}
function connectEdge(edge, x0, y0, x1, y1) {
var v1 = edge[1];
if (v1) { return true; }
var v0 = edge[0],
left = edge.left,
right = edge.right,
lx = left[0],
ly = left[1],
rx = right[0],
ry = right[1],
fx = (lx + rx) / 2,
fy = (ly + ry) / 2,
fm,
fb;
if (ry === ly) {
if (fx < x0 || fx >= x1) { return; }
if (lx > rx) {
if (!v0) { v0 = [fx, y0]; }
else if (v0[1] >= y1) { return; }
v1 = [fx, y1];
} else {
if (!v0) { v0 = [fx, y1]; }
else if (v0[1] < y0) { return; }
v1 = [fx, y0];
}
} else {
fm = (lx - rx) / (ry - ly);
fb = fy - fm * fx;
if (fm < -1 || fm > 1) {
if (lx > rx) {
if (!v0) { v0 = [(y0 - fb) / fm, y0]; }
else if (v0[1] >= y1) { return; }
v1 = [(y1 - fb) / fm, y1];
} else {
if (!v0) { v0 = [(y1 - fb) / fm, y1]; }
else if (v0[1] < y0) { return; }
v1 = [(y0 - fb) / fm, y0];
}
} else {
if (ly < ry) {
if (!v0) { v0 = [x0, fm * x0 + fb]; }
else if (v0[0] >= x1) { return; }
v1 = [x1, fm * x1 + fb];
} else {
if (!v0) { v0 = [x1, fm * x1 + fb]; }
else if (v0[0] < x0) { return; }
v1 = [x0, fm * x0 + fb];
}
}
}
edge[0] = v0;
edge[1] = v1;
return true;
}
function cellHalfedgeStart(cell, edge) {
return edge[+(edge.left !== cell.site)];
}
function cellHalfedgeEnd(cell, edge) {
return edge[+(edge.left === cell.site)];
}
var epsilon$4 = 1e-6;
var cells;
var edges;
function triangleArea(a, b, c) {
return (a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1]);
}
var createAttendeesChart = function (container, data, config) {
var height = config.height;
var heightInner = config.heightInner;
var padding = config.padding;
var width = config.width;
var widthInner = config.widthInner;
var attendeesMax = max(data, function (d) { return d.attendees.length; });
var barWidth = (widthInner / data.length) * .95;
var barWidthHalf = barWidth * .5;
var fontSize = 16;
var scaleX = linear$2()
.domain([0, data.length])
.range([padding, padding + widthInner]);
var scaleY = linear$2()
.domain([0, attendeesMax])
.range([padding, padding + heightInner - padding - fontSize]);
var color$$1 = linear$2()
.domain([0, data.length])
.range(['#00709f', '#009de0']);
var svg = select(container)
.attr('height', height)
.attr('width', width);
var entry = svg.selectAll('g')
.data(data)
.enter().append('g');
entry.append('rect')
.attr('x', function (d, i) { return scaleX(i); })
.attr('y', function (d) { return scaleY(attendeesMax) + padding - scaleY(d.attendees.length); })
.attr('fill', function (d, i) { return color$$1(i); })
.attr('height', function (d) { return scaleY(d.attendees.length); })
.attr('width', barWidth);
entry.append('text')
.attr('class', 'chart__value text-middle')
.attr('x', function (d, i) { return barWidthHalf + scaleX(i); })
.attr('y', scaleY(attendeesMax))
.text(function (d) { return d.attendees.length; });
entry.append('text')
.attr('class', 'text-middle')
.attr('x', function (d, i) { return barWidthHalf + scaleX(i); })
.attr('y', scaleY(attendeesMax) + padding + padding)
.text(function (d, i) { return i + 2008; });
};
var getDataSimilarityRatio = function (accessor) {
var getSmallestArray = function (a, b) { return a.length < b.length ? a : b; };
var getLargestArray = function (a, b) { return a.length > b.length ? a : b; };
return {
data: function data(a, b) {
var c = getSmallestArray(a, b);
var d = getLargestArray(a, b);
return d.reduce(function (equalObjectCount, value) {
var key = accessor(value);
var isInOtherArray = c.some(function (d) { return key === accessor(d); });
if (isInOtherArray) {
return equalObjectCount + 1;
}
return equalObjectCount;
}, 0) / d.length;
},
};
};
var createReturningAttendeesChart = function (container, data, config) {
var height = config.height;
var heightInner = config.heightInner;
var padding = config.padding;
var width = config.width;
var widthInner = config.widthInner;
var returningAttendees = data.map(function (edition, i) {
if (i === 0) { return 0; }
var previousEdition = data[i - 1];
return getDataSimilarityRatio(function (d) { return d.name; })
.data(edition.attendees, previousEdition.attendees);
});
var barWidth = widthInner / data.length;
var barWidthHalf = barWidth * .5;
var fontSize = 16;
var scaleX = linear$2()
.domain([0, data.length])
.range([padding, padding + widthInner]);
var scaleY = linear$2()
.domain([0, 1])
.range([padding, padding + heightInner - padding]);
var svg = select(container)
.attr('height', height)
.attr('width', width);
var line$$1 = line()
.x(function (d, i) { return scaleX(i); })
.y(function (d) { return scaleY(1) - scaleY(d); });
var entry = svg.selectAll('g')
.data(returningAttendees)
.enter().append('g');
entry.append('path')
.attr('class', 'chart__line')
.datum(returningAttendees)
.attr('d', line$$1);
entry.append('circle')
.attr('class', 'chart__line-point')
.attr('cx', function (d, i) { return scaleX(i); })
.attr('cy', function (d) { return scaleY(1) - scaleY(d); })
.attr('r', 4);
entry.append('text')
.attr('class', 'chart__line-value text-middle')
.attr('x', function (d, i) { return scaleX(i); })
.attr('y', function (d) { return scaleY(1) - scaleY(d) + fontSize * 2; })
.text(function (d) { return format('.0%')(d); });
entry.append('text')
.attr('class', 'text-middle')
.attr('x', function (d, i) { return barWidthHalf + scaleX(i); })
.attr('y', scaleY(1) + padding + padding)
.text(function (d, i) { return i + 2008; });
};
var arrayUnique = function (arr, value) {
if (arr.indexOf(value) === -1) {
arr.push(value);
}
return arr;
};
var compareEntriesByValueAndKey = function (a, b) {
var diff = b.value - a.value;
if (diff === 0) {
return a.key.localeCompare(b.key);
}
return diff;
};
var countSimilarObjects = function () {
var getKey = function (d) { return d; };
return {
key: function key(f) {
getKey = f;
return this;
},
data: function data(data$1) {
return data$1.reduce(function (obj, item) {
var key = getKey(item);
if (!(key in obj)) {
obj[key] = 0;
}
obj[key]++;
return obj;
}, {});
},
};
};
var getAttendees = function (data) { return data.reduce(function (total, d) { return total.concat(d.attendees); }, []); };
var createTopAttendeesList = function (container, data) {
var list = select(container);
var attendees = getAttendees(data);
var attendeesTop = countSimilarObjects()
.key(function (d) { return d.name; })
.data(attendees);
var attendeesTopEntries = entries(attendeesTop)
.filter(function (d) { return d.value > 1; })
.sort(compareEntriesByValueAndKey);
var valueMapping = attendeesTopEntries
.map(function (d) { return d.value; })
.reduce(arrayUnique, []);
list.selectAll('li')
.data(attendeesTopEntries)
.enter().append('li')
.attr('value', function (d) { return valueMapping.indexOf(d.value) + 1; })
.text(function (d) { return ((d.key) + " (" + (d.value) + ")"); });
};
var createTopFirstNameList = function (container, data) {
var list = select(container);
var attendees = getAttendees(data);
var attendeesTop = countSimilarObjects()
.key(function (d) { return d.name.split(' ').shift(); })
.data(attendees);
var attendeesTopEntries = entries(attendeesTop)
.sort(compareEntriesByValueAndKey);
var valueMapping = attendeesTopEntries
.map(function (d) { return d.value; })
.reduce(arrayUnique, []);
list.selectAll('li')
.data(attendeesTopEntries)
.enter().append('li')
.attr('value', function (d) { return valueMapping.indexOf(d.value) + 1; })
.text(function (d) { return ((d.key) + " (" + (d.value) + ")"); });
};
var hasAttendee = function (edition, name) { return edition.attendees
.some(function (attendee) { return attendee.name === name; }); };
var createLoyalAttendees = function (container, data, config) {
var height = config.height;
var heightInner = config.heightInner;
var padding = config.padding;
var width = config.width;
var widthInner = config.widthInner;
var returningAttendees = data.map(function (edition, i, editions) {
if (i === 0) { return 1; }
var firstEdition = editions[0];
var previousEdition = editions[i - 1];
var returning = 0;
edition.attendees.forEach(function (attendee) {
returning += hasAttendee(firstEdition, attendee.name) ? 1 : 0;
});
return returning / firstEdition.attendees.length;
});
var barWidth = (widthInner / data.length) * .95;
var barWidthHalf = barWidth * .5;
var fontSize = 16;
var scaleX = linear$2()
.domain([0, data.length])
.range([padding, padding + widthInner]);
var scaleY = linear$2()
.domain([0, 1])
.range([padding, padding + heightInner - padding - fontSize]);
var color$$1 = linear$2()
.domain([0, data.length])
.range(['#00709f', '#009de0']);
var svg = select(container)
.attr('height', height)
.attr('width', width);
var entry = svg.selectAll('g')
.data(returningAttendees)
.enter().append('g');
entry.append('rect')
.attr('x', function (d, i) { return scaleX(i); })
.attr('y', function (d) { return scaleY(1) + padding - scaleY(d); })
.attr('fill', function (d, i) { return color$$1(i); })
.attr('height', function (d) { return scaleY(d); })
.attr('width', barWidth);
entry.append('text')
.attr('class', 'chart__value text-middle')
.attr('x', function (d, i) { return barWidthHalf + scaleX(i); })
.attr('y', scaleY(1))
.text(function (d) { return format('.1%')(d); });
entry.append('text')
.attr('class', 'text-middle')
.attr('x', function (d, i) { return barWidthHalf + scaleX(i); })
.attr('y', scaleY(1) + padding + padding)
.text(function (d, i) { return i + 2008; });
};
var CLASS = 'expandable-list';
var CLASS_COLLAPSED = 'expandable-list--collapsed';
var insertAfter = function (newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
};
var toggle = function (list, button) {
list.classList.toggle(CLASS_COLLAPSED);
button.textContent = list.classList.contains(CLASS_COLLAPSED)
? list.dataset.labelExpand
: list.dataset.labelCollapse;
};
var createExpandableList = function (list, length) {
if ( length === void 0 ) length = 10;
var button = document.createElement('button');
button.textContent = list.dataset.labelExpand;
insertAfter(button, list);
list.classList.add(CLASS, CLASS_COLLAPSED);
button.addEventListener('click', function () { return toggle(list, button); });
};
var chartAttendees = document.querySelector('.js-chart-attendees');
var chartReturningAttendees = document.querySelector('.js-chart-returning-attendees');
var listTopAttendees = document.querySelector('.js-list-top-attendees');
var listTopFirstNames = document.querySelector('.js-list-top-first-names');
var chartLoyalAttendees = document.querySelector('.js-chart-loyal-attendees');
var chartConfig = createChartConfig(chartAttendees.parentElement);
fetch('data/attendees.json')
.then(fetchError)
.then(function (response) { return response.json(); })
.then(function (response) {
createAttendeesChart(chartAttendees, response, chartConfig);
createReturningAttendeesChart(chartReturningAttendees, response, chartConfig);
createTopAttendeesList(listTopAttendees, response);
createTopFirstNameList(listTopFirstNames, response);
createLoyalAttendees(chartLoyalAttendees, response, chartConfig);
})
.then(function () {
createExpandableList(listTopAttendees);
createExpandableList(listTopFirstNames);
})
.catch(console.error);
}());
//# sourceMappingURL=main.js.map
|
/* global require */
(function() {
'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var files = {
js: 'app/js/*.js'
};
var tasks = {
watch: 'watch',
lint: 'lint'
};
var lintFiles = [files.js, 'Gulpfile.js'];
var eslintConfig = {
globals: [
'$',
'SparkMD5'
]
};
gulp.task(tasks.lint, function () {
return gulp.src(lintFiles)
.pipe(eslint(eslintConfig))
.pipe(eslint.format());
});
gulp.task(tasks.watch, [tasks.lint], function () {
gulp.watch(lintFiles, [tasks.lint]);
});
gulp.task('default', [tasks.watch]);
}());
|
var app = app || {};
(function(){
app.TestButton = React.createClass({displayName: "TestButton",
handleClick: function() {
//this.props.submitTestTask(this.props.btnType);
},
render: function() {
return ( React.createElement("button", {onClick: this.handleClick,
className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) );
}
});
app.CodeEditor = React.createClass({displayName: "CodeEditor",
handleType:function(){
console.log(this.props.code);
},
componentDidMount:function(){
},
render:function(){
return (
React.createElement("div", {id: "codeeditor", onKeyPress: this.handleType, ref: "codes"}, this.props.code)
);
}
});
})();
|
/*--------Original/Nick combo---------------*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var truckSchema = Schema({
truckName: String,
currentAddress: String,
foodType: String,
active: Boolean
});
module.exports = mongoose.model('Truck', truckSchema);
/*
There are many ways of doing the same thing
in javascript and this is one of them. There are three
setups defined below that would all potentially work
with a few tweaks.
*/
/*--------Original setup-------------*/
// var mongoose = require('mongoose');
// var Truck = new mongoose.Schema({
// truckName: String,
// currentAddress: String,
// foodType: String,
// active: Boolean
// });
// module.exports = mongoose.model('Truck', Truck);
/* This exports the 'Truck' model, defined above,
so that it can be called in by the index.js file
inside the routes folder as follows:
var TruckSchema = require('../schemas/truck'); */
/*--------------------------------------*/
//Nick's example
// var mongoose = require('mongoose');
// var Schema = mongoose.Schema
// var trucksSchema = new Schema ({
// truckName: String,
// currentAddress: String,
// foodType: String,
// active: Boolean,
// });
// mongoose.model('trucks', trucksSchema);
/*
Nick --- we need module.exports here as you
can see on line 37. Otherwise the routes > index.js
on lines 2 or 3 cannot see this new mongoose schema
we setup here
*/
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* 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 Ajax.org B.V. nor the
* names of its 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-mutedrainbow-sky";
exports.cssText = require("../requirejs/text!./mutedrainbow_sky.css");
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
/**
* Node.js API Starter Kit (https://reactstarter.com/nodejs)
*
* Copyright © 2016-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* @flow */
/* eslint-disable global-require, no-underscore-dangle */
import { nodeDefinitions, fromGlobalId } from 'graphql-relay';
const { nodeInterface, nodeField: node, nodesField: nodes } = nodeDefinitions(
(globalId, context) => {
const { type, id } = fromGlobalId(globalId);
if (type === 'User') return context.users.load(id);
if (type === 'Story') return context.stories.load(id);
if (type === 'Comment') return context.comments.load(id);
return null;
},
(obj) => {
if (obj.__type === 'User') return require('./UserType').default;
if (obj.__type === 'Story') return require('./StoryType').default;
if (obj.__type === 'Comment') return require('./CommentType').default;
return null;
},
);
export { nodeInterface, node, nodes };
|
$(function () {
var serie;
function onMessage(e) {
if (serie){
var shift;
if (serie.data.length > 10){
shift = true;
}else{
shift = false;
}
serie.addPoint([parseInt(e.data, 10)], true, shift);
}
}
function onClose() {
console.log("Connection closed.");
}
$.getJSON('./data/', function(data){
$('#chart').highcharts(data);
serie = $('#chart').highcharts().series[0];
});
websocket = new WebSocket("ws://"+ window.location.host + window.location.pathname + "streaming/");
websocket.onmessage = onMessage;
websocket.onclose = onClose;
});
|
define(['chaplin', 'views/site-view'], function(Chaplin, SiteView) {
'use strict';
var Controller = Chaplin.Controller.extend({
// Place your application-specific controller features here.
beforeAction: function() {
this.compose('site', SiteView);
}
});
return Controller;
});
|
'use strict';
angular.module('app', ['ui.bootstrap']); |
export default function throttle(fcn, threshhold) {
let last = 0
let timeout = null
return (...args) => {
const time = new Date().getTime()
if (time < last + threshhold) {
clearTimeout(timeout)
timeout = setTimeout(() => {
last = time
fcn.apply(this, args)
}, threshhold)
} else {
last = time
fcn.apply(this, args)
}
}
}
|
import { Bullhorn } from './Bullhorn';
import { Deferred } from './Deferred';
import { QueryString } from './QueryString';
export class Query {
constructor(endpoint) {
this.endpoint = endpoint;
this.records = [];
this._page = 0;
this.WHERE = 'where';
this.ORDER = 'orderBy';
this.parameters = {
fields: ['id'],
start: 0,
count: 10
};
}
fields(...args) {
this.parameters.fields = args[0] instanceof Array ? args[0] : args;
return this;
}
sort(...args) {
this.parameters[this.ORDER] = args[0] instanceof Array ? args[0] : args;
return this;
}
query(value) {
this.parameters[this.WHERE] = value;
return this;
}
count(value) {
this.parameters.count = value;
return this;
}
page(value) {
this._page = value;
this.parameters.start = this.parameters.count * value;
return this;
}
nextpage() {
this.page(++this._page);
return this.run(true);
}
params(object) {
this.parameters = Object.assign(this.parameters, object);
return this;
}
get(add) {
return this.run(add);
}
run(add) {
let interceptor = new Deferred();
let request;
//BH-15325: Akamai has a query string limit.
let too_long = new QueryString('', this.parameters).toString().length > 8000;
if ( too_long ) {
request = Bullhorn.http().post(this.endpoint, this.parameters)
} else {
request = Bullhorn.http().get(this.endpoint, this.parameters)
}
request
.then( (response) => {
if(add) this.records = this.records.concat(response.data);
else this.records = response.data;
interceptor.resolve(response);
})
.catch( (message) => {
interceptor.reject(message);
});
return interceptor;
}
}
|
const page1 = `
<p>
<h1>This is page 1</h1>
</p>
`;
export default page1; |
$(document).ready(function() {
$("#arrow").on('click', function(event) {
console.log("I reached here!");
$('html, body').animate({
scrollTop: $("#about-me").offset().top
}, 1200);
});
var colors = ['#4744AE', '#800F80', '#F5A503', '#3AA1BF'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
$('.color-word').css('color', random_color);
//settings
(function($) {
"use strict";
var $navbar = $("#navbar"),
y_pos = $navbar.offset().top,
height = $navbar.height();
$(document).scroll(function() {
var scrollTop = $(this).scrollTop();
if (scrollTop > y_pos + height) {
$navbar.addClass("navbar-fixed").animate({
top: 0
});
} else if (scrollTop <= y_pos) {
$navbar.removeClass("navbar-fixed").clearQueue().animate({
top: "-48px"
}, 0);
}
});
})(jQuery, undefined);
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
// Scroll to inline links
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
|
/*!
* AngularJS Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.7
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.menuBar
*/
angular.module('material.components.menuBar', [
'material.core',
'material.components.icon',
'material.components.menu'
]);
MenuBarController['$inject'] = ["$scope", "$rootScope", "$element", "$attrs", "$mdConstant", "$document", "$mdUtil", "$timeout"];
angular
.module('material.components.menuBar')
.controller('MenuBarController', MenuBarController);
var BOUND_MENU_METHODS = ['handleKeyDown', 'handleMenuHover', 'scheduleOpenHoveredMenu', 'cancelScheduledOpen'];
/**
* ngInject
*/
function MenuBarController($scope, $rootScope, $element, $attrs, $mdConstant, $document, $mdUtil, $timeout) {
this.$element = $element;
this.$attrs = $attrs;
this.$mdConstant = $mdConstant;
this.$mdUtil = $mdUtil;
this.$document = $document;
this.$scope = $scope;
this.$rootScope = $rootScope;
this.$timeout = $timeout;
var self = this;
angular.forEach(BOUND_MENU_METHODS, function(methodName) {
self[methodName] = angular.bind(self, self[methodName]);
});
}
MenuBarController.prototype.init = function() {
var $element = this.$element;
var $mdUtil = this.$mdUtil;
var $scope = this.$scope;
var self = this;
var deregisterFns = [];
$element.on('keydown', this.handleKeyDown);
this.parentToolbar = $mdUtil.getClosest($element, 'MD-TOOLBAR');
deregisterFns.push(this.$rootScope.$on('$mdMenuOpen', function(event, el) {
if (self.getMenus().indexOf(el[0]) != -1) {
$element[0].classList.add('md-open');
el[0].classList.add('md-open');
self.currentlyOpenMenu = el.controller('mdMenu');
self.currentlyOpenMenu.registerContainerProxy(self.handleKeyDown);
self.enableOpenOnHover();
}
}));
deregisterFns.push(this.$rootScope.$on('$mdMenuClose', function(event, el, opts) {
var rootMenus = self.getMenus();
if (rootMenus.indexOf(el[0]) != -1) {
$element[0].classList.remove('md-open');
el[0].classList.remove('md-open');
}
if ($element[0].contains(el[0])) {
var parentMenu = el[0];
while (parentMenu && rootMenus.indexOf(parentMenu) == -1) {
parentMenu = $mdUtil.getClosest(parentMenu, 'MD-MENU', true);
}
if (parentMenu) {
if (!opts.skipFocus) parentMenu.querySelector('button:not([disabled])').focus();
self.currentlyOpenMenu = undefined;
self.disableOpenOnHover();
self.setKeyboardMode(true);
}
}
}));
$scope.$on('$destroy', function() {
self.disableOpenOnHover();
while (deregisterFns.length) {
deregisterFns.shift()();
}
});
this.setKeyboardMode(true);
};
MenuBarController.prototype.setKeyboardMode = function(enabled) {
if (enabled) this.$element[0].classList.add('md-keyboard-mode');
else this.$element[0].classList.remove('md-keyboard-mode');
};
MenuBarController.prototype.enableOpenOnHover = function() {
if (this.openOnHoverEnabled) return;
var self = this;
self.openOnHoverEnabled = true;
if (self.parentToolbar) {
self.parentToolbar.classList.add('md-has-open-menu');
// Needs to be on the next tick so it doesn't close immediately.
self.$mdUtil.nextTick(function() {
angular.element(self.parentToolbar).on('click', self.handleParentClick);
}, false);
}
angular
.element(self.getMenus())
.on('mouseenter', self.handleMenuHover);
};
MenuBarController.prototype.handleMenuHover = function(e) {
this.setKeyboardMode(false);
if (this.openOnHoverEnabled) {
this.scheduleOpenHoveredMenu(e);
}
};
MenuBarController.prototype.disableOpenOnHover = function() {
if (!this.openOnHoverEnabled) return;
this.openOnHoverEnabled = false;
if (this.parentToolbar) {
this.parentToolbar.classList.remove('md-has-open-menu');
angular.element(this.parentToolbar).off('click', this.handleParentClick);
}
angular
.element(this.getMenus())
.off('mouseenter', this.handleMenuHover);
};
MenuBarController.prototype.scheduleOpenHoveredMenu = function(e) {
var menuEl = angular.element(e.currentTarget);
var menuCtrl = menuEl.controller('mdMenu');
this.setKeyboardMode(false);
this.scheduleOpenMenu(menuCtrl);
};
MenuBarController.prototype.scheduleOpenMenu = function(menuCtrl) {
var self = this;
var $timeout = this.$timeout;
if (menuCtrl != self.currentlyOpenMenu) {
$timeout.cancel(self.pendingMenuOpen);
self.pendingMenuOpen = $timeout(function() {
self.pendingMenuOpen = undefined;
if (self.currentlyOpenMenu) {
self.currentlyOpenMenu.close(true, { closeAll: true });
}
menuCtrl.open();
}, 200, false);
}
};
MenuBarController.prototype.handleKeyDown = function(e) {
var keyCodes = this.$mdConstant.KEY_CODE;
var currentMenu = this.currentlyOpenMenu;
var wasOpen = currentMenu && currentMenu.isOpen;
this.setKeyboardMode(true);
var handled, newMenu, newMenuCtrl;
switch (e.keyCode) {
case keyCodes.DOWN_ARROW:
if (currentMenu) {
currentMenu.focusMenuContainer();
} else {
this.openFocusedMenu();
}
handled = true;
break;
case keyCodes.UP_ARROW:
currentMenu && currentMenu.close();
handled = true;
break;
case keyCodes.LEFT_ARROW:
newMenu = this.focusMenu(-1);
if (wasOpen) {
newMenuCtrl = angular.element(newMenu).controller('mdMenu');
this.scheduleOpenMenu(newMenuCtrl);
}
handled = true;
break;
case keyCodes.RIGHT_ARROW:
newMenu = this.focusMenu(+1);
if (wasOpen) {
newMenuCtrl = angular.element(newMenu).controller('mdMenu');
this.scheduleOpenMenu(newMenuCtrl);
}
handled = true;
break;
}
if (handled) {
e && e.preventDefault && e.preventDefault();
e && e.stopImmediatePropagation && e.stopImmediatePropagation();
}
};
MenuBarController.prototype.focusMenu = function(direction) {
var menus = this.getMenus();
var focusedIndex = this.getFocusedMenuIndex();
if (focusedIndex == -1) { focusedIndex = this.getOpenMenuIndex(); }
var changed = false;
if (focusedIndex == -1) { focusedIndex = 0; changed = true; }
else if (
direction < 0 && focusedIndex > 0 ||
direction > 0 && focusedIndex < menus.length - direction
) {
focusedIndex += direction;
changed = true;
}
if (changed) {
menus[focusedIndex].querySelector('button').focus();
return menus[focusedIndex];
}
};
MenuBarController.prototype.openFocusedMenu = function() {
var menu = this.getFocusedMenu();
menu && angular.element(menu).controller('mdMenu').open();
};
MenuBarController.prototype.getMenus = function() {
var $element = this.$element;
return this.$mdUtil.nodesToArray($element[0].children)
.filter(function(el) { return el.nodeName == 'MD-MENU'; });
};
MenuBarController.prototype.getFocusedMenu = function() {
return this.getMenus()[this.getFocusedMenuIndex()];
};
MenuBarController.prototype.getFocusedMenuIndex = function() {
var $mdUtil = this.$mdUtil;
var focusedEl = $mdUtil.getClosest(
this.$document[0].activeElement,
'MD-MENU'
);
if (!focusedEl) return -1;
var focusedIndex = this.getMenus().indexOf(focusedEl);
return focusedIndex;
};
MenuBarController.prototype.getOpenMenuIndex = function() {
var menus = this.getMenus();
for (var i = 0; i < menus.length; ++i) {
if (menus[i].classList.contains('md-open')) return i;
}
return -1;
};
MenuBarController.prototype.handleParentClick = function(event) {
var openMenu = this.querySelector('md-menu.md-open');
if (openMenu && !openMenu.contains(event.target)) {
angular.element(openMenu).controller('mdMenu').close(true, {
closeAll: true
});
}
};
/**
* @ngdoc directive
* @name mdMenuBar
* @module material.components.menuBar
* @restrict E
* @description
*
* Menu bars are containers that hold multiple menus. They change the behavior and appearence
* of the `md-menu` directive to behave similar to an operating system provided menu.
*
* @usage
* <hljs lang="html">
* <md-menu-bar>
* <md-menu>
* <button ng-click="$mdMenu.open()">
* File
* </button>
* <md-menu-content>
* <md-menu-item>
* <md-button ng-click="ctrl.sampleAction('share', $event)">
* Share...
* </md-button>
* </md-menu-item>
* <md-menu-divider></md-menu-divider>
* <md-menu-item>
* <md-menu-item>
* <md-menu>
* <md-button ng-click="$mdMenu.open()">New</md-button>
* <md-menu-content>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-bar>
* </hljs>
*
* ## Menu Bar Controls
*
* You may place `md-menu-items` that function as controls within menu bars.
* There are two modes that are exposed via the `type` attribute of the `md-menu-item`.
* `type="checkbox"` will function as a boolean control for the `ng-model` attribute of the
* `md-menu-item`. `type="radio"` will function like a radio button, setting the `ngModel`
* to the `string` value of the `value` attribute. If you need non-string values, you can use
* `ng-value` to provide an expression (this is similar to how angular's native `input[type=radio]` works.
*
* <hljs lang="html">
* <md-menu-bar>
* <md-menu>
* <button ng-click="$mdMenu.open()">
* Sample Menu
* </button>
* <md-menu-content>
* <md-menu-item type="checkbox" ng-model="settings.allowChanges">Allow changes</md-menu-item>
* <md-menu-divider></md-menu-divider>
* <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 1</md-menu-item>
* <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 2</md-menu-item>
* <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 3</md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-bar>
* </hljs>
*
*
* ### Nesting Menus
*
* Menus may be nested within menu bars. This is commonly called cascading menus.
* To nest a menu place the nested menu inside the content of the `md-menu-item`.
* <hljs lang="html">
* <md-menu-item>
* <md-menu>
* <button ng-click="$mdMenu.open()">New</md-button>
* <md-menu-content>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-item>
* </hljs>
*
*/
MenuBarDirective['$inject'] = ["$mdUtil", "$mdTheming"];
angular
.module('material.components.menuBar')
.directive('mdMenuBar', MenuBarDirective);
/* ngInject */
function MenuBarDirective($mdUtil, $mdTheming) {
return {
restrict: 'E',
require: 'mdMenuBar',
controller: 'MenuBarController',
compile: function compile(templateEl, templateAttrs) {
if (!templateAttrs.ariaRole) {
templateEl[0].setAttribute('role', 'menubar');
}
angular.forEach(templateEl[0].children, function(menuEl) {
if (menuEl.nodeName == 'MD-MENU') {
if (!menuEl.hasAttribute('md-position-mode')) {
menuEl.setAttribute('md-position-mode', 'left bottom');
// Since we're in the compile function and actual `md-buttons` are not compiled yet,
// we need to query for possible `md-buttons` as well.
menuEl.querySelector('button, a, md-button').setAttribute('role', 'menuitem');
}
var contentEls = $mdUtil.nodesToArray(menuEl.querySelectorAll('md-menu-content'));
angular.forEach(contentEls, function(contentEl) {
contentEl.classList.add('md-menu-bar-menu');
contentEl.classList.add('md-dense');
if (!contentEl.hasAttribute('width')) {
contentEl.setAttribute('width', 5);
}
});
}
});
// Mark the child menu items that they're inside a menu bar. This is necessary,
// because mnMenuItem has special behaviour during compilation, depending on
// whether it is inside a mdMenuBar. We can usually figure this out via the DOM,
// however if a directive that uses documentFragment is applied to the child (e.g. ngRepeat),
// the element won't have a parent and won't compile properly.
templateEl.find('md-menu-item').addClass('md-in-menu-bar');
return function postLink(scope, el, attr, ctrl) {
el.addClass('_md'); // private md component indicator for styling
$mdTheming(scope, el);
ctrl.init();
};
}
};
}
angular
.module('material.components.menuBar')
.directive('mdMenuDivider', MenuDividerDirective);
function MenuDividerDirective() {
return {
restrict: 'E',
compile: function(templateEl, templateAttrs) {
if (!templateAttrs.role) {
templateEl[0].setAttribute('role', 'separator');
}
}
};
}
MenuItemController['$inject'] = ["$scope", "$element", "$attrs"];
angular
.module('material.components.menuBar')
.controller('MenuItemController', MenuItemController);
/**
* ngInject
*/
function MenuItemController($scope, $element, $attrs) {
this.$element = $element;
this.$attrs = $attrs;
this.$scope = $scope;
}
MenuItemController.prototype.init = function(ngModel) {
var $element = this.$element;
var $attrs = this.$attrs;
this.ngModel = ngModel;
if ($attrs.type == 'checkbox' || $attrs.type == 'radio') {
this.mode = $attrs.type;
this.iconEl = $element[0].children[0];
this.buttonEl = $element[0].children[1];
if (ngModel) {
// Clear ngAria set attributes
this.initClickListeners();
}
}
};
// ngAria auto sets attributes on a menu-item with a ngModel.
// We don't want this because our content (buttons) get the focus
// and set their own aria attributes appropritately. Having both
// breaks NVDA / JAWS. This undeoes ngAria's attrs.
MenuItemController.prototype.clearNgAria = function() {
var el = this.$element[0];
var clearAttrs = ['role', 'tabindex', 'aria-invalid', 'aria-checked'];
angular.forEach(clearAttrs, function(attr) {
el.removeAttribute(attr);
});
};
MenuItemController.prototype.initClickListeners = function() {
var self = this;
var ngModel = this.ngModel;
var $scope = this.$scope;
var $attrs = this.$attrs;
var $element = this.$element;
var mode = this.mode;
this.handleClick = angular.bind(this, this.handleClick);
var icon = this.iconEl;
var button = angular.element(this.buttonEl);
var handleClick = this.handleClick;
$attrs.$observe('disabled', setDisabled);
setDisabled($attrs.disabled);
ngModel.$render = function render() {
self.clearNgAria();
if (isSelected()) {
icon.style.display = '';
button.attr('aria-checked', 'true');
} else {
icon.style.display = 'none';
button.attr('aria-checked', 'false');
}
};
$scope.$$postDigest(ngModel.$render);
function isSelected() {
if (mode == 'radio') {
var val = $attrs.ngValue ? $scope.$eval($attrs.ngValue) : $attrs.value;
return ngModel.$modelValue == val;
} else {
return ngModel.$modelValue;
}
}
function setDisabled(disabled) {
if (disabled) {
button.off('click', handleClick);
} else {
button.on('click', handleClick);
}
}
};
MenuItemController.prototype.handleClick = function(e) {
var mode = this.mode;
var ngModel = this.ngModel;
var $attrs = this.$attrs;
var newVal;
if (mode == 'checkbox') {
newVal = !ngModel.$modelValue;
} else if (mode == 'radio') {
newVal = $attrs.ngValue ? this.$scope.$eval($attrs.ngValue) : $attrs.value;
}
ngModel.$setViewValue(newVal);
ngModel.$render();
};
MenuItemDirective['$inject'] = ["$mdUtil", "$mdConstant", "$$mdSvgRegistry"];
angular
.module('material.components.menuBar')
.directive('mdMenuItem', MenuItemDirective);
/* ngInject */
function MenuItemDirective($mdUtil, $mdConstant, $$mdSvgRegistry) {
return {
controller: 'MenuItemController',
require: ['mdMenuItem', '?ngModel'],
priority: $mdConstant.BEFORE_NG_ARIA,
compile: function(templateEl, templateAttrs) {
var type = templateAttrs.type;
var inMenuBarClass = 'md-in-menu-bar';
// Note: This allows us to show the `check` icon for the md-menu-bar items.
// The `md-in-menu-bar` class is set by the mdMenuBar directive.
if ((type == 'checkbox' || type == 'radio') && templateEl.hasClass(inMenuBarClass)) {
var text = templateEl[0].textContent;
var buttonEl = angular.element('<md-button type="button"></md-button>');
var iconTemplate = '<md-icon md-svg-src="' + $$mdSvgRegistry.mdChecked + '"></md-icon>';
buttonEl.html(text);
buttonEl.attr('tabindex', '0');
templateEl.html('');
templateEl.append(angular.element(iconTemplate));
templateEl.append(buttonEl);
templateEl.addClass('md-indent').removeClass(inMenuBarClass);
setDefault('role', type == 'checkbox' ? 'menuitemcheckbox' : 'menuitemradio', buttonEl);
moveAttrToButton('ng-disabled');
} else {
setDefault('role', 'menuitem', templateEl[0].querySelector('md-button, button, a'));
}
return function(scope, el, attrs, ctrls) {
var ctrl = ctrls[0];
var ngModel = ctrls[1];
ctrl.init(ngModel);
};
function setDefault(attr, val, el) {
el = el || templateEl;
if (el instanceof angular.element) {
el = el[0];
}
if (!el.hasAttribute(attr)) {
el.setAttribute(attr, val);
}
}
function moveAttrToButton(attribute) {
var attributes = $mdUtil.prefixer(attribute);
angular.forEach(attributes, function(attr) {
if (templateEl[0].hasAttribute(attr)) {
var val = templateEl[0].getAttribute(attr);
buttonEl[0].setAttribute(attr, val);
templateEl[0].removeAttribute(attr);
}
});
}
}
};
}
})(window, window.angular); |
'use strict';
module.exports = {
db: 'mongodb://localhost/matsi-test',
port: 3001,
app: {
title: 'matsi - Test Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
}; |
export default { path: 'test'
, getComponent(nextState, cb) {
require.ensure([], require => cb(null, require('./components/Test').default))
}
, getChildRoutes(location, cb) {
require.ensure([], require => cb(null, [ require('./routes/Grids').default
, require('./routes/Forms').default
]))
}
}
|
import React from 'react';
//
import {Basic} from 'czechidm-core';
import {SystemGroupManager} from '../../redux';
import SystemGroupTable from './SystemGroupTable';
/**
* Table of system groups.
*
* @author Vít Švanda
* @since 11.2.0
*
*/
export default class SystemGroups extends Basic.AbstractContent {
constructor(props, context) {
super(props, context);
this.manager = new SystemGroupManager();
}
getContentKey() {
return 'acc:content.systemGroup';
}
getNavigationKey() {
return 'system-groups';
}
render() {
return (
<div>
{this.renderPageHeader()}
<Basic.Panel>
<SystemGroupTable uiKey="system-groups-table" manager={this.manager}/>
</Basic.Panel>
</div>
);
}
}
SystemGroups.propTypes = {
};
SystemGroups.defaultProps = {
};
|
import { Model, prefix, attr, hasMany, belongsTo } from 'sofa';
export default Model.extend({
id: prefix(),
name: attr('string'),
email: attr('string'),
blogs: hasMany('blog', { inverse: 'authors', query: 'author-blogs', relationship: 'author-blogs' }),
posts: hasMany('post', { inverse: 'author', persist: false }),
post: belongsTo('post', { query: 'author-first-post' }),
willCreate() {
let name = this.get('name');
if(!name) {
name = 'unnamed';
}
let id = name.trim().toLowerCase();
this.set('id', id);
}
});
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const emptyFunction = require('fbjs/lib/emptyFunction');
describe('ReactDOMInput', () => {
let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
let setUntrackedValue;
function dispatchEventOnNode(node, type) {
node.dispatchEvent(new Event(type, {bubbles: true, cancelable: true}));
}
beforeEach(() => {
jest.resetModules();
setUntrackedValue = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
'value',
).set;
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
});
it('should properly control a value even if no event listener exists', () => {
const container = document.createElement('div');
let stub;
expect(() => {
stub = ReactDOM.render(<input type="text" value="lion" />, container);
}).toWarnDev(
'Failed prop type: You provided a `value` prop to a form field without an `onChange` handler.',
);
document.body.appendChild(container);
const node = ReactDOM.findDOMNode(stub);
setUntrackedValue.call(node, 'giraffe');
// This must use the native event dispatching. If we simulate, we will
// bypass the lazy event attachment system so we won't actually test this.
dispatchEventOnNode(node, 'change');
expect(node.value).toBe('lion');
document.body.removeChild(container);
});
it('should control a value in reentrant events', () => {
class ControlledInputs extends React.Component {
state = {value: 'lion'};
a = null;
b = null;
switchedFocus = false;
change(newValue) {
this.setState({value: newValue});
// Calling focus here will blur the text box which causes a native
// change event. Ideally we shouldn't have to fire this ourselves.
// Don't remove unless you've verified the fix in #8240 is still covered.
dispatchEventOnNode(this.a, 'change');
this.b.focus();
}
blur(currentValue) {
this.switchedFocus = true;
// currentValue should be 'giraffe' here because we should not have
// restored it on the target yet.
this.setState({value: currentValue});
}
render() {
return (
<div>
<input
type="text"
ref={n => (this.a = n)}
value={this.state.value}
onChange={e => this.change(e.target.value)}
onBlur={e => this.blur(e.target.value)}
/>
<input type="text" ref={n => (this.b = n)} />
</div>
);
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<ControlledInputs />, container);
// We need it to be in the body to test native event dispatching.
document.body.appendChild(container);
// Focus the field so we can later blur it.
// Don't remove unless you've verified the fix in #8240 is still covered.
instance.a.focus();
setUntrackedValue.call(instance.a, 'giraffe');
// This must use the native event dispatching. If we simulate, we will
// bypass the lazy event attachment system so we won't actually test this.
dispatchEventOnNode(instance.a, 'change');
dispatchEventOnNode(instance.a, 'blur');
expect(instance.a.value).toBe('giraffe');
expect(instance.switchedFocus).toBe(true);
document.body.removeChild(container);
});
it('should control values in reentrant events with different targets', () => {
class ControlledInputs extends React.Component {
state = {value: 'lion'};
a = null;
b = null;
change(newValue) {
// This click will change the checkbox's value to false. Then it will
// invoke an inner change event. When we finally, flush, we need to
// reset the checkbox's value to true since that is its controlled
// value.
this.b.click();
}
render() {
return (
<div>
<input
type="text"
ref={n => (this.a = n)}
value="lion"
onChange={e => this.change(e.target.value)}
/>
<input
type="checkbox"
ref={n => (this.b = n)}
checked={true}
onChange={() => {}}
/>
</div>
);
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<ControlledInputs />, container);
// We need it to be in the body to test native event dispatching.
document.body.appendChild(container);
setUntrackedValue.call(instance.a, 'giraffe');
// This must use the native event dispatching. If we simulate, we will
// bypass the lazy event attachment system so we won't actually test this.
dispatchEventOnNode(instance.a, 'input');
expect(instance.a.value).toBe('lion');
expect(instance.b.checked).toBe(true);
document.body.removeChild(container);
});
describe('switching text inputs between numeric and string numbers', () => {
it('does change the number 2 to "2.0" with no change handler', () => {
let stub = <input type="text" value={2} onChange={jest.fn()} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
node.value = '2.0';
ReactTestUtils.Simulate.change(stub);
expect(node.getAttribute('value')).toBe('2');
expect(node.value).toBe('2');
});
it('does change the string "2" to "2.0" with no change handler', () => {
let stub = <input type="text" value={'2'} onChange={jest.fn()} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
node.value = '2.0';
ReactTestUtils.Simulate.change(stub);
expect(node.getAttribute('value')).toBe('2');
expect(node.value).toBe('2');
});
it('changes the number 2 to "2.0" using a change handler', () => {
class Stub extends React.Component {
state = {
value: 2,
};
onChange = event => {
this.setState({value: event.target.value});
};
render() {
const {value} = this.state;
return <input type="text" value={value} onChange={this.onChange} />;
}
}
const stub = ReactTestUtils.renderIntoDocument(<Stub />);
const node = ReactDOM.findDOMNode(stub);
node.value = '2.0';
ReactTestUtils.Simulate.change(node);
expect(node.getAttribute('value')).toBe('2.0');
expect(node.value).toBe('2.0');
});
});
it('does change the string ".98" to "0.98" with no change handler', () => {
class Stub extends React.Component {
state = {
value: '.98',
};
render() {
return <input type="number" value={this.state.value} />;
}
}
let stub;
expect(() => {
stub = ReactTestUtils.renderIntoDocument(<Stub />);
}).toWarnDev(
'You provided a `value` prop to a form field ' +
'without an `onChange` handler.',
);
const node = ReactDOM.findDOMNode(stub);
stub.setState({value: '0.98'});
expect(node.value).toEqual('0.98');
});
it('performs a state change from "" to 0', () => {
class Stub extends React.Component {
state = {
value: '',
};
render() {
return <input type="number" value={this.state.value} readOnly={true} />;
}
}
const stub = ReactTestUtils.renderIntoDocument(<Stub />);
const node = ReactDOM.findDOMNode(stub);
stub.setState({value: 0});
expect(node.value).toEqual('0');
});
it('updates the value on radio buttons from "" to 0', function() {
const container = document.createElement('div');
ReactDOM.render(
<input type="radio" value="" onChange={function() {}} />,
container,
);
ReactDOM.render(
<input type="radio" value={0} onChange={function() {}} />,
container,
);
expect(container.firstChild.value).toBe('0');
expect(container.firstChild.getAttribute('value')).toBe('0');
});
it('updates the value on checkboxes from "" to 0', function() {
const container = document.createElement('div');
ReactDOM.render(
<input type="checkbox" value="" onChange={function() {}} />,
container,
);
ReactDOM.render(
<input type="checkbox" value={0} onChange={function() {}} />,
container,
);
expect(container.firstChild.value).toBe('0');
expect(container.firstChild.getAttribute('value')).toBe('0');
});
it('distinguishes precision for extra zeroes in string number values', () => {
class Stub extends React.Component {
state = {
value: '3.0000',
};
render() {
return <input type="number" value={this.state.value} />;
}
}
let stub;
expect(() => {
stub = ReactTestUtils.renderIntoDocument(<Stub />);
}).toWarnDev(
'You provided a `value` prop to a form field ' +
'without an `onChange` handler.',
);
const node = ReactDOM.findDOMNode(stub);
stub.setState({value: '3'});
expect(node.value).toEqual('3');
});
it('should display `defaultValue` of number 0', () => {
let stub = <input type="text" defaultValue={0} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
expect(node.getAttribute('value')).toBe('0');
expect(node.value).toBe('0');
});
it('only assigns defaultValue if it changes', () => {
class Test extends React.Component {
render() {
return <input defaultValue="0" />;
}
}
const component = ReactTestUtils.renderIntoDocument(<Test />);
const node = ReactDOM.findDOMNode(component);
Object.defineProperty(node, 'defaultValue', {
get() {
return '0';
},
set(value) {
throw new Error(
`defaultValue was assigned ${value}, but it did not change!`,
);
},
});
component.forceUpdate();
});
it('should display "true" for `defaultValue` of `true`', () => {
let stub = <input type="text" defaultValue={true} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
expect(node.value).toBe('true');
});
it('should display "false" for `defaultValue` of `false`', () => {
let stub = <input type="text" defaultValue={false} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
expect(node.value).toBe('false');
});
it('should update `defaultValue` for uncontrolled input', () => {
const container = document.createElement('div');
const node = ReactDOM.render(
<input type="text" defaultValue="0" />,
container,
);
expect(node.value).toBe('0');
ReactDOM.render(<input type="text" defaultValue="1" />, container);
expect(node.value).toBe('0');
expect(node.defaultValue).toBe('1');
});
it('should update `defaultValue` for uncontrolled date/time input', () => {
const container = document.createElement('div');
const node = ReactDOM.render(
<input type="date" defaultValue="1980-01-01" />,
container,
);
expect(node.value).toBe('1980-01-01');
ReactDOM.render(<input type="date" defaultValue="2000-01-01" />, container);
expect(node.value).toBe('1980-01-01');
expect(node.defaultValue).toBe('2000-01-01');
ReactDOM.render(<input type="date" />, container);
});
it('should take `defaultValue` when changing to uncontrolled input', () => {
const container = document.createElement('div');
const node = ReactDOM.render(
<input type="text" value="0" readOnly="true" />,
container,
);
expect(node.value).toBe('0');
expect(() =>
ReactDOM.render(<input type="text" defaultValue="1" />, container),
).toWarnDev(
'A component is changing a controlled input of type ' +
'text to be uncontrolled.',
);
expect(node.value).toBe('0');
});
it('should render defaultValue for SSR', () => {
const markup = ReactDOMServer.renderToString(
<input type="text" defaultValue="1" />,
);
const div = document.createElement('div');
div.innerHTML = markup;
expect(div.firstChild.getAttribute('value')).toBe('1');
expect(div.firstChild.getAttribute('defaultValue')).toBe(null);
});
it('should render value for SSR', () => {
const element = <input type="text" value="1" onChange={() => {}} />;
const markup = ReactDOMServer.renderToString(element);
const div = document.createElement('div');
div.innerHTML = markup;
expect(div.firstChild.getAttribute('value')).toBe('1');
expect(div.firstChild.getAttribute('defaultValue')).toBe(null);
});
it('should render name attribute if it is supplied', () => {
const container = document.createElement('div');
const node = ReactDOM.render(<input type="text" name="name" />, container);
expect(node.name).toBe('name');
expect(container.firstChild.getAttribute('name')).toBe('name');
});
it('should render name attribute if it is supplied for SSR', () => {
const element = <input type="text" name="name" />;
const markup = ReactDOMServer.renderToString(element);
const div = document.createElement('div');
div.innerHTML = markup;
expect(div.firstChild.getAttribute('name')).toBe('name');
});
it('should not render name attribute if it is not supplied', () => {
const container = document.createElement('div');
ReactDOM.render(<input type="text" />, container);
expect(container.firstChild.getAttribute('name')).toBe(null);
});
it('should not render name attribute if it is not supplied for SSR', () => {
const element = <input type="text" />;
const markup = ReactDOMServer.renderToString(element);
const div = document.createElement('div');
div.innerHTML = markup;
expect(div.firstChild.getAttribute('name')).toBe(null);
});
it('should display "foobar" for `defaultValue` of `objToString`', () => {
const objToString = {
toString: function() {
return 'foobar';
},
};
let stub = <input type="text" defaultValue={objToString} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
expect(node.value).toBe('foobar');
});
it('should display `value` of number 0', () => {
let stub = <input type="text" value={0} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
expect(node.value).toBe('0');
});
it('should allow setting `value` to `true`', () => {
const container = document.createElement('div');
let stub = <input type="text" value="yolo" onChange={emptyFunction} />;
const node = ReactDOM.render(stub, container);
expect(node.value).toBe('yolo');
stub = ReactDOM.render(
<input type="text" value={true} onChange={emptyFunction} />,
container,
);
expect(node.value).toEqual('true');
});
it('should allow setting `value` to `false`', () => {
const container = document.createElement('div');
let stub = <input type="text" value="yolo" onChange={emptyFunction} />;
const node = ReactDOM.render(stub, container);
expect(node.value).toBe('yolo');
stub = ReactDOM.render(
<input type="text" value={false} onChange={emptyFunction} />,
container,
);
expect(node.value).toEqual('false');
});
it('should allow setting `value` to `objToString`', () => {
const container = document.createElement('div');
let stub = <input type="text" value="foo" onChange={emptyFunction} />;
const node = ReactDOM.render(stub, container);
expect(node.value).toBe('foo');
const objToString = {
toString: function() {
return 'foobar';
},
};
stub = ReactDOM.render(
<input type="text" value={objToString} onChange={emptyFunction} />,
container,
);
expect(node.value).toEqual('foobar');
});
it('should not incur unnecessary DOM mutations', () => {
const container = document.createElement('div');
ReactDOM.render(<input value="a" onChange={() => {}} />, container);
const node = container.firstChild;
let nodeValue = 'a';
const nodeValueSetter = jest.fn();
Object.defineProperty(node, 'value', {
get: function() {
return nodeValue;
},
set: nodeValueSetter.mockImplementation(function(newValue) {
nodeValue = newValue;
}),
});
ReactDOM.render(<input value="a" onChange={() => {}} />, container);
expect(nodeValueSetter).toHaveBeenCalledTimes(0);
ReactDOM.render(<input value="b" onChange={() => {}} />, container);
expect(nodeValueSetter).toHaveBeenCalledTimes(1);
});
it('should not incur unnecessary DOM mutations for numeric type conversion', () => {
const container = document.createElement('div');
ReactDOM.render(<input value="0" onChange={() => {}} />, container);
const node = container.firstChild;
let nodeValue = '0';
const nodeValueSetter = jest.fn();
Object.defineProperty(node, 'value', {
get: function() {
return nodeValue;
},
set: nodeValueSetter.mockImplementation(function(newValue) {
nodeValue = newValue;
}),
});
ReactDOM.render(<input value={0} onChange={() => {}} />, container);
expect(nodeValueSetter).toHaveBeenCalledTimes(0);
});
it('should not incur unnecessary DOM mutations for the boolean type conversion', () => {
const container = document.createElement('div');
ReactDOM.render(<input value="true" onChange={() => {}} />, container);
const node = container.firstChild;
let nodeValue = 'true';
const nodeValueSetter = jest.fn();
Object.defineProperty(node, 'value', {
get: function() {
return nodeValue;
},
set: nodeValueSetter.mockImplementation(function(newValue) {
nodeValue = newValue;
}),
});
ReactDOM.render(<input value={true} onChange={() => {}} />, container);
expect(nodeValueSetter).toHaveBeenCalledTimes(0);
});
it('should properly control a value of number `0`', () => {
let stub = <input type="text" value={0} onChange={emptyFunction} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
node.value = 'giraffe';
ReactTestUtils.Simulate.change(node);
expect(node.value).toBe('0');
});
it('should properly control 0.0 for a text input', () => {
let stub = <input type="text" value={0} onChange={emptyFunction} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
node.value = '0.0';
ReactTestUtils.Simulate.change(node, {target: {value: '0.0'}});
expect(node.value).toBe('0');
});
it('should properly control 0.0 for a number input', () => {
let stub = <input type="number" value={0} onChange={emptyFunction} />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
node.value = '0.0';
ReactTestUtils.Simulate.change(node, {target: {value: '0.0'}});
expect(node.value).toBe('0.0');
});
it('should properly transition from an empty value to 0', function() {
const container = document.createElement('div');
ReactDOM.render(<input type="text" value="" />, container);
ReactDOM.render(<input type="text" value={0} />, container);
const node = container.firstChild;
expect(node.value).toBe('0');
expect(node.defaultValue).toBe('0');
});
it('should properly transition from 0 to an empty value', function() {
const container = document.createElement('div');
ReactDOM.render(<input type="text" value={0} />, container);
ReactDOM.render(<input type="text" value="" />, container);
const node = container.firstChild;
expect(node.value).toBe('');
expect(node.defaultValue).toBe('');
});
it('should properly transition a text input from 0 to an empty 0.0', function() {
const container = document.createElement('div');
ReactDOM.render(<input type="text" value={0} />, container);
ReactDOM.render(<input type="text" value="0.0" />, container);
const node = container.firstChild;
expect(node.value).toBe('0.0');
expect(node.defaultValue).toBe('0.0');
});
it('should properly transition a number input from "" to 0', function() {
const container = document.createElement('div');
ReactDOM.render(<input type="number" value="" />, container);
ReactDOM.render(<input type="number" value={0} />, container);
const node = container.firstChild;
expect(node.value).toBe('0');
expect(node.defaultValue).toBe('0');
});
it('should properly transition a number input from "" to "0"', function() {
const container = document.createElement('div');
ReactDOM.render(<input type="number" value="" />, container);
ReactDOM.render(<input type="number" value="0" />, container);
const node = container.firstChild;
expect(node.value).toBe('0');
expect(node.defaultValue).toBe('0');
});
it('should have the correct target value', () => {
let handled = false;
const handler = function(event) {
expect(event.target.nodeName).toBe('INPUT');
handled = true;
};
const stub = <input type="text" value={0} onChange={handler} />;
const container = document.createElement('div');
const node = ReactDOM.render(stub, container);
setUntrackedValue.call(node, 'giraffe');
ReactTestUtils.SimulateNative.input(node, {
path: [node, container],
});
expect(handled).toBe(true);
});
it('should not set a value for submit buttons unnecessarily', () => {
let stub = <input type="submit" />;
stub = ReactTestUtils.renderIntoDocument(stub);
const node = ReactDOM.findDOMNode(stub);
// The value shouldn't be '', or else the button will have no text; it
// should have the default "Submit" or "Submit Query" label. Most browsers
// report this as not having a `value` attribute at all; IE reports it as
// the actual label that the user sees.
expect(
!node.hasAttribute('value') || node.getAttribute('value').length > 0,
).toBe(true);
});
it('should control radio buttons', () => {
class RadioGroup extends React.Component {
render() {
return (
<div>
<input
ref="a"
type="radio"
name="fruit"
checked={true}
onChange={emptyFunction}
/>
A
<input ref="b" type="radio" name="fruit" onChange={emptyFunction} />
B
<form>
<input
ref="c"
type="radio"
name="fruit"
defaultChecked={true}
onChange={emptyFunction}
/>
</form>
</div>
);
}
}
const stub = ReactTestUtils.renderIntoDocument(<RadioGroup />);
const aNode = stub.refs.a;
const bNode = stub.refs.b;
const cNode = stub.refs.c;
expect(aNode.checked).toBe(true);
expect(bNode.checked).toBe(false);
// c is in a separate form and shouldn't be affected at all here
expect(cNode.checked).toBe(true);
bNode.checked = true;
// This next line isn't necessary in a proper browser environment, but
// jsdom doesn't uncheck the others in a group (which makes this whole test
// a little less effective)
aNode.checked = false;
expect(cNode.checked).toBe(true);
// Now let's run the actual ReactDOMInput change event handler
ReactTestUtils.Simulate.change(bNode);
// The original state should have been restored
expect(aNode.checked).toBe(true);
expect(cNode.checked).toBe(true);
});
it('should check the correct radio when the selected name moves', () => {
class App extends React.Component {
state = {
updated: false,
};
onClick = () => {
this.setState({updated: true});
};
render() {
const {updated} = this.state;
const radioName = updated ? 'secondName' : 'firstName';
return (
<div>
<button type="button" onClick={this.onClick} />
<input
type="radio"
name={radioName}
onChange={emptyFunction}
checked={updated === true}
/>
<input
type="radio"
name={radioName}
onChange={emptyFunction}
checked={updated === false}
/>
</div>
);
}
}
const stub = ReactTestUtils.renderIntoDocument(<App />);
const buttonNode = ReactDOM.findDOMNode(stub).childNodes[0];
const firstRadioNode = ReactDOM.findDOMNode(stub).childNodes[1];
expect(firstRadioNode.checked).toBe(false);
ReactTestUtils.Simulate.click(buttonNode);
expect(firstRadioNode.checked).toBe(true);
});
it('should control radio buttons if the tree updates during render', () => {
const sharedParent = document.createElement('div');
const container1 = document.createElement('div');
const container2 = document.createElement('div');
sharedParent.appendChild(container1);
let aNode;
let bNode;
class ComponentA extends React.Component {
componentDidMount() {
ReactDOM.render(<ComponentB />, container2);
}
render() {
return (
<div>
<input
ref={n => (aNode = n)}
type="radio"
name="fruit"
checked={true}
onChange={emptyFunction}
/>
A
</div>
);
}
}
class ComponentB extends React.Component {
state = {changed: false};
handleChange = () => {
this.setState({
changed: true,
});
};
componentDidUpdate() {
sharedParent.appendChild(container2);
}
render() {
return (
<div>
<input
ref={n => (bNode = n)}
type="radio"
name="fruit"
checked={false}
onChange={this.handleChange}
/>
B
</div>
);
}
}
ReactDOM.render(<ComponentA />, container1);
expect(aNode.checked).toBe(true);
expect(bNode.checked).toBe(false);
bNode.checked = true;
// This next line isn't necessary in a proper browser environment, but
// jsdom doesn't uncheck the others in a group (which makes this whole test
// a little less effective)
aNode.checked = false;
// Now let's run the actual ReactDOMInput change event handler
ReactTestUtils.Simulate.change(bNode);
// The original state should have been restored
expect(aNode.checked).toBe(true);
expect(bNode.checked).toBe(false);
});
it('should warn with value and no onChange handler and readOnly specified', () => {
ReactTestUtils.renderIntoDocument(
<input type="text" value="zoink" readOnly={true} />,
);
expect(() =>
ReactTestUtils.renderIntoDocument(
<input type="text" value="zoink" readOnly={false} />,
),
).toWarnDev(
'Warning: Failed prop type: You provided a `value` prop to a form ' +
'field without an `onChange` handler. This will render a read-only ' +
'field. If the field should be mutable use `defaultValue`. ' +
'Otherwise, set either `onChange` or `readOnly`.\n' +
' in input (at **)',
);
});
it('should have a this value of undefined if bind is not used', () => {
const unboundInputOnChange = function() {
expect(this).toBe(undefined);
};
let instance = <input type="text" onChange={unboundInputOnChange} />;
instance = ReactTestUtils.renderIntoDocument(instance);
ReactTestUtils.Simulate.change(instance);
});
it('should warn with checked and no onChange handler with readOnly specified', () => {
ReactTestUtils.renderIntoDocument(
<input type="checkbox" checked="false" readOnly={true} />,
);
expect(() =>
ReactTestUtils.renderIntoDocument(
<input type="checkbox" checked="false" readOnly={false} />,
),
).toWarnDev(
'Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler. ' +
'This will render a read-only field. If the field should be mutable use `defaultChecked`. ' +
'Otherwise, set either `onChange` or `readOnly`.',
);
});
it('should update defaultValue to empty string', () => {
const container = document.createElement('div');
ReactDOM.render(<input type="text" defaultValue={'foo'} />, container);
ReactDOM.render(<input type="text" defaultValue={''} />, container);
expect(container.firstChild.defaultValue).toBe('');
});
it('should warn if value is null', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(<input type="text" value={null} />),
).toWarnDev(
'`value` prop on `input` should not be null. ' +
'Consider using an empty string to clear the component or `undefined` ' +
'for uncontrolled components.',
);
ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
});
it('should warn if checked and defaultChecked props are specified', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<input
type="radio"
checked={true}
defaultChecked={true}
readOnly={true}
/>,
),
).toWarnDev(
'A component contains an input of type radio with both checked and defaultChecked props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the checked prop, or the defaultChecked prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
ReactTestUtils.renderIntoDocument(
<input
type="radio"
checked={true}
defaultChecked={true}
readOnly={true}
/>,
);
});
it('should warn if value and defaultValue props are specified', () => {
expect(() =>
ReactTestUtils.renderIntoDocument(
<input type="text" value="foo" defaultValue="bar" readOnly={true} />,
),
).toWarnDev(
'A component contains an input of type text with both value and defaultValue props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
ReactTestUtils.renderIntoDocument(
<input type="text" value="foo" defaultValue="bar" readOnly={true} />,
);
});
it('should warn if controlled input switches to uncontrolled (value is undefined)', () => {
const stub = (
<input type="text" value="controlled" onChange={emptyFunction} />
);
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() => ReactDOM.render(<input type="text" />, container)).toWarnDev(
'Warning: A component is changing a controlled input of type text to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if controlled input switches to uncontrolled (value is null)', () => {
const stub = (
<input type="text" value="controlled" onChange={emptyFunction} />
);
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="text" value={null} />, container),
).toWarnDev([
'`value` prop on `input` should not be null. ' +
'Consider using an empty string to clear the component or `undefined` for uncontrolled components',
'Warning: A component is changing a controlled input of type text to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
]);
});
it('should warn if controlled input switches to uncontrolled with defaultValue', () => {
const stub = (
<input type="text" value="controlled" onChange={emptyFunction} />
);
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(
<input type="text" defaultValue="uncontrolled" />,
container,
),
).toWarnDev(
'Warning: A component is changing a controlled input of type text to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if uncontrolled input (value is undefined) switches to controlled', () => {
const stub = <input type="text" />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="text" value="controlled" />, container),
).toWarnDev(
'Warning: A component is changing an uncontrolled input of type text to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if uncontrolled input (value is null) switches to controlled', () => {
const stub = <input type="text" value={null} />;
const container = document.createElement('div');
expect(() => ReactDOM.render(stub, container)).toWarnDev(
'`value` prop on `input` should not be null. ' +
'Consider using an empty string to clear the component or `undefined` for uncontrolled components.',
);
expect(() =>
ReactDOM.render(<input type="text" value="controlled" />, container),
).toWarnDev(
'Warning: A component is changing an uncontrolled input of type text to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if controlled checkbox switches to uncontrolled (checked is undefined)', () => {
const stub = (
<input type="checkbox" checked={true} onChange={emptyFunction} />
);
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="checkbox" />, container),
).toWarnDev(
'Warning: A component is changing a controlled input of type checkbox to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if controlled checkbox switches to uncontrolled (checked is null)', () => {
const stub = (
<input type="checkbox" checked={true} onChange={emptyFunction} />
);
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="checkbox" checked={null} />, container),
).toWarnDev(
'Warning: A component is changing a controlled input of type checkbox to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if controlled checkbox switches to uncontrolled with defaultChecked', () => {
const stub = (
<input type="checkbox" checked={true} onChange={emptyFunction} />
);
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(
<input type="checkbox" defaultChecked={true} />,
container,
),
).toWarnDev(
'Warning: A component is changing a controlled input of type checkbox to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if uncontrolled checkbox (checked is undefined) switches to controlled', () => {
const stub = <input type="checkbox" />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="checkbox" checked={true} />, container),
).toWarnDev(
'Warning: A component is changing an uncontrolled input of type checkbox to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if uncontrolled checkbox (checked is null) switches to controlled', () => {
const stub = <input type="checkbox" checked={null} />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="checkbox" checked={true} />, container),
).toWarnDev(
'Warning: A component is changing an uncontrolled input of type checkbox to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if controlled radio switches to uncontrolled (checked is undefined)', () => {
const stub = <input type="radio" checked={true} onChange={emptyFunction} />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() => ReactDOM.render(<input type="radio" />, container)).toWarnDev(
'Warning: A component is changing a controlled input of type radio to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if controlled radio switches to uncontrolled (checked is null)', () => {
const stub = <input type="radio" checked={true} onChange={emptyFunction} />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="radio" checked={null} />, container),
).toWarnDev(
'Warning: A component is changing a controlled input of type radio to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if controlled radio switches to uncontrolled with defaultChecked', () => {
const stub = <input type="radio" checked={true} onChange={emptyFunction} />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="radio" defaultChecked={true} />, container),
).toWarnDev(
'Warning: A component is changing a controlled input of type radio to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if uncontrolled radio (checked is undefined) switches to controlled', () => {
const stub = <input type="radio" />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="radio" checked={true} />, container),
).toWarnDev(
'Warning: A component is changing an uncontrolled input of type radio to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should warn if uncontrolled radio (checked is null) switches to controlled', () => {
const stub = <input type="radio" checked={null} />;
const container = document.createElement('div');
ReactDOM.render(stub, container);
expect(() =>
ReactDOM.render(<input type="radio" checked={true} />, container),
).toWarnDev(
'Warning: A component is changing an uncontrolled input of type radio to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('should not warn if radio value changes but never becomes controlled', () => {
const container = document.createElement('div');
ReactDOM.render(<input type="radio" value="value" />, container);
ReactDOM.render(<input type="radio" />, container);
ReactDOM.render(
<input type="radio" value="value" defaultChecked={true} />,
container,
);
ReactDOM.render(
<input type="radio" value="value" onChange={() => null} />,
container,
);
ReactDOM.render(<input type="radio" />, container);
});
it('should not warn if radio value changes but never becomes uncontrolled', () => {
const container = document.createElement('div');
ReactDOM.render(
<input type="radio" checked={false} onChange={() => null} />,
container,
);
ReactDOM.render(
<input
type="radio"
value="value"
defaultChecked={true}
checked={false}
onChange={() => null}
/>,
container,
);
});
it('should warn if radio checked false changes to become uncontrolled', () => {
const container = document.createElement('div');
ReactDOM.render(
<input
type="radio"
value="value"
checked={false}
onChange={() => null}
/>,
container,
);
expect(() =>
ReactDOM.render(<input type="radio" value="value" />, container),
).toWarnDev(
'Warning: A component is changing a controlled input of type radio to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components\n' +
' in input (at **)',
);
});
it('sets type, step, min, max before value always', () => {
const log = [];
const originalCreateElement = document.createElement;
spyOnDevAndProd(document, 'createElement').and.callFake(function(type) {
const el = originalCreateElement.apply(this, arguments);
let value = '';
if (type === 'input') {
Object.defineProperty(el, 'value', {
get: function() {
return value;
},
set: function(val) {
value = '' + val;
log.push('set property value');
},
});
spyOnDevAndProd(el, 'setAttribute').and.callFake(function(name) {
log.push('set attribute ' + name);
});
}
return el;
});
ReactTestUtils.renderIntoDocument(
<input
value="0"
onChange={() => {}}
type="range"
min="0"
max="100"
step="1"
/>,
);
expect(log).toEqual([
'set attribute type',
'set attribute min',
'set attribute max',
'set attribute step',
'set property value',
'set attribute value',
'set attribute checked',
'set attribute checked',
]);
});
it('sets value properly with type coming later in props', () => {
const input = ReactTestUtils.renderIntoDocument(
<input value="hi" type="radio" />,
);
expect(input.value).toBe('hi');
});
it('does not raise a validation warning when it switches types', () => {
class Input extends React.Component {
state = {type: 'number', value: 1000};
render() {
const {value, type} = this.state;
return <input onChange={() => {}} type={type} value={value} />;
}
}
const input = ReactTestUtils.renderIntoDocument(<Input />);
const node = ReactDOM.findDOMNode(input);
// If the value is set before the type, a validation warning will raise and
// the value will not be assigned.
input.setState({type: 'text', value: 'Test'});
expect(node.value).toEqual('Test');
});
it('resets value of date/time input to fix bugs in iOS Safari', () => {
function strify(x) {
return JSON.stringify(x, null, 2);
}
const log = [];
const originalCreateElement = document.createElement;
spyOnDevAndProd(document, 'createElement').and.callFake(function(type) {
const el = originalCreateElement.apply(this, arguments);
let value = '';
if (type === 'input') {
Object.defineProperty(el, 'value', {
get: function() {
return value;
},
set: function(val) {
value = '' + val;
log.push(`node.value = ${strify(val)}`);
},
});
spyOnDevAndProd(el, 'setAttribute').and.callFake(function(name, val) {
log.push(`node.setAttribute(${strify(name)}, ${strify(val)})`);
});
}
return el;
});
ReactTestUtils.renderIntoDocument(
<input type="date" defaultValue="1980-01-01" />,
);
expect(log).toEqual([
'node.setAttribute("type", "date")',
'node.value = "1980-01-01"',
'node.setAttribute("value", "1980-01-01")',
'node.setAttribute("checked", "")',
'node.setAttribute("checked", "")',
]);
});
describe('assigning the value attribute on controlled inputs', function() {
function getTestInput() {
return class extends React.Component {
state = {
value: this.props.value == null ? '' : this.props.value,
};
onChange = event => {
this.setState({value: event.target.value});
};
render() {
const type = this.props.type;
const value = this.state.value;
return <input type={type} value={value} onChange={this.onChange} />;
}
};
}
it('always sets the attribute when values change on text inputs', function() {
const Input = getTestInput();
const stub = ReactTestUtils.renderIntoDocument(<Input type="text" />);
const node = ReactDOM.findDOMNode(stub);
ReactTestUtils.Simulate.change(node, {target: {value: '2'}});
expect(node.getAttribute('value')).toBe('2');
});
it('does not set the value attribute on number inputs if focused', () => {
const Input = getTestInput();
const stub = ReactTestUtils.renderIntoDocument(
<Input type="number" value="1" />,
);
const node = ReactDOM.findDOMNode(stub);
node.focus();
ReactTestUtils.Simulate.change(node, {target: {value: '2'}});
expect(node.getAttribute('value')).toBe('1');
});
it('sets the value attribute on number inputs on blur', () => {
const Input = getTestInput();
const stub = ReactTestUtils.renderIntoDocument(
<Input type="number" value="1" />,
);
const node = ReactDOM.findDOMNode(stub);
ReactTestUtils.Simulate.change(node, {target: {value: '2'}});
ReactTestUtils.SimulateNative.blur(node);
expect(node.getAttribute('value')).toBe('2');
});
it('an uncontrolled number input will not update the value attribute on blur', () => {
const stub = ReactTestUtils.renderIntoDocument(
<input type="number" defaultValue="1" />,
);
const node = ReactDOM.findDOMNode(stub);
node.value = 4;
ReactTestUtils.SimulateNative.blur(node);
expect(node.getAttribute('value')).toBe('1');
});
it('an uncontrolled text input will not update the value attribute on blur', () => {
const stub = ReactTestUtils.renderIntoDocument(
<input type="text" defaultValue="1" />,
);
const node = ReactDOM.findDOMNode(stub);
node.value = 4;
ReactTestUtils.SimulateNative.blur(node);
expect(node.getAttribute('value')).toBe('1');
});
});
describe('setting a controlled input to undefined', () => {
let input;
function renderInputWithStringThenWithUndefined() {
class Input extends React.Component {
state = {value: 'first'};
render() {
return (
<input
onChange={e => this.setState({value: e.target.value})}
value={this.state.value}
/>
);
}
}
const stub = ReactTestUtils.renderIntoDocument(<Input />);
input = ReactDOM.findDOMNode(stub);
ReactTestUtils.Simulate.change(input, {target: {value: 'latest'}});
ReactTestUtils.Simulate.change(input, {target: {value: undefined}});
}
it('reverts the value attribute to the initial value', () => {
expect(renderInputWithStringThenWithUndefined).toWarnDev(
'Input elements should not switch from controlled to ' +
'uncontrolled (or vice versa).',
);
expect(input.getAttribute('value')).toBe('first');
});
it('preserves the value property', () => {
expect(renderInputWithStringThenWithUndefined).toWarnDev(
'Input elements should not switch from controlled to ' +
'uncontrolled (or vice versa).',
);
expect(input.value).toBe('latest');
});
});
describe('setting a controlled input to null', () => {
let input;
function renderInputWithStringThenWithNull() {
class Input extends React.Component {
state = {value: 'first'};
render() {
return (
<input
onChange={e => this.setState({value: e.target.value})}
value={this.state.value}
/>
);
}
}
const stub = ReactTestUtils.renderIntoDocument(<Input />);
input = ReactDOM.findDOMNode(stub);
ReactTestUtils.Simulate.change(input, {target: {value: 'latest'}});
ReactTestUtils.Simulate.change(input, {target: {value: null}});
}
it('reverts the value attribute to the initial value', () => {
expect(renderInputWithStringThenWithNull).toWarnDev([
'`value` prop on `input` should not be null. ' +
'Consider using an empty string to clear the component ' +
'or `undefined` for uncontrolled components.',
'Input elements should not switch from controlled ' +
'to uncontrolled (or vice versa).',
]);
expect(input.getAttribute('value')).toBe('first');
});
it('preserves the value property', () => {
expect(renderInputWithStringThenWithNull).toWarnDev([
'`value` prop on `input` should not be null. ' +
'Consider using an empty string to clear the component ' +
'or `undefined` for uncontrolled components.',
'Input elements should not switch from controlled ' +
'to uncontrolled (or vice versa).',
]);
expect(input.value).toBe('latest');
});
});
describe('When given a Symbol value', function() {
it('treats initial Symbol value as an empty string', function() {
const container = document.createElement('div');
expect(() =>
ReactDOM.render(
<input value={Symbol('foobar')} onChange={() => {}} />,
container,
),
).toWarnDev('Invalid value for prop `value`');
const node = container.firstChild;
expect(node.value).toBe('');
expect(node.getAttribute('value')).toBe('');
});
it('treats updated Symbol value as an empty string', function() {
const container = document.createElement('div');
ReactDOM.render(<input value="foo" onChange={() => {}} />, container);
expect(() =>
ReactDOM.render(
<input value={Symbol('foobar')} onChange={() => {}} />,
container,
),
).toWarnDev('Invalid value for prop `value`');
const node = container.firstChild;
expect(node.value).toBe('');
expect(node.getAttribute('value')).toBe('');
});
it('treats initial Symbol defaultValue as an empty string', function() {
const container = document.createElement('div');
ReactDOM.render(<input defaultValue={Symbol('foobar')} />, container);
const node = container.firstChild;
expect(node.value).toBe('');
expect(node.getAttribute('value')).toBe('');
// TODO: we should warn here.
});
it('treats updated Symbol defaultValue as an empty string', function() {
const container = document.createElement('div');
ReactDOM.render(<input defaultValue="foo" />, container);
ReactDOM.render(<input defaultValue={Symbol('foobar')} />, container);
const node = container.firstChild;
expect(node.value).toBe('foo');
expect(node.getAttribute('value')).toBe('');
// TODO: we should warn here.
});
});
describe('When given a function value', function() {
it('treats initial function value as an empty string', function() {
const container = document.createElement('div');
expect(() =>
ReactDOM.render(
<input value={() => {}} onChange={() => {}} />,
container,
),
).toWarnDev('Invalid value for prop `value`');
const node = container.firstChild;
expect(node.value).toBe('');
expect(node.getAttribute('value')).toBe('');
});
it('treats updated function value as an empty string', function() {
const container = document.createElement('div');
ReactDOM.render(<input value="foo" onChange={() => {}} />, container);
expect(() =>
ReactDOM.render(
<input value={() => {}} onChange={() => {}} />,
container,
),
).toWarnDev('Invalid value for prop `value`');
const node = container.firstChild;
expect(node.value).toBe('');
expect(node.getAttribute('value')).toBe('');
});
it('treats initial function defaultValue as an empty string', function() {
const container = document.createElement('div');
ReactDOM.render(<input defaultValue={() => {}} />, container);
const node = container.firstChild;
expect(node.value).toBe('');
expect(node.getAttribute('value')).toBe('');
// TODO: we should warn here.
});
it('treats updated function defaultValue as an empty string', function() {
const container = document.createElement('div');
ReactDOM.render(<input defaultValue="foo" />, container);
ReactDOM.render(<input defaultValue={() => {}} />, container);
const node = container.firstChild;
expect(node.value).toBe('foo');
expect(node.getAttribute('value')).toBe('');
// TODO: we should warn here.
});
});
describe('checked inputs without a value property', function() {
// In absence of a value, radio and checkboxes report a value of "on".
// Between 16 and 16.2, we assigned a node's value to it's current
// value in order to "dettach" it from defaultValue. This had the unfortunate
// side-effect of assigning value="on" to radio and checkboxes
it('does not add "on" in absence of value on a checkbox', function() {
const container = document.createElement('div');
ReactDOM.render(
<input type="checkbox" defaultChecked={true} />,
container,
);
const node = container.firstChild;
expect(node.value).toBe('on');
expect(node.hasAttribute('value')).toBe(false);
});
it('does not add "on" in absence of value on a radio', function() {
const container = document.createElement('div');
ReactDOM.render(<input type="radio" defaultChecked={true} />, container);
const node = container.firstChild;
expect(node.value).toBe('on');
expect(node.hasAttribute('value')).toBe(false);
});
});
});
|
export default {
text: '#000',
textHighlight: '#000',
icon: '#000',
unknown: '#c0ab7f',
success: '#4eb6a3',
warning: '#d1be65',
failure: '#ff9176',
}
|
'use strict'
module.exports = {
contract: `contract structArrayStorage {
struct intStruct {
int8 i8;
int16 i16;
uint32 ui32;
int i256;
uint16 ui16;
int32 i32;
}
intStruct intStructDec;
int64[7] i5;
int64[] idyn5;
int32[][4] dyn1;
int32[][4][] dyn2;
struct simpleStruct {
int8 i8;
string str;
}
simpleStruct[][3] arrayStruct;
constructor () public {
intStructDec.i8 = 32;
intStructDec.i16 = -54;
intStructDec.ui32 = 128;
intStructDec.i256 = -1243565465756;
intStructDec.ui16 = 34556;
intStructDec.i32 = -345446546;
i5[0] = -2134;
i5[1] = 345;
i5[2] = -3246;
i5[3] = 4357;
i5[4] = 324;
i5[5] = -2344;
i5[6] = 3254;
idyn5.push(-2134);
idyn5.push(345);
idyn5.push(-3246);
idyn5.push(4357);
idyn5.push(324);
idyn5.push(-2344);
idyn5.push(3254);
idyn5.push(-254);
idyn5.push(-2354);
dyn1[0].push(3);
dyn1[1].push(12);
dyn1[1].push(-12);
dyn1[1].push(-1234);
dyn1[2].push(1);
dyn1[2].push(12);
dyn1[2].push(1235);
dyn1[2].push(-12);
dyn1[2].push(-123456);
dyn1[2].push(-23435435);
dyn1[2].push(543543);
dyn1[2].push(2);
dyn1[2].push(-1);
dyn1[2].push(232432);
dyn1[3].push(232432);
dyn1[3].push(232432);
int32[][4] memory e1;
e1[0] = new int32[](3);
e1[1] = new int32[](3);
e1[2] = new int32[](3);
e1[3] = new int32[](3);
e1[0][0] = 23;
e1[0][1] = -23;
e1[0][2] = -28;
e1[1][0] = 23;
e1[1][1] = -23;
e1[1][2] = -28;
e1[2][0] = 23;
e1[2][1] = -23;
e1[2][2] = -28;
e1[3][0] = 23;
e1[3][1] = -23;
e1[3][2] = -28;
dyn2.push(e1);
int32[][4] memory e2;
e2[0] = new int32[](3);
e2[1] = new int32[](3);
e2[2] = new int32[](3);
e2[3] = new int32[](3);
e2[0][0] = 23;
e2[0][1] = -23;
e2[0][2] = -28;
e2[1][0] = 23;
e2[1][1] = -23;
e2[1][2] = -28;
e2[2][0] = 23;
e2[2][1] = -23;
e2[2][2] = -28;
e2[3][0] = 23;
e2[3][1] = -23;
e2[3][2] = -28;
dyn2.push(e2);
simpleStruct memory s1;
s1.i8 = 34;
s1.str = 'test_str_short';
simpleStruct memory s2;
s1.i8 = -123;
s1.str = 'test_str_long test_str_lo ngtest_str_longtest_str_ longtest_str_longtest_ str_longtest_str_l ongtest_str_long';
arrayStruct[0].push(s1);
arrayStruct[0].push(s2);
simpleStruct memory s3;
s3.i8 = 50;
s3.str = 'test_str_short';
arrayStruct[1].push(s3);
simpleStruct memory s4;
s4.i8 = 60;
s4.str = 'test_str_short';
simpleStruct memory s5;
s5.i8 = 84;
s5.str = 'test_str_long test_str_lo ngtest_str_longtest_str_ longtest_str_longtest_ str_longtest_str_l ongtest_str_long';
simpleStruct memory s6;
s5.i8 = -34;
s5.str = 'test_str_short';
arrayStruct[2].push(s4);
arrayStruct[2].push(s5);
arrayStruct[2].push(s6);
}
}
`,
storage: {
'0x0000000000000000000000000000000000000000000000000000000000000000': '0x0000000000000000000000000000000000000000000000000000000080ffca20',
'0x0000000000000000000000000000000000000000000000000000000000000001': '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffede75b8df64',
'0x0000000000000000000000000000000000000000000000000000000000000002': '0x0000000000000000000000000000000000000000000000000000eb68e76e86fc',
'0x0000000000000000000000000000000000000000000000000000000000000003': '0x0000000000001105fffffffffffff3520000000000000159fffffffffffff7aa',
'0x0000000000000000000000000000000000000000000000000000000000000004': '0x00000000000000000000000000000cb6fffffffffffff6d80000000000000144',
'0x0000000000000000000000000000000000000000000000000000000000000005': '0x0000000000000000000000000000000000000000000000000000000000000009',
'0x036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0': '0x0000000000001105fffffffffffff3520000000000000159fffffffffffff7aa',
'0x036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db1': '0xffffffffffffff020000000000000cb6fffffffffffff6d80000000000000144',
'0x036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db2': '0x000000000000000000000000000000000000000000000000fffffffffffff6ce',
'0x0000000000000000000000000000000000000000000000000000000000000006': '0x0000000000000000000000000000000000000000000000000000000000000001',
'0x0000000000000000000000000000000000000000000000000000000000000007': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0x0000000000000000000000000000000000000000000000000000000000000008': '0x000000000000000000000000000000000000000000000000000000000000000a',
'0x0000000000000000000000000000000000000000000000000000000000000009': '0x0000000000000000000000000000000000000000000000000000000000000002',
'0xf652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688': '0x0000000000000000000000000000000000000000fffffb2efffffff40000000c',
'0xf3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee3': '0x0000000200084b37fe9a6755fffe1dc0fffffff4000004d30000000c00000001',
'0xf3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee4': '0x00000000000000000000000000000000000000000000000000038bf0ffffffff',
'0x6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af': '0x00000000000000000000000000000000000000000000000000038bf000038bf0',
'0x000000000000000000000000000000000000000000000000000000000000000a': '0x0000000000000000000000000000000000000000000000000000000000000002',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a8': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a9': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2aa': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2ab': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2ac': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2ad': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2ae': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2af': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0x410c2796757c1866e144712b649ab035b22d7295530f125d2b7bc17fa7b793b5': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0x06b493c1ca289c5326ef56c162cd187bf96c737c2c9bbda318cc345be15042af': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0x7a0b543a77c72a2154fae01417d93ab4a7f07c9a6bbce5febfeb9904a41b7914': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0x5370eae143cc2f6260640bd734b0cdaf587bbcfc81362df39d56d5a29a7e663b': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0xd5211e5652076f058928f5b24e1816690291c298b337ea927f8d0f3aabb8a05a': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0xf232dee5d9edbb879fab95c81a3867fe42b8d79b05e9c99336c5297487f94e8d': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0x8a82e6d20ae2c2a82dd8e575dac6354ce964fd35e3d1cdb79bb1757c6a7675b6': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0xa9e6724ab7d0ccf2de69222bc5703c9df2049038736e6d57f437315272b76a3a': '0x0000000000000000000000000000000000000000ffffffe4ffffffe900000017',
'0x000000000000000000000000000000000000000000000000000000000000000b': '0x0000000000000000000000000000000000000000000000000000000000000002',
'0x000000000000000000000000000000000000000000000000000000000000000c': '0x0000000000000000000000000000000000000000000000000000000000000001',
'0x000000000000000000000000000000000000000000000000000000000000000d': '0x0000000000000000000000000000000000000000000000000000000000000003',
'0x0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db9': '0x0000000000000000000000000000000000000000000000000000000000000022',
'0x0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01dba': '0x746573745f7374725f73686f727400000000000000000000000000000000001c',
'0x0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01dbb': '0x0000000000000000000000000000000000000000000000000000000000000085',
'0x0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01dbc': '0x00000000000000000000000000000000000000000000000000000000000000db',
'0x40abea1508c7557b93b3e219e777ce8530b60f9f8452ef1c627dbc62b53708fc': '0x746573745f7374725f6c6f6e6720746573745f7374725f6c6f206e6774657374',
'0x40abea1508c7557b93b3e219e777ce8530b60f9f8452ef1c627dbc62b53708fd': '0x5f7374725f6c6f6e67746573745f7374725f206c6f6e67746573745f7374725f',
'0x40abea1508c7557b93b3e219e777ce8530b60f9f8452ef1c627dbc62b53708fe': '0x6c6f6e67746573745f207374725f6c6f6e67746573745f7374725f6c206f6e67',
'0x40abea1508c7557b93b3e219e777ce8530b60f9f8452ef1c627dbc62b53708ff': '0x746573745f7374725f6c6f6e6700000000000000000000000000000000000000',
'0xdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c7': '0x0000000000000000000000000000000000000000000000000000000000000032',
'0xdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c8': '0x746573745f7374725f73686f727400000000000000000000000000000000001c',
'0xd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb5': '0x000000000000000000000000000000000000000000000000000000000000003c',
'0xd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb6': '0x746573745f7374725f73686f727400000000000000000000000000000000001c',
'0xd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb7': '0x0000000000000000000000000000000000000000000000000000000000000054',
'0xd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb8': '0x00000000000000000000000000000000000000000000000000000000000000db',
'0x87466a1ae97409dd9d9cd9368751b439509d8b3f8fc2bb47a4264e5d6fd4d324': '0x746573745f7374725f6c6f6e6720746573745f7374725f6c6f206e6774657374',
'0x87466a1ae97409dd9d9cd9368751b439509d8b3f8fc2bb47a4264e5d6fd4d325': '0x5f7374725f6c6f6e67746573745f7374725f206c6f6e67746573745f7374725f',
'0x87466a1ae97409dd9d9cd9368751b439509d8b3f8fc2bb47a4264e5d6fd4d326': '0x6c6f6e67746573745f207374725f6c6f6e67746573745f7374725f6c206f6e67',
'0x87466a1ae97409dd9d9cd9368751b439509d8b3f8fc2bb47a4264e5d6fd4d327': '0x746573745f7374725f6c6f6e6700000000000000000000000000000000000000',
'0xd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb9': '0x00000000000000000000000000000000000000000000000000000000000000de',
'0xd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eba': '0x746573745f7374725f73686f727400000000000000000000000000000000001c'
}
}
|
import * as models from '../index';
import {globalBeforeEach} from '../../__jest__/before-each';
describe('init()', () => {
beforeEach(globalBeforeEach);
it('contains all required fields', async () => {
Date.now = jest.fn().mockReturnValue(1478795580200);
expect(models.request.init()).toEqual({
isPrivate: false,
authentication: {},
body: {},
headers: [],
metaSortKey: -1478795580200,
method: 'GET',
name: 'New Request',
description: '',
parameters: [],
url: '',
settingStoreCookies: true,
settingSendCookies: true,
settingDisableRenderRequestBody: false,
settingEncodeUrl: true,
settingRebuildPath: true
});
});
});
describe('create()', async () => {
beforeEach(globalBeforeEach);
it('creates a valid request', async () => {
Date.now = jest.fn().mockReturnValue(1478795580200);
const request = await models.request.create({
name: 'Test Request',
parentId: 'fld_124',
description: 'A test Request'
});
const expected = {
_id: 'req_cc1dd2ca4275747aa88199e8efd42403',
isPrivate: false,
created: 1478795580200,
modified: 1478795580200,
parentId: 'fld_124',
type: 'Request',
authentication: {},
description: 'A test Request',
body: {},
headers: [],
metaSortKey: -1478795580200,
method: 'GET',
name: 'Test Request',
parameters: [],
url: '',
settingStoreCookies: true,
settingSendCookies: true,
settingDisableRenderRequestBody: false,
settingEncodeUrl: true,
settingRebuildPath: true
};
expect(request).toEqual(expected);
expect(await models.request.getById(expected._id)).toEqual(expected);
});
it('fails when missing parentId', async () => {
Date.now = jest.fn().mockReturnValue(1478795580200);
expect(() => models.request.create({name: 'Test Request'})).toThrow('New Requests missing `parentId`');
});
});
describe('updateMimeType()', async () => {
beforeEach(globalBeforeEach);
it('adds header when does not exist', async () => {
const request = await models.request.create({name: 'My Request', parentId: 'fld_1'});
expect(request).not.toBeNull();
const newRequest = await models.request.updateMimeType(request, 'text/html');
expect(newRequest.headers).toEqual([{name: 'Content-Type', value: 'text/html'}]);
});
it('replaces header when exists', async () => {
const request = await models.request.create({
name: 'My Request',
parentId: 'fld_1',
headers: [
{name: 'content-tYPE', value: 'application/json'},
{name: 'foo', value: 'bar'},
{bad: true},
null
]
});
expect(request).not.toBeNull();
const newRequest = await models.request.updateMimeType(request, 'text/html');
expect(newRequest.headers).toEqual([
{name: 'content-tYPE', value: 'text/html'},
{name: 'foo', value: 'bar'},
{bad: true},
null
]);
});
it('replaces header when exists', async () => {
const request = await models.request.create({
name: 'My Request',
parentId: 'fld_1',
headers: [{name: 'content-tYPE', value: 'application/json'}]
});
expect(request).not.toBeNull();
const newRequest = await models.request.updateMimeType(request, 'text/html');
expect(newRequest.headers).toEqual([{name: 'content-tYPE', value: 'text/html'}]);
});
it('keeps content-type', async () => {
const request = await models.request.create({
name: 'My Request',
parentId: 'fld_1',
headers: [{name: 'content-tYPE', value: 'application/json'}]
});
expect(request).not.toBeNull();
const newRequest = await models.request.updateMimeType(request, null);
expect(newRequest.body).toEqual({});
expect(newRequest.headers).toEqual([{name: 'content-tYPE', value: 'application/json'}]);
});
it('uses saved body when provided', async () => {
const request = await models.request.create({
name: 'My Request',
parentId: 'fld_1',
body: {
text: 'My Data'
}
});
expect(request).not.toBeNull();
const newRequest = await models.request.updateMimeType(request, 'application/json', false, {text: 'Saved Data'});
expect(newRequest.body.text).toEqual('Saved Data');
});
it('uses existing body when saved body not provided', async () => {
const request = await models.request.create({
name: 'My Request',
parentId: 'fld_1',
body: {
text: 'My Data'
}
});
expect(request).not.toBeNull();
const newRequest = await models.request.updateMimeType(request, 'application/json', false, {});
expect(newRequest.body.text).toEqual('My Data');
});
});
describe('migrate()', () => {
beforeEach(globalBeforeEach);
it('migrates basic case', () => {
const original = {
headers: [],
body: 'hello world!'
};
const expected = {
headers: [],
body: {mimeType: '', text: 'hello world!'},
url: ''
};
expect(models.request.migrate(original)).toEqual(expected);
});
it('migrates form-urlencoded', () => {
const original = {
headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}],
body: 'foo=bar&baz={{ hello }}'
};
const expected = {
headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}],
body: {
mimeType: 'application/x-www-form-urlencoded',
params: [
{name: 'foo', value: 'bar'},
{name: 'baz', value: '{{ hello }}'}
]
},
url: ''
};
expect(models.request.migrate(original)).toEqual(expected);
});
it('migrates form-urlencoded with charset', () => {
const original = {
headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded; charset=utf-8'}],
body: 'foo=bar&baz={{ hello }}'
};
const expected = {
headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded; charset=utf-8'}],
body: {
mimeType: 'application/x-www-form-urlencoded',
params: [
{name: 'foo', value: 'bar'},
{name: 'baz', value: '{{ hello }}'}
]
},
url: ''
};
expect(models.request.migrate(original)).toEqual(expected);
});
it('migrates form-urlencoded malformed', () => {
const original = {
headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}],
body: '{"foo": "bar"}'
};
const expected = {
headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}],
body: {
mimeType: 'application/x-www-form-urlencoded',
params: [
{name: '{"foo": "bar"}', value: ''}
]
},
url: ''
};
expect(models.request.migrate(original)).toEqual(expected);
});
it('migrates mime-type', () => {
const contentToMimeMap = {
'application/json; charset=utf-8': 'application/json',
'text/plain': 'text/plain',
'malformed': 'malformed'
};
for (const contentType of Object.keys(contentToMimeMap)) {
const original = {
headers: [{name: 'content-type', value: contentType}],
body: ''
};
const expected = {
headers: [{name: 'content-type', value: contentType}],
body: {mimeType: contentToMimeMap[contentType], text: ''},
url: ''
};
expect(models.request.migrate(original)).toEqual(expected);
}
});
it('skips migrate for schema 1', () => {
const original = {
body: {mimeType: 'text/plain', text: 'foo'}
};
expect(models.request.migrate(original)).toBe(original);
});
it('migrates with weird data', () => {
const newBody = {body: {mimeType: '', text: 'foo bar!'}};
const stringBody = {body: 'foo bar!'};
const nullBody = {body: null};
const noBody = {};
const expected = {
body: {
mimeType: '',
text: 'foo bar!'
},
url: ''
};
const expected2 = {
body: {},
url: ''
};
expect(models.request.migrate(newBody)).toEqual(expected);
expect(models.request.migrate(stringBody)).toEqual(expected);
expect(models.request.migrate(nullBody)).toEqual(expected2);
expect(models.request.migrate(noBody)).toEqual(expected2);
});
it('migrates from initModel()', async () => {
Date.now = jest.fn().mockReturnValue(1478795580200);
const original = {
_id: 'req_123',
headers: [],
body: 'hello world!'
};
const expected = {
_id: 'req_123',
isPrivate: false,
type: 'Request',
url: '',
created: 1478795580200,
modified: 1478795580200,
metaSortKey: -1478795580200,
name: 'New Request',
description: '',
method: 'GET',
headers: [],
authentication: {},
parameters: [],
parentId: null,
body: {mimeType: '', text: 'hello world!'},
settingStoreCookies: true,
settingSendCookies: true,
settingDisableRenderRequestBody: false,
settingEncodeUrl: true,
settingRebuildPath: true
};
const migrated = await models.initModel(models.request.type, original);
expect(migrated).toEqual(expected);
});
});
|
import React from 'react';
import {
StyleSheet,
Text,
View,
Button,
Image,
Dimensions,
} from 'react-native';
import {
StackNavigator,
} from 'react-navigation';
class MenuScreen extends React.Component {
static navigationOptions = {
title: 'Menu'
}
render() {
const imageURI = Expo.Asset.fromModule(require('../assets/screens/menu.png')).uri;
return (
<View style={{position: 'relative', alignItems: 'flex-end', justifyContent: 'center', flex: 1}}>
<Text onPress={this._handlePress}>Go to Settings</Text>
<Image
source={{ uri: imageURI }}
style={{ height: '100%', width: '100%', opacity: 0.1, position: 'absolute'}}
/>
<Button
title="aaaaaaaaaaaa"
style={{ height: 100, width: '100%', position: 'absolute', float: 'down', bottom: 0 }}
onPress={this._handleButtonPress}
/>
</View>
)
}
_handlePress = () => {
this.props.navigation.navigate('Menu');
}
_handleButtonPress = () => {
this.props.navigation.navigate('Menu');
}
}
|
/* eslint-env mocha */
"use strict";
var assert = require("chai").assert;
var setGasPrice = require("../src/set-gas-price");
describe("set-gas-price", function () {
var test = function (t) {
it(t.description, function (done) {
setGasPrice(t.rpc, function (err, gasPrice) {
t.assertions(err, gasPrice);
done();
});
});
};
test({
description: "set current gas price",
rpc: {
eth: {
gasPrice: function (callback) {
callback(null, "0x1234");
}
}
},
assertions: function (err, gasPrice) {
assert.strictEqual(gasPrice, 4660);
}
});
test({
description: "gasPrice is undefined",
rpc: {
eth: {
gasPrice: function (callback) {
callback(null, undefined);
}
}
},
assertions: function (err, gasPrice) {
assert.isTrue(err instanceof Error);
assert.isUndefined(gasPrice);
}
});
test({
description: "gasPrice is null",
rpc: {
eth: {
gasPrice: function (callback) {
callback(null, null);
}
}
},
assertions: function (err, gasPrice) {
assert.isTrue(err instanceof Error);
assert.isUndefined(gasPrice);
}
});
});
|
var _ = require('lodash');
module.exports = function(grunt) {
'use-strict';
/* Initialize configuration
-----------------------------------------------------*/
require('load-grunt-tasks')(grunt);
require('time-grunt')(grunt);
// default config
var config = {
sourcemap: false,
compass: false
};
// apply command line configuration
_.forEach(grunt.option.flags(), function(option) {
config[option] = grunt.option(option);
});
// default paths
var paths = {
assets: 'assets',
build: 'assets',
sass: 'sass',
scss: 'scss',
css: 'css',
js: 'js',
img: 'images',
fonts: 'fonts'
};
/* Tasks
-----------------------------------------------------*/
var tasks = {};
tasks.paths = paths;
// Watch---------------------------
// [TODO]: add support to compass
// [TODO]: add support to coffee
tasks.watch = {
gruntfile: {
files: ['./Gruntfile.js'],
options: {
reload: true
}
},
stylesheets: {
files: [
'<%= paths.assets %>/<%= paths.scss %>/**/*.{scss,sass}',
'<%= paths.assets %>/<%= paths.sass %>/**/*.{scss,sass}',
],
tasks: ['sass', 'autoprefixer']
}
};
// BrowserSync --------------------
// [TODO]: configure proxy option
tasks.browserSync = {
dev: {
bsFiles: {
src: [
'<%= paths.build %>/<%= paths.css %>/**/*.css',
'<%= paths.build %>/<%= paths.img %>/**/*.{png,jpg,gif}',
'<%= paths.build %>/<%= paths.js %>/**/*.js',
'**/*.php'
]
},
options: {
watchTask: true,
ghostMode: {
location: true
},
debugInfo: false // silence is golden.
}
}
};
// Sass ---------------------------
tasks.sass = {
dev: {
files: [
{
expand: true,
cwd: '<%= paths.assets %>/<%= paths.scss %>/',
src: [
'**/*.scss'
],
dest: '<%= paths.build %>/<%= paths.css %>',
ext: '.css',
extDot: 'last'
},
{
expand: true,
cwd: '<%= paths.assets %>/<%= paths.sass %>/',
src: [
'**/*.sass'
],
dest: '<%= paths.build %>/<%= paths.css %>',
ext: '.css',
extDot: 'last'
}
],
options: {
style: 'compressed',
sourcemap: config.sourcemap,
compass: config.compass
}
}
};
// Imagemin -----------------------
tasks.imagemin = {
dev: {
files: [{
expand: true,
cwd: '<%= paths.assets %>/<%= paths.img %>',
src: '**/*.{png,jpg,gif,svg}',
dest: '<%= paths.build %>/<%= paths.img %>'
}],
options: {
optimizationLevel: 7
}
}
};
// Autoprefixer -------------------
tasks.autoprefixer = {
options: {
map: true,
browsers: ['last 2 versions', 'ie 8', 'ie 9', '> 1%']
},
dev: {
files: [{
expand: true,
cwd: '<%= paths.build %>/<%= paths.css %>/',
src: [
'**/*.css'
],
dest: '<%= paths.build %>/<%= paths.css %>',
ext: '.css',
extDot: 'last'
}]
}
};
// configures grunt
grunt.initConfig(tasks);
/* Group Tasks
-----------------------------------------------------*/
grunt.registerTask('default', [
'browserSync',
'watch'
]);
grunt.registerTask('build', [
'sass',
'autoprefixer',
'imagemin'
]);
};
|
var assert = require('assert')
var url = require('url')
var _ = require('lodash')
var sinon = require('sinon')
var __ = require('@carbon-io/carbon-core').fibers.__(module)
var ejson = require('@carbon-io/carbon-core').ejson
var o = require('@carbon-io/carbon-core').atom.o(module)
var _o = require('@carbon-io/carbon-core').bond._o(module)
var testtube = require('@carbon-io/carbon-core').testtube
var carbond = require('../..')
var pong = require('../fixtures/pong')
/**************************************************************************
* update tests
*/
__(function() {
module.exports = o.main({
/**********************************************************************
* _type
*/
_type: testtube.Test,
/**********************************************************************
* name
*/
name: 'UpdateTests',
/**********************************************************************
* tests
*/
tests: [
o({
_type: carbond.test.ServiceTest,
name: 'DefaultConfigUpdateTests',
service: o({
_type: pong.Service,
endpoints: {
update: o({
_type: pong.Collection,
enabled: {update: true}
})
}
}),
tests: [
{
name: 'UpdateTest',
description: 'Test PATCH',
reqSpec: {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: 1
})
},
body: {
foo: 'bar'
}
},
resSpec: {
statusCode: 200,
body: {n: 1}
}
},
{
name: 'UpdateNoBodyTest',
description: 'Test PATCH with no body',
reqSpec: {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: 0
})
}
// NOTE: an undefined body gets converted to `{}` which complies with the default
// update schema
},
resSpec: {
statusCode: 200,
body: {n: 0}
}
},
{
name: 'UpdateReturnValueValidationTest',
description: 'Test invalid handler return value',
reqSpec: {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: {n: 0}
})
}
},
resSpec: {
statusCode: 500,
}
},
{
name: 'UpdateUpsertButNotSupportedTest',
description: 'Test upsert throws when not supported',
reqSpec: {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: {val: {$args: 0}, created: true}
})
},
body: {
foo: 'bar'
}
},
resSpec: {
statusCode: 500
}
},
{
name: 'UpdateUpsertWithUpsertParamButNotSupportedTest',
description: 'Test upsert throws when not supported even if "upsert" parameter passed',
setup: function() {
this.preUpdateOperationSpy = sinon.spy(this.parent.service.endpoints.update, 'preUpdateOperation')
this.updateSpy = sinon.spy(this.parent.service.endpoints.update, 'update')
},
teardown: function() {
try {
assert(!('upsert' in this.preUpdateOperationSpy.firstCall.args[1].parameters))
assert(!('upsert' in this.updateSpy.firstCall.args[0]))
} finally {
this.preUpdateOperationSpy.restore()
this.updateSpy.restore()
}
},
reqSpec: {
url: '/update',
method: 'PATCH',
parameters: {
upsert: true
},
headers: {
'x-pong': ejson.stringify({
update: {val: {$args: 0}, created: true}
})
},
body: {
foo: 'bar'
}
},
resSpec: {
statusCode: 500
}
},
]
}),
o({
_type: carbond.test.ServiceTest,
name: 'CustomSchemaConfigUpdateTests',
service: o({
_type: pong.Service,
endpoints: {
update: o({
_type: pong.Collection,
enabled: {update: true},
updateConfig: {
schema: {
type: 'object',
properties: {
foo: {
type: 'string',
pattern: '^(bar|baz|yaz)$'
}
},
patternProperties: {
'^\\d+$': {type: 'string'}
},
additionalProperties: false
}
}
}),
update1: o({
_type: pong.Collection,
enabled: {update: true},
updateConfig: {
'$parameters.update.schema': {
type: 'object',
properties: {
foo: {
type: 'string',
pattern: '^(bar|baz|yaz)$'
}
},
patternProperties: {
'^\\d+$': {type: 'string'}
},
additionalProperties: false
}
}
})
}
}),
tests: [
{
name: 'FailUpdateSchemaTest',
description: 'Test PATCH with malformed body',
reqSpec: {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: 1
})
},
body: {
bar: 'foo',
666: 'foo'
}
},
resSpec: {
statusCode: 400
}
},
{
name: 'SuccessUpdateSchemaTest',
description: 'Test PATCH with well formed body',
reqSpec: {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: 1
})
},
body: {
foo: 'bar',
666: 'foo'
}
},
resSpec: {
statusCode: 200,
body: {n: 1}
}
},
{
name: 'FailUpdate1SchemaTest',
description: 'Test PATCH with malformed body',
setup: function(context) {
this.history = context.httpHistory
},
reqSpec: function() {
return _.assign(_.clone(this.history.getReqSpec('FailUpdateSchemaTest')),
{url: '/update1'})
},
resSpec: {
$property: {get: function() {return this.history.getResSpec('FailUpdateSchemaTest')}}
}
},
{
name: 'SuccessUpdate1SchemaTest',
description: 'Test PATCH with well formed body',
setup: function(context) {
this.history = context.httpHistory
},
reqSpec: function() {
return _.assign(_.clone(this.history.getReqSpec('SuccessUpdateSchemaTest')),
{url: '/update1'})
},
resSpec: {
$property: {get: function() {return this.history.getResSpec('SuccessUpdateSchemaTest')}}
}
}
]
}),
o({
_type: carbond.test.ServiceTest,
name: 'SupportsUpsertDoesNotReturnUpsertedObjectsConfigUpdateTests',
service: o({
_type: pong.Service,
endpoints: {
update: o({
_type: pong.Collection,
enabled: {update: true},
updateConfig: {
supportsUpsert: true
}
})
}
}),
setup: function(context) {
carbond.test.ServiceTest.prototype.setup.apply(this, arguments)
context.global.idParameterName = this.service.endpoints.update.idParameterName
context.global.idHeaderName = this.service.endpoints.update.idHeaderName
},
teardown: function(context) {
delete context.global.idHeaderName
delete context.global.idParameterName
carbond.test.ServiceTest.prototype.teardown.apply(this, arguments)
},
tests: [
{
name: 'UpdateWithUpsertMissingParameterTest',
description: 'Test PATCH fails when upsert performed but not requested',
reqSpec: {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: {
val: 1,
created: true
}
})
},
body: {
foo: 'bar'
}
},
resSpec: {
statusCode: 500
}
},
{
name: 'UpdateWithUpsertTest',
description: 'Test PATCH results in upsert when requested',
reqSpec: function(context) {
return {
url: '/update',
method: 'PATCH',
parameters: {
upsert: true
},
headers: {
'x-pong': ejson.stringify({
update: {
val: [{[context.global.idParameterName]: '0'}],
created: true
}
})
},
body: {
foo: 'bar'
}
}
},
resSpec: {
statusCode: 201,
headers: function(headers, context) {
assert.deepStrictEqual(headers.location, '/update?' + context.global.idParameterName + '=0')
assert.deepStrictEqual(headers[context.global.idHeaderName], '["0"]')
},
body: {n: 1}
}
},
{
name: 'UpdateWithUpsertReturnsNumberOfUpsertedObjectsTest',
description: 'Test PATCH fails when number of upserted objects returned',
reqSpec: function(context) {
return {
url: '/update',
method: 'PATCH',
parameters: {
upsert: true
},
headers: {
'x-pong': ejson.stringify({
update: {
val: 1,
created: true
}
})
},
body: {
foo: 'bar'
}
}
},
resSpec: {
statusCode: 500
}
},
]
}),
o({
_type: carbond.test.ServiceTest,
name: 'SupportsUpsertReturnUpsertedObjectsConfigUpdateTests',
service: o({
_type: pong.Service,
endpoints: {
update: o({
_type: pong.Collection,
enabled: {update: true},
updateConfig: {
supportsUpsert: true,
returnsUpsertedObjects: true
}
})
}
}),
setup: function(context) {
carbond.test.ServiceTest.prototype.setup.apply(this, arguments)
context.global.idParameterName = this.service.endpoints.update.idParameterName
context.global.idHeaderName = this.service.endpoints.update.idHeaderName
},
teardown: function(context) {
delete context.global.idHeaderName
delete context.global.idParameterName
carbond.test.ServiceTest.prototype.teardown.apply(this, arguments)
},
tests: [
{
name: 'UpdateWithUpsertMissingParameterTest',
description: 'Test PATCH fails when upsert performed but not requested',
reqSpec: function(context) {
return {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: {
val: [{[context.global.idParameterName]: '0', foo: 'bar'}],
created: true
}
})
},
body: {
foo: 'bar'
}
}
},
resSpec: {
statusCode: 500
}
},
{
name: 'UpdateWithUpsertTest',
description: 'Test PATCH results in upsert when requested',
reqSpec: function(context) {
return {
url: '/update',
method: 'PATCH',
parameters: {
upsert: true
},
headers: {
'x-pong': ejson.stringify({
update: {
val: [{[context.global.idParameterName]: '0', foo: 'bar'}],
created: true
}
})
},
body: {
foo: 'bar'
}
}
},
resSpec: {
statusCode: 201,
headers: function(headers, context) {
assert.deepStrictEqual(headers.location, '/update?' + context.global.idParameterName + '=0')
assert.deepStrictEqual(headers[context.global.idHeaderName], '["0"]')
},
body: function(body, context) {
assert.deepStrictEqual(body, [{[context.global.idParameterName]: '0', foo: 'bar'}])
}
}
},
{
name: 'UpdateWithUpsertReturnsNumberOfUpsertedObjectsTest',
description: 'Test PATCH fails when number of upserted objects returned',
reqSpec: function(context) {
return {
url: '/update',
method: 'PATCH',
parameters: {
upsert: true
},
headers: {
'x-pong': ejson.stringify({
update: {
val: 1,
created: true
}
})
},
body: {
foo: 'bar'
}
}
},
resSpec: {
statusCode: 500
}
},
]
}),
o({
_type: carbond.test.ServiceTest,
name: 'CustomConfigParameterTests',
service: o({
_type: pong.Service,
endpoints: {
update: o({
_type: pong.Collection,
idGenerator: pong.util.collectionIdGenerator,
enabled: {update: true},
updateConfig: {
parameters: {
$merge: {
foo: {
location: 'header',
schema: {
type: 'number',
minimum: 0,
multipleOf: 2
}
}
}
}
}
})
}
}),
tests: [
o({
_type: testtube.Test,
name: 'UpdateConfigCustomParameterInitializationTest',
doTest: function(context) {
let updateOperation = this.parent.service.endpoints.update.patch
assert.deepEqual(updateOperation.parameters, {
update: {
name: 'update',
location: 'body',
description: carbond.collections.UpdateConfig._STRINGS.parameters.update.description,
schema: { type: 'object' },
required: true,
default: undefined
},
foo: {
name: 'foo',
location: 'header',
description: undefined,
schema: {type: 'number', minimum: 0, multipleOf: 2},
required: false,
default: undefined
},
})
}
}),
{
name: 'UpdateConfigCustomParameterPassedViaOptionsFailTest',
setup: function(context) {
context.local.updateSpy = sinon.spy(this.parent.service.endpoints.update, 'update')
},
teardown: function(context) {
assert.equal(context.local.updateSpy.called, false)
context.local.updateSpy.restore()
},
reqSpec: function(context) {
return {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: 1
}),
foo: 3
},
body: {foo: 'bar'}
}
},
resSpec: {
statusCode: 400
}
},
{
name: 'UpdateConfigCustomParameterPassedViaOptionsSuccessTest',
setup: function(context) {
context.local.updateSpy = sinon.spy(this.parent.service.endpoints.update, 'update')
},
teardown: function(context) {
assert.equal(context.local.updateSpy.firstCall.args[1].foo, 4)
context.local.updateSpy.restore()
},
reqSpec: function(context) {
return {
url: '/update',
method: 'PATCH',
headers: {
'x-pong': ejson.stringify({
update: 1
}),
foo: 4
},
body: {foo: 'bar'}
}
},
resSpec: {
statusCode: 200
}
}
]
}),
o({
_type: carbond.test.ServiceTest,
name: 'HookAndHandlerContextTests',
service: o({
_type: carbond.Service,
endpoints: {
update: o({
_type: carbond.collections.Collection,
enabled: {update: true},
preUpdateOperation: function(config, req, res, context) {
context.preUpdateOperation = 1
return carbond.collections.Collection.prototype.preUpdateOperation.apply(this, arguments)
},
preUpdate: function(update, options, context) {
context.preUpdate = 1
return carbond.collections.Collection.prototype.preUpdate.apply(this, arguments)
},
update: function(update, options, context) {
context.update = 1
return 1
},
postUpdate: function(result, update, options, context) {
context.postUpdate = 1
return carbond.collections.Collection.prototype.postUpdate.apply(this, arguments)
},
postUpdateOperation: function(result, config, req, res, context) {
context.postUpdateOperation = 1
res.set('context', ejson.stringify(context))
return carbond.collections.Collection.prototype.postUpdateOperation.apply(this, arguments)
}
})
}
}),
tests: [
{
reqSpec: {
url: '/update',
method: 'PATCH'
},
resSpec: {
statusCode: 200,
headers: function(headers) {
assert.deepEqual(ejson.parse(headers.context), {
preUpdateOperation: 1,
preUpdate: 1,
update: 1,
postUpdate: 1,
postUpdateOperation: 1
})
}
}
}
]
})
]
})
})
|
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chris Spencer <chris.ag.spencer AT googlemail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
var oop = require("pilot/oop");
var Behaviour = require('ace/mode/behaviour').Behaviour;
var CstyleBehaviour = function () {
this.add("braces", "insertion", function (state, action, editor, session, text) {
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '{' + selected + '}',
selection: false
}
} else {
return {
text: '{}',
selection: [1, 1]
}
}
} else if (text == '}') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
}
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1});
if (!openBracePos)
return false;
var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString());
var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
}
}
}
return false;
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
}
}
return false;
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '(' + selected + ')',
selection: false
}
} else {
return {
text: '()',
selection: [1, 1]
}
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
}
}
}
}
return false;
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
return false;
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '"' + selected + '"',
selection: false
}
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
// We're escaped.
if (leftChar == '\\') {
return false;
}
// Find what token we're inside.
var tokens = session.getTokens(selection.start.row, selection.start.row)[0].tokens;
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf('"');
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
// Try and be smart about when we auto insert.
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) {
return {
text: '""',
selection: [1,1]
}
} else if (token && token.type === "string") {
// Ignore input and move right one if we're typing over the closing quote.
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '"') {
return {
text: '',
selection: [1, 1]
}
}
}
}
}
return false;
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '"') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
return false;
});
}
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
}); |
/*jslint node: true */
'use strict';
var
Figuier = require('../figuier'),
Use;
module.exports = Use = function (process, config) {
if (!(this instanceof Use)) {
return new Use(process, this);
}
if (!(config instanceof Figuier)) {
throw 'Trying to manually instantiate';
}
this.process = process.bind(config);
}; |
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Analytics",
"Api",
"Application",
"Assets",
"BaseApplication",
"BaseCollection",
"BaseModel",
"BasePage",
"BaseRouter",
"BaseView",
"Bootstrap",
"CanvasCharacter",
"CanvasStroke",
"CharacterEditor",
"DataDecomp",
"DataDecomps",
"DataItem",
"DataItems",
"DataParam",
"DataParams",
"DataReview",
"DataReviews",
"DataSRSConfig",
"DataSRSConfigs",
"DataSentence",
"DataSentences",
"DataStroke",
"DataStrokes",
"DataVocab",
"DataVocabList",
"DataVocabLists",
"DataVocabs",
"Dialogs",
"IndexedDBAdapter",
"Kana",
"ListRowTable",
"ListSectionTable",
"ListTable",
"Mapper",
"PageAccount",
"PageCreateAccount",
"PageDashboard",
"PageExport",
"PageFilters",
"PageLanding",
"PageLanguageSelect",
"PageLearningCenter",
"PageList",
"PageListSection",
"PageListSelect",
"PageLists",
"PageLogin",
"PageScratchpad",
"PageSettings",
"PageStats",
"PageStrokeOrder",
"PageStudy",
"PageTests",
"PageWords",
"ParamEditor",
"Params",
"PinyinConverter",
"Prompt",
"PromptCanvas",
"PromptController",
"PromptDefn",
"PromptGradingButtons",
"PromptRdng",
"PromptRune",
"PromptTone",
"Recognizer",
"Router",
"RouterAccountCreation",
"RouterAdmin",
"RouterLearningCenter",
"ScheduleItem",
"ScheduleItems",
"Shortstraw",
"Sidebars",
"Strokes",
"Timer",
"TimerStopwatch",
"User",
"UserData",
"UserSettings",
"UserStats",
"UserSubscription",
"VocabTable"
],
"modules": [
"Application",
"Components",
"Framework"
],
"allModules": [
{
"displayName": "Application",
"name": "Application"
},
{
"displayName": "Components",
"name": "Components"
},
{
"displayName": "Framework",
"name": "Framework"
}
]
} };
}); |
"use strict"
var Immutable = require('immutable');
var EventEmitter = require('events').EventEmitter;
var assign = require("object-assign");
var { Map, List, OrderedMap } = Immutable;
var CHANGE_EVENT = "CHANGE";
var JSONDispatcher = require('../dispatcher/JSONDispatcher')
var { ActionTypes } = require('../constants/JSONConstants')
var JSONUtils = require("../utils/JSONUtils")
var JSONSearch = require("../utils/JSONSearch")
var _JSONState = { loading: true, activeBtn: "std", searchType: "std", searchOptions: {} },
_curIdx = 0,
_curSearchIdx = -1,
_data = [],
_searchData = [],
_searchArray;
function getCurrentData(){
return _data[_curIdx]
}
function getCurrentSearchData(opts){
return _searchData[_curSearchIdx]
}
function updateCurrentData(nextData, opts){
opts = opts || {};
if(opts.type != "search"){
if(_curIdx + 1 === _data.length)
_data.push(nextData);
else{
_data = _data.slice(0, _curIdx + 1);
_data.push(nextData);
}
_curIdx++;
}
else{
if(_curSearchIdx + 1 === _data.length)
_searchData.push(nextData);
else{
_searchData = _searchData.slice(0, _curSearchIdx + 1);
_searchData.push(nextData);
}
_curSearchIdx++;
}
}
function resetSearchData(){
_searchData = [];
_curSearchIdx = -1;
_JSONState.searchParentPath = [];
}
function _runSearch(){
var regexpOpts = _JSONState.searchOptions.caseSensitive ? "" : "i";
if(_JSONState.searchType == "path"){
var results = JSONSearch.runSearch(
getCurrentData(),
_JSONState.searchTerm,
_JSONState.searchType,
_searchArray
);
_JSONState.searching = true;
updateCurrentData(results.searchData, { type: "search" });
_JSONState.searchSuggestions = results.searchSuggestions;
_JSONState.searchParentPath = results.searchParentPath;
}
else if(_JSONState.searchType == "std"){
_JSONState.searchRegExp = new RegExp("(" + JSONUtils.escapeForRegExp(_JSONState.searchTerm) + ")", regexpOpts);
}
else if(_JSONState.searchType == "regexp"){
try{
_JSONState.searchRegExp = new RegExp("(" + _JSONState.searchTerm + ")", regexpOpts);
_JSONState.searchRegExpError = false;
}
catch(e){
_JSONState.searchRegExpError = true;
}
}
}
function _updateValue(path, value){
if(_JSONState.searching && _JSONState.searchType == "path"){
updateCurrentData(getCurrentSearchData().setIn(path, value), { type: "search" })
updateCurrentData(getCurrentData().setIn(_JSONState.searchParentPath.concat(path), value))
}
else
updateCurrentData(getCurrentData().setIn(path, value))
}
function _updateKV(data, path, prevKey, newKey, value, opts){
opts = opts || {}
var curDataParentNode = data.getIn(path)
curDataParentNode = curDataParentNode.set(newKey, value)
curDataParentNode = curDataParentNode.remove(prevKey, value)
updateCurrentData(data.setIn(path, curDataParentNode), opts)
}
function updateKeyValue(path, prevKey, newKey, value){
_updateKV(getCurrentData(), path, prevKey, newKey, value)
if(_JSONState.searching && _JSONState.searchType == "path")
_updateKV(getCurrentSearchData(), path, prevKey, newKey, value, { type: "search" })
}
var JSONStore = assign({}, EventEmitter.prototype, {
initialize: function (data) {
if(Map.isMap(data) || List.isList(data))
_data.push(data)
else
_data.push(Immutable.fromJS(data))
//JSONUtils.buildSearchData(data);
_JSONState.loading = false;
JSONStore.emitChange();
},
getData: function(){
return _JSONState.searching && _JSONState.searchType == "path" ? getCurrentSearchData() : getCurrentData();
},
getJS: function(){
return getCurrentData().toJS()
},
getJSON: function(){
return getCurrentData().toJSON()
},
getState: function () {
return _JSONState;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
});
var JSONDispatcherToken = JSONDispatcher.register(function (action) {
switch(action.actionType){
case ActionTypes.CREATE_NEW_VALUE:
var path = action.path.split(".").filter(p => p.length > 0).concat(action.key),
value = typeof action.value == "object" ?
Immutable.fromJS(action.value) :
action.value;
if(_JSONState.searching && _JSONState.searchType == "path"){
updateCurrentData(getCurrentSearchData().setIn(path, value), { type: "search" })
updateCurrentData(getCurrentData().setIn(_JSONState.searchParentPath.concat(path), value))
}
else{
updateCurrentData(getCurrentData().setIn(path, value))
}
JSONStore.emitChange();
break;
case ActionTypes.EDIT_VALUE:
JSONStore.emitChange();
break;
case ActionTypes.END_BULK_EDIT:
var path = JSONUtils.getFullPath(action.path),
targetObj = getCurrentData().getIn(path).toJS(),
value;
if(Array.isArray(action.value)){
path.push(action.key);
value = Immutable.fromJS(action.value);
}
else{
assign(targetObj, action.value);
// var keys = Object.keys(targetObj),
// updateKeys = Object.keys(action.value),
// orderedKeys = [],
// combined = assign({}, targetObj, action.value)
// for(var i = 0; i < keys.length; i++){
// if(keys[i] == action.key){
// for(var j = 0; j < updateKeys.length; j++){
// orderedKeys.push(updateKeys[j])
// }
// }
// else
// orderedKeys.push(keys[i])
// }
value = Immutable.fromJS(targetObj);//orderedKeys.reduce((om, key) => om.set(key, Immutable.fromJS(combined[key])), new OrderedMap())
}
updateCurrentData(getCurrentData().setIn(path, value))
//_updateValue(path, Immutable.fromJS(action.value));
JSONStore.emitChange();
break;
case ActionTypes.END_KEY_EDIT:
var curData = getCurrentData(),
value = curData.getIn(action.path.split(".")),
parentKeyPath = JSONUtils.getParentKeyPath(action.path);
updateKeyValue(parentKeyPath, action.prevKey, action.newKey, value)
JSONStore.emitChange();
break;
case ActionTypes.END_EDIT:
var path = JSONUtils.getFullPath(action.path),
value = Immutable.fromJS(action.value);
_updateValue(path, value);
JSONStore.emitChange();
break;
case ActionTypes.REDO:
if(_curIdx + 1 < _data.length)
_curIdx++;
if(_JSONState.searching && _JSONState.searchType == "path"){
if(_curSearchIdx + 1 < _searchData.length)
_curSearchIdx++;
}
JSONStore.emitChange();
break;
case ActionTypes.SEARCH_DATA_BUILT:
_JSONState.canSearch = true;
_searchArray = action.searchArray;
JSONStore.emitChange();
break;
case ActionTypes.SET_SEARCH_OPTION:
_JSONState.searchOptions[action.option] = !_JSONState.searchOptions[action.option];
if(_JSONState.searchTerm.length)
_runSearch();
JSONStore.emitChange();
break;
case ActionTypes.SET_SEARCH_TYPE:
_JSONState.searchType = action.type;
JSONStore.emitChange();
break;
case ActionTypes.UNDO:
if(_curIdx > 0)
_curIdx--;
if(_JSONState.searching && _JSONState.searchType == "path"){
if(_curSearchIdx > 0)
_curSearchIdx--;
}
JSONStore.emitChange();
break;
case ActionTypes.UPDATE_SEARCHTERM:
_JSONState.searchTerm = action.searchTerm;
if(_JSONState.searchTerm.length){
_runSearch();
}
else{
_JSONState.searchRegExp = null;
_JSONState.searchTerm = "";
_JSONState.searching = false;
_JSONState.searchSuggestions = [];
resetSearchData();
}
JSONStore.emitChange();
break;
default:
break;
}
});
module.exports = JSONStore;
|
angular.module('angular.shared.endpoind.factory',[])
.constant('API_ENDPOINT', 'http://45.55.153.158/api')
.factory('ApiEndpoint', ['API_ENDPOINT',
function (API_ENDPOINT) {
return {
Authenticate: function () {
return API_ENDPOINT + '/auth/authorize';
},
GetProfile: function () {
return API_ENDPOINT + '/profile';
},
RefreshToken: function () {
return API_ENDPOINT + '/auth/refresh';
},
};
}]
);
|
function solve(args) {
var len = args.length;
counter = 1;
maxSequince = 0;
for (var i = 0; i < len - 1; i += 1) {
if (+args[i] < +args[i + 1]) {
counter++;
} else {
if (maxSequince < counter) {
maxSequince = counter;
}
counter = 1;
}
}
if (maxSequince < counter) {
maxSequince = counter;
}
return maxSequince;
}
//solve(['10', '2', '1', '1', '2', '3', '3', '2', '2', '2', '1']); |
import mongoose from 'mongoose';
const callSchema = mongoose.Schema({
ticket: {
type: Number
},
call_time: {
type: Date
},
analyst: {
type: Schema.Types.ObjectId,
ref: 'User'
}
call_made: {
type: Boolean,
required: true
},
other_party: {
type: String,
required: true
},
notes: {
type: String,
required: true
},
acknowledged: {
type: Boolean,
default: false
},
created_at: {
type: Boolean,
default: Date.now
},
updated_at: {
type: Date
}
});
const Call = mongoose.model('Call', callSchema);
export default Call; |
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
var robert_and_kims_weather_app = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('robert_and_kims_weather_app', () => robert_and_kims_weather_app);
|
// eslint-disable-next-line
'use strict'
const Libp2p = require('libp2p')
const Websockets = require('libp2p-websockets')
const WebSocketStar = require('libp2p-websocket-star')
const WebRTCStar = require('libp2p-webrtc-star')
const MPLEX = require('libp2p-mplex')
const { NOISE } = require('@chainsafe/libp2p-noise')
const KadDHT = require('libp2p-kad-dht')
const DelegatedPeerRouter = require('libp2p-delegated-peer-routing')
const DelegatedContentRouter = require('libp2p-delegated-content-routing')
export default function Libp2pBundle ({peerInfo, peerBook}) {
const wrtcstar = new WebRTCStar({id: peerInfo.id})
const wsstar = new WebSocketStar({id: peerInfo.id})
const delegatedApiOptions = {
host: '0.0.0.0',
protocol: 'http',
port: '8080'
}
return new Libp2p({
peerInfo,
peerBook,
// Lets limit the connection managers peers and have it check peer health less frequently
connectionManager: {
maxPeers: 10,
pollInterval: 5000
},
modules: {
contentRouting: [
new DelegatedContentRouter(peerInfo.id, delegatedApiOptions)
],
peerRouting: [
new DelegatedPeerRouter(delegatedApiOptions)
],
peerDiscovery: [
wrtcstar.discovery,
wsstar.discovery
],
transport: [
wrtcstar,
wsstar,
Websockets
],
streamMuxer: [
MPLEX
],
connEncryption: [
NOISE
],
dht: KadDHT
},
config: {
peerDiscovery: {
autoDial: false,
webrtcStar: {
enabled: false
},
websocketStar: {
enabled: false
}
},
dht: {
enabled: false
},
relay: {
enabled: true,
hop: {
enabled: false
}
}
}
})
}
|
'use strict';
//noinspection JSUnusedLocalSymbols
const { indent } = require('../utils');
const qs = require('querystring');
class GithubApi {
constructor(auth) {
this.rp = require('request-promise-native')
.defaults({
gzip : true,
jar : true,
auth : auth,
json : true,
resolveWithFullResponse: true,
headers : {
'Accept' : 'application/vnd.github.v3+json',
'User-Agent': 'cpriest/hain-plugin-psl',
}
});
}
async get(query) {
if(query.substr(0, 1) === '/')
query = 'https://api.github.com' + query;
let res = await this.rp(query);
let nextPageURL = (res.headers.link || '')
.split(/,\s*/)
.reduce((acc, link) => {
if(link.indexOf('rel="next"') >= 0)
return link.match(/<(.+?)>/)[1];
return acc;
}, '');
if(nextPageURL) {
return (/** @type {object[]} */ res.body.items || /** @type {string} */ res.body)
.concat(await this.get(nextPageURL));
}
return res.body.items || res.body;
}
}
//noinspection JSUnusedLocalSymbols
module.exports = (() => {
let { MatchlistProvider } = require('./Providers');
/**
* @property {QueryableProviderDefinition} def
*/
class GithubProvider extends MatchlistProvider {
/**
* Builds the matchlist according to what's queryable by the Github API
*
* @returns {Promise<object[]>}
*/
BuildMatchlist() {
let API = new GithubApi(this.def.auth);
return this.ResolveQueries(API);
}
/**
* @param API {GithubApi}
*
* @returns {Promise<object[]>}
*/
async ResolveQueries(API) {
try {
return []
.concat(
...await Promise.all(
this.def.queries
.map(query =>
API.get(`${this.def.uri}?per_page=100&q=` + qs.escape(query))
)
)
);
} catch(e) {
psl.log('Failed to fetch results from Github:', e.stack || e);
psl.toast.enqueue('Failed to fetch results from Github, see debug log.');
}
return [];
}
}
return GithubProvider;
})();
|
let m = new Map();
Math.sign(-1);
|
const lowercaseWords = /(?:^\w|[A-Z]|\b\w)/g
const wordSeparators = /[\s-:]+/g
const camelCase = str => str
.trim()
.replace(lowercaseWords, (letter, index) => index === 0 ? letter.toLowerCase() : letter.toUpperCase())
.replace(wordSeparators, '')
const pascalCase = str => {
if (!str) return str
const camel = camelCase(str)
return camel[0].toUpperCase() + camel.slice(1)
}
module.exports = {
camelCase,
pascalCase
}
|
import React from 'react';
import { Link } from '@curi/react';
function ToolsList(props) {
return (
<div>
<h1>Tools</h1>
<p>
Below are some tools that may assist you in encrypting and decrypting
messages. What they don't do is encrypt and decrypt messages for you.
</p>
<ul>
<li>
<Link to='Shift Tools'>Shift Cipher Tools</Link>
</li>
<li>
<Link to='Vigenere Tools'>Vigenère Cipher Tools</Link>
</li>
</ul>
</div>
);
}
export default ToolsList;
|
/** All server api will define in here. */
define('api', ['adminApp', 'config'], function (adminApp, config) {
adminApp
.factory('adminHttp', ['$http', function ($http){
$http.defaults.useXDomain = true;
var serverUrl = config.serverHost + config.namespace;
// var serverUrl = 'http://www.duastone.com/solutions';
return function (config){
if(config.method.toUpperCase() == 'POST'
|| config.method.toUpperCase() == 'PUT'
|| config.method.toUpperCase() == 'DELETE') {
return $http({
url: serverUrl + config.url,
method: config.method.toUpperCase(),
headers: {
'Content-Type': 'application/json'
},
// transformRequest : function(data){
// if (data === undefined) {
// return data;
// }
// return $.param(data);
// },
data: config.data
});
} else if (config.method.toUpperCase() == 'GET') {
return $http({
url: serverUrl + config.url,
method: 'GET',
data: config.data
});
}
};
}])
.service('api', ['adminHttp', function (adminHttp) {
var o = function(options, success, error) {
adminHttp(options)
.success(function(res){
res && success && success(res);
})
.error(function(err) {
err && error && error(err);
});
};
/** Get count for dashboard. */
this.count = function(success, error) {
adminHttp({method: 'GET', url: '/dashboard/count'})
.success(function(count){
count && success && success(count);
})
.error(function(err) {
err && error && error(err);
});
};
this.hotnews = function(success, error) {
adminHttp({method: 'GET', url: '/hotnews'})
.success(function(hotnews) {
hotnews && success && success(hotnews);
})
.error(function(err) {
err && error && error(err);
});
};
this.lastTenCpuMonitor = function(success, error) {
adminHttp({method: 'GET', url: '/cms'})
.success(function(hotnews) {
hotnews && success && success(hotnews);
})
.error(function(err) {
err && error && error(err);
});
};
this.missionList = function(success, error) {
adminHttp({method: 'GET', url: '/mission'})
.success(function(missions) {
missions && success && success(missions);
})
.error(function(err) {
err && error && error(err);
});
};
this.missionAdd = function(mission, success, error) {
adminHttp({method: 'POST', url: '/mission', data: mission})
.success(function(missions) {
missions && success && success(missions);
})
.error(function(err) {
err && error && error(err);
});
};
this.missionUpdate = function(mission, success, error) {
adminHttp({method: 'PUT', url: '/mission', data: mission})
.success(function(missions) {
missions && success && success(missions);
})
.error(function(err) {
err && error && error(err);
});
};
this.missionDelete = function(id, success, error) {
adminHttp({method: 'DELETE', url: '/mission', data: {id: id}})
.success(function(res) {
res && success && success(res);
})
.error(function(err) {
err && error && error(err);
});
};
this.label = {
get: function(categoryId, success, error) {
o({method: 'GET', url: '/label?categoryId=' + categoryId}, success, error);
},
post: function(label, success, error) {
o({method: 'POST', url: '/label', data: label}, success, error);
},
delete: function(id, success, error) {
o({method: 'DELETE', url: '/label', data: {id: id}}, success, error);
}
};
this.category = {
get: function(success, error) {
o({method: 'GET', url: '/category'}, success, error);
},
post: function(category, success, error) {
o({method: 'POST', url: '/category', data: category}, success, error);
},
delete: function(id, success, error) {
o({method: 'DELETE', url: '/category', data: {id: id}}, success, error);
}
};
// Doc System interface api.
this.doc = {
getSubject: function(success, error) {
o({method: 'GET', url: '/doc/subject'}, success, error);
},
getSubjectById: function(subjectId, success, error) {
o({method: 'GET', url: '/doc/subject/id?subjectId=' + subjectId}, success, error);
},
postSubject: function(subject, success, error) {
o({method: 'POST', url: '/doc/subject', data: subject}, success, error);
},
deleteSubject: function(subjectId, success, error) {
o({method: 'DELETE', url: '/doc/subject', data: {id: subjectId}}, success, error);
},
getTitle: function(subjectId, success, error) {
o({method: 'GET', url: '/doc/title?subjectId=' + subjectId}, success, error);
},
postTitle: function(title, success, error) {
o({method: 'POST', url: '/doc/title', data: title}, success, error);
},
deleteTitle: function(titleId, success, error) {
o({method: 'DELETE', url: '/doc/title', data: {id: titleId}}, success, error);
},
getContent: function(titleId, success, error) {
o({method: 'GET', url: '/doc/content?titleId=' + titleId}, success, error);
},
postContent: function(content, success, error) {
o({method: 'POST', url: '/doc/content', data: content}, success, error);
},
putContent: function(content, success, error) {
o({method: 'PUT', url: '/doc/content', data: content}, success, error);
},
};
}]);
});
|
import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Album from './components/album';
import Albums from './components/albums';
import Artist from './components/artist';
import Artists from './components/artists';
import Navigation from './components/navigation';
import NotFound from './components/not-found';
import Overview from './components/overview';
import Plays from './components/plays';
import Track from './components/track';
import Tracks from './components/tracks';
import './app.css';
class App extends React.Component {
render() {
return (
<div>
<BrowserRouter>
<div>
<Route path="/:path" component={Navigation} />
<div className="app-content">
<Switch>
<Route exact path="/" component={Overview} />
<Route exact path="/artists" component={Artists} />
<Route exact path="/artists/:id" component={Artist} />
<Route exact path="/albums" component={Albums} />
<Route exact path="/albums/:id" component={Album} />
<Route exact path="/tracks" component={Tracks} />
<Route exact path="/tracks/:id" component={Track} />
<Route exact path="/plays" component={Plays} />
<Route component={NotFound}/>
</Switch>
</div>
</div>
</BrowserRouter>
<div className="app-footer">
Development and support — Ross Nomann, 2017
</div>
</div>
);
}
}
export default App;
|
'use strict'
var dirname = require('path').dirname,
exec = require('child_process').exec,
test = require('tap')
require('../')
if (process.env.TEST_STILL_NOT_A_FUNCTION)
nonExistingFunction()
else {
test.plan(2)
var args = [ 'cover', __filename, '--report', 'none', '--print', 'none', '--include-pid' ].join(' ')
exec('./node_modules/.bin/istanbul ' + args, {
env: {
PATH: process.env.PATH,
TEST_STILL_NOT_A_FUNCTION: 1
}
}, onexit)
}
function onexit(err, stdout, stderr) {
test.type(err, Error, 'process should fail')
test.match(stderr, /not defined/i, 'error message should not be overridden')
}
|
var DEFAULT_WIDTH = 550;
module.exports = {
re: [
/^https?:\/\/(www|m)\.facebook\.com\/([a-zA-Z0-9\.\-]+)\/?(?:\?f?ref=\w+)?$/i
],
getMeta: function(oembed, urlMatch) {
if (oembed.html) {
var title = oembed.html.match(/>([^<>]+)<\/a><\/blockquote>/i);
title = title ? title[1] : urlMatch[2];
return {
title: title
};
}
},
getLink: function(oembed, meta, options) {
// skip user profiles - they can not be embedded
if ((meta.al && meta.al.android && meta.al.android.url && /\/profile\//.test(meta.al.android.url)) || !/blockquote/.test(oembed.html)) {
return;
}
return {
type: CONFIG.T.text_html,
rel: [CONFIG.R.app, CONFIG.R.ssl, CONFIG.R.html5],
html: oembed.html,
"max-width": oembed.width
};
},
tests: [
"https://www.facebook.com/hlaskyjanalasaka?fref=nf",
{
noFeeds: true
}
]
}; |
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ModuleBase = require("../Base");
var Collection = require('./Collection');
var FileSystem = require('./FileSystem');
var Promise = require('bluebird');
var mongodb = require('mongodb');
var extend = require('extend');
// Counter
var COLLECTION_COUNTER_DEFAULT = "_private.counter";
/**
* Mongo class
*/
var Mongo = function (_ModuleBase) {
_inherits(Mongo, _ModuleBase);
function Mongo() {
_classCallCheck(this, Mongo);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Mongo).apply(this, arguments));
}
_createClass(Mongo, [{
key: "moduleSetup",
/**
* Construct the Mongo extension
*/
value: function moduleSetup() {
var self = this;
// Connect to the mongo db
var connect = Promise.promisify(mongodb.MongoClient.connect, { context: mongodb.MongoClient });
return connect(this.options.url, { promiseLibrary: Promise }).then(function (db) {
self._db = db;
});
}
/**
* Close the db
*/
}, {
key: "moduleClose",
value: function moduleClose() {
if (!this._db) return;
var db = this._db;
this._db = null;
return db.close(true);
}
/**
* Make obejctID
* @param {*} The ID to construct the object with
*/
}, {
key: "makeObjectID",
value: function makeObjectID(id) {
return new mongodb.ObjectID(id);
}
/**
* Get a given collection
*/
}, {
key: "collection",
value: function collection(name) {
return new Collection(name, this._db.collection(name));
}
/**
* Convert obejct to query
* @param {object} obj The object to convert to query object
* @param {string} baseName the name of the base for the query
* @param {boolean|number} depth If the conversion must be recursive
* @param {object?} output The object to be outputed and returned
* @return The output object or a new one if none is provided
*/
}, {
key: "toQuery",
value: function toQuery(obj, baseName, depth, output) {
output = output || {};
baseName = baseName ? baseName + '.' : '';
if (typeof depth === 'undefined') depth = true;
for (var key in obj) {
var value = obj[key];
var keyName = baseName + key;
if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === 'object') {
if (depth === true) {
this.toQuery(value, keyName, true, output);
continue;
} else if (typeof depth === 'number' && depth > 0) {
this.toQuery(value, keyName, depth - 1, output);
continue;
}
}
output[keyName] = value;
}
return output;
}
/**
* options
*/
}, {
key: "fs",
value: function fs(options) {
return new FileSystem(this._db, options);
}
/**
* Get next sequencial data form name
*/
}, {
key: "getNextSequence",
value: function getNextSequence(name) {
var counter = this.options.counter || COLLECTION_COUNTER_DEFAULT;
return this.collection(counter).findOneAndUpdate({ _id: name }, { $inc: { value: 1 } }, { upsert: true }).then(function (item) {
if (!item || !item.value) return 0;
return item.value.value | 0;
});
}
}]);
return Mongo;
}(ModuleBase);
;
// Exports the Mongo class
module.exports = Mongo; |
// Test for writing a SML-File
var sml = require('../index');
var smlFile = new sml.SmlFile();
//smlFile.setType("SML");
//smlFile.setStatus(0x01);
//smlFile.setVersion(1);
var smlMessage1 = new sml.SmlMessage();
smlMessage1.setMessageTag(sml.Constants.PUBLIC_OPEN_RESPONSE);
smlMessage1.setTransactionId("01234567890abc");
smlMessage1.setGroupNo(0);
smlMessage1.setAbortOnError(0);
smlMessage1.setCRC16(0xFFFF);
// EndOfSmlMsg
//var endOfSmlMsg = new EndOfSmlMsg();
//smlMessage1.setEndOfSmlMsg(endOfSmlMsg);
// Message Body
var smlPublicOpenResponse = new sml.SmlPublicOpenResponse();
//smlPublicOpenResponse.setCodepage("ISO9660");
smlPublicOpenResponse.setClientId("0500153b022e39");
smlPublicOpenResponse.setReqFileId("510158881");
smlPublicOpenResponse.setServerId("1ba5590af1a");
smlTime = new sml.SmlTime();
smlTime.setTimestamp(4294967295);
smlPublicOpenResponse.setRefTime(smlTime);
//smlPublicOpenResponse.setSmlVersion();
smlMessage1.setMessageBody(smlPublicOpenResponse);
smlFile.addMessage(smlMessage1);
var smlMessage2 = new sml.SmlMessage();
smlMessage2.setTransactionId("510158883");
smlMessage2.setMessageTag(sml.Constants.GET_PROFILE_LIST_RESPONSE);
var smlGetProfileListResponse = new sml.SmlGetProfileListResponse();
smlGetProfileListResponse.setServerId("1ba5590af1aa");
var actTime = new sml.SmlTime();
actTime.setTimestamp(4294967295);
smlGetProfileListResponse.setActTime(actTime);
smlGetProfileListResponse.setRegPeriod(0);
var parameterTreePath = new sml.SmlTreePath();
parameterTreePath.addPathEntry("rgrdgdfgf");
smlGetProfileListResponse.setParameterTreePath(parameterTreePath);
var valTime = new sml.SmlTime();
valTime.setSecIndex(4294967295);
smlGetProfileListResponse.setValTime(valTime);
smlGetProfileListResponse.setStatus(386);
var periodList = new sml.SmlPeriodList();
var periodListEntry = new sml.SmlPeriodListEntry();
periodListEntry.setObjName("0100010800ff");
periodListEntry.setUnit(30);
periodListEntry.setScaler(-1);
periodListEntry.setValue(1252);
periodListEntry.setValueType(sml.Constants.INT16);
//periodListEntry.setValueSignature();
periodList.addListEntry(periodListEntry);
var periodListEntry = new sml.SmlPeriodListEntry();
periodListEntry.setObjName("0100010801ff");
periodListEntry.setUnit(30);
periodListEntry.setScaler(-1);
periodListEntry.setValue(1252);
periodListEntry.setValueType(sml.Constants.INT16);
//periodListEntry.setValueSignature();
periodList.addListEntry(periodListEntry);
var periodListEntry = new sml.SmlPeriodListEntry();
periodListEntry.setObjName("0100100700ff");
periodListEntry.setUnit(30);
periodListEntry.setScaler(-1);
periodListEntry.setValue(523);
periodListEntry.setValueType(sml.Constants.INT16);
//periodListEntry.setValueSignature();
periodList.addListEntry(periodListEntry);
var periodListEntry = new sml.SmlPeriodListEntry();
periodListEntry.setObjName("0100010802ff");
periodListEntry.setUnit(30);
periodListEntry.setScaler(-1);
periodListEntry.setValue(986);
periodListEntry.setValueType(sml.Constants.INT16);
//periodListEntry.setValueSignature();
periodList.addListEntry(periodListEntry);
smlGetProfileListResponse.setPeriodList(periodList);
//smlGetProfileListResponse.setRawdata();
//smlGetProfileListResponse.setPeriodSignature();
smlMessage2.setMessageBody(smlGetProfileListResponse);
smlFile.addMessage(smlMessage2);
var smlMessage3 = new sml.SmlMessage();
smlMessage3.setTransactionId("510158884");
smlMessage3.setMessageTag(sml.Constants.PUBLIC_CLOSE_RESPONSE);
var smlPublicCloseResponse = new sml.SmlPublicCloseResponse();
//smlPublicCloseResponse.setGlobalSignature();
smlMessage3.setMessageBody(smlPublicCloseResponse);
smlFile.addMessage(smlMessage3);
var buffer = smlFile.write()
console.log(smlFile.toString());
console.log(buffer.toString(16));
|
(function ($) {
Drupal.behaviors.killToolbarAutoSidebar = {
attach: function (context) {
window.matchMedia('(min-width: 975px)').addListener( function(event) {
event.matches ? $('#toolbar-item-administration', context).click() : $('.toolbar-item.is-active', context).click();
});
}
};
})(jQuery);
|
var structx265_1_1SPS =
[
[ "bUseAMP", "structx265_1_1SPS.html#a713e18a360613ebe57ff11e97d9bd43e", null ],
[ "bUseSAO", "structx265_1_1SPS.html#a840125b92a05d8707921b0d2f3c3b937", null ],
[ "bUseStrongIntraSmoothing", "structx265_1_1SPS.html#a1daed1579d50ed1572594c5ebe1e83b5", null ],
[ "chromaFormatIdc", "structx265_1_1SPS.html#af007a9860a3112dc49f2cb53c1cd17df", null ],
[ "conformanceWindow", "structx265_1_1SPS.html#a8f90fc75d3338fccf4686ac586575ef2", null ],
[ "log2DiffMaxMinCodingBlockSize", "structx265_1_1SPS.html#a4c8dd3a1116dc54e6456e1e55bd1c08b", null ],
[ "log2MinCodingBlockSize", "structx265_1_1SPS.html#a8aa8169dcb9b84f5732b72e31c76cd8e", null ],
[ "maxAMPDepth", "structx265_1_1SPS.html#ae1271e61bfa9254a774098d41f3fb345", null ],
[ "maxDecPicBuffering", "structx265_1_1SPS.html#a8d3fdd5945df7ff54dcc9c69d68684ee", null ],
[ "numCuInHeight", "structx265_1_1SPS.html#a992cd8f8de9308453218891079540e89", null ],
[ "numCuInWidth", "structx265_1_1SPS.html#a58f693e6dbe3362a165df9488408c0ee", null ],
[ "numCUsInFrame", "structx265_1_1SPS.html#aacd0f094fbde905ab86f44b34c8311f2", null ],
[ "numPartInCUSize", "structx265_1_1SPS.html#a6b8ac85b9c403cf3cc03cbb0a1825142", null ],
[ "numPartitions", "structx265_1_1SPS.html#a1a6a4e6201b0ee6dfa91a6bb209ab0c8", null ],
[ "numReorderPics", "structx265_1_1SPS.html#a74de3196941e594706942b4f5dc512d1", null ],
[ "picHeightInLumaSamples", "structx265_1_1SPS.html#a9e026e65a04183bff5a6a08bb3d9530e", null ],
[ "picWidthInLumaSamples", "structx265_1_1SPS.html#abf620f06fde249410c014f5bcaf5b524", null ],
[ "quadtreeTULog2MaxSize", "structx265_1_1SPS.html#ad622f7229fc55e7a1ed399865f0451c3", null ],
[ "quadtreeTULog2MinSize", "structx265_1_1SPS.html#a3acb0b30ef3118d74dae0b8db5bc7c66", null ],
[ "quadtreeTUMaxDepthInter", "structx265_1_1SPS.html#a98aa5143a54411b4dcc6e7a39f8433f2", null ],
[ "quadtreeTUMaxDepthIntra", "structx265_1_1SPS.html#a259d25823766a19f0c1cf8b672808ec9", null ],
[ "vuiParameters", "structx265_1_1SPS.html#a50a1aca292b4fdfa768a8ceb135f778e", null ]
]; |
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Score;
return {
setters:[],
execute: function() {
Score = (function () {
function Score(player, points) {
this.player = player;
this.points = points;
this.when = new Date();
}
return Score;
}());
exports_1("Score", Score);
}
}
});
//# sourceMappingURL=score.js.map |
require('commons');
require('lessDir/base/special.less');
define(['script/index/load_init'], function(LOAD) {})
|
"use strict";
var Hapi = require('hapi');
var packageHandler = require('src/handlers/package');
var packageValidate = require('src/validate/package');
module.exports = function() {
return [
{
method: 'POST',
path: '/package/upload',
handler: packageHandler.upload,
config: {
payload: {
output: 'stream',
parse: false,
allow: 'multipart/form-data'
}
}
}
];
}(); |
var configLoader = require('../lib/config-loader')
, sh = require('shelljs')
, path = require('path')
, fs = require('fs')
, db = require('../lib/db').create({name: 'test-db', host: 'localhost', port: 27017})
, Server = require('../lib/server')
, Collection = require('../lib/resources/collection')
, Files = require('../lib/resources/files')
, ClientLib = require('../lib/resources/client-lib')
, InternalResources = require('../lib/resources/internal-resources')
, Dashboard = require('../lib/resources/dashboard')
, sinon = require('sinon')
, basepath = './test/support/proj';
describe('config-loader', function() {
beforeEach(function() {
if (fs.existsSync(basepath)) {
sh.rm('-rf', basepath);
}
sh.mkdir('-p', basepath);
this.server = new Server();
this.sinon = sinon.sandbox.create();
});
afterEach(function() {
this.sinon.restore();
});
describe('.loadConfig()', function() {
it('should load resources', function(done) {
this.timeout(10000);
sh.mkdir('-p', path.join(basepath, 'resources/foo'));
sh.mkdir('-p', path.join(basepath, 'resources/bar'));
JSON.stringify({type: "Collection", val: 1}).to(path.join(basepath, 'resources/foo/config.json'));
JSON.stringify({type: "Collection", val: 2}).to(path.join(basepath, 'resources/bar/config.json'));
configLoader.loadConfig(basepath, this.server, function(err, resources) {
if (err) return done(err);
expect(resources).to.have.length(6);
expect(resources.filter(function(r) { return r.name == 'foo';})).to.have.length(1);
expect(resources.filter(function(r) { return r.name == 'bar';})).to.have.length(1);
done();
});
});
it('should return a set of resource instances', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources/foo'));
JSON.stringify({type: "Collection", properties: {}}).to(path.join(basepath, 'resources/foo/config.json'));
configLoader.loadConfig(basepath, {db: db}, function(err, resourceList) {
expect(resourceList).to.have.length(5);
expect(resourceList[0].config.properties).to.be.a('object');
expect(resourceList[0] instanceof Collection).to.equal(true);
done(err);
});
});
it('should add internal resources', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources'));
configLoader.loadConfig(basepath, {}, function(err, resourceList) {
if (err) return done(err);
expect(resourceList).to.have.length(4);
expect(resourceList[0] instanceof Files).to.equal(true);
expect(resourceList[1] instanceof InternalResources).to.equal(true);
expect(resourceList[2] instanceof ClientLib).to.equal(true);
expect(resourceList[3] instanceof Dashboard).to.equal(true);
done(err);
});
});
it('should add internal resources but hide_dpdjs', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources'));
server = { options: { hide_dpdjs: true } }
configLoader.loadConfig( basepath, server, function(err, resourceList) {
if (err) return done(err);
expect(resourceList).to.have.length(2);
expect(resourceList[0] instanceof Files).to.equal(true);
expect(resourceList[1] instanceof InternalResources).to.equal(true);
done(err);
});
});
it('should add internal resources but hide_dashboard', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources'));
server = { options: { hide_dashboard: true } }
configLoader.loadConfig( basepath, server, function(err, resourceList) {
if (err) return done(err);
expect(resourceList).to.have.length(3);
expect(resourceList[0] instanceof Files).to.equal(true);
expect(resourceList[1] instanceof InternalResources).to.equal(true);
expect(resourceList[2] instanceof ClientLib).to.equal(true);
done(err);
});
});
it('should not attempt to load files', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources'));
('').to(path.join(basepath, 'resources/.DS_STORE'));
configLoader.loadConfig(basepath, {}, function(err, resourceList) {
if (err) return done(err);
done();
});
});
it('should throw a sane error when looking for config.json', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources/foo'));
configLoader.loadConfig(basepath, {}, function(err, resourceList) {
expect(err).to.exist;
expect(err.message).to.equal("Expected file: " + path.join('resources', 'foo', 'config.json'));
done();
});
});
it('should use public_dir option if available', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources'));
configLoader.loadConfig(basepath, {}, function(err, resourceList) {
if (err) return done(err);
expect(resourceList[0].config.public).to.equal('./public');
});
var opts = {};
opts.options = {};
opts.options.public_dir = 'test';
configLoader.loadConfig(basepath, opts, function(err, resourceList) {
if (err) return done(err);
expect(resourceList[0].config.public).to.equal('test');
});
done();
});
it('should use env options path if exists', function(done) {
sh.mkdir('-p', path.join(basepath, 'resources'));
var public_dir = basepath + '/test';
var opts = {};
opts.options = {};
opts.options.public_dir = public_dir;
opts.options.env = 'dev';
sh.mkdir('-p', public_dir + '-dev');
configLoader.loadConfig(basepath, opts, function(err, resourceList) {
if (err) return done(err);
expect(resourceList[0].config.public).to.equal(public_dir + '-dev');
done();
});
});
it('should read directories only once on multiple server.route requests', function (done) {
sh.mkdir('-p', path.join(basepath, 'resources'));
var server = new Server({ server_dir: basepath });
var callsLeft = 20;
function next() {
if (callsLeft == 0) {
expect(fs.readdir.callCount).to.equal(1);
return done();
};
callsLeft--;
server.route(req, res);
}
var originalLoadConfig = configLoader.loadConfig;
this.sinon.stub(configLoader, 'loadConfig', function (basepath, server, fn) {
originalLoadConfig(basepath, server, function () {
// intercepting this call so that we can call this sequentially
next();
fn.apply(this, arguments);
});
});
var req = { url: 'foo', headers: {} };
var res = { body: 'bar' };
var fs = require('fs');
sinon.spy(fs, 'readdir');
next();
});
});
});
|
/*!
* Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file.
*/
// Need to fork xhr to support environments with full object freezing; namely,
// SalesForce's Aura and Locker environment.
// See https://github.com/naugtur/xhr for license information
// Maintain the original code style of https://github.com/naugtur/xhr since
// we're trying to diverge as little as possible.
/* eslint-disable */
"use strict";
var window = require("global/window")
var isFunction = require("is-function")
var parseHeaders = require("parse-headers")
var xtend = require("xtend")
module.exports = createXHR
createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
options = initParams(uri, options, callback)
options.method = method.toUpperCase()
return _createXHR(options)
}
})
function forEachArray(array, iterator) {
for (var i = 0; i < array.length; i+= 1) {
iterator(array[i])
}
}
function isEmpty(obj){
for(var i in obj){
if(obj.hasOwnProperty(i)) return false
}
return true
}
function initParams(uri, options, callback) {
var params = uri
if (isFunction(options)) {
callback = options
if (typeof uri === "string") {
params = {uri:uri}
}
} else {
params = xtend(options, {uri: uri})
}
params.callback = callback
return params
}
function createXHR(uri, options, callback) {
options = initParams(uri, options, callback)
return _createXHR(options)
}
function _createXHR(options) {
if(typeof options.callback === "undefined"){
throw new Error("callback argument missing")
}
var called = false
var callback = function cbOnce(err, response, body){
if(!called){
called = true
options.callback(err, response, body)
}
}
function readystatechange() {
if (xhr.readyState === 4) {
setTimeout(loadFunc, 0)
}
}
function getBody() {
// Chrome with requestType=blob throws errors arround when even testing access to responseText
var body = undefined
if (xhr.response) {
body = xhr.response
} else {
body = xhr.responseText || getXml(xhr)
}
if (isJson) {
try {
body = JSON.parse(body)
} catch (e) {}
}
return body
}
function errorFunc(evt) {
clearTimeout(timeoutTimer)
if(!(evt instanceof Error)){
evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
}
evt.statusCode = 0
return callback(evt, failureResponse)
}
// will load the data & process the response in a special response object
function loadFunc() {
if (aborted) return
var status
clearTimeout(timeoutTimer)
if(options.useXDR && xhr.status===undefined) {
//IE8 CORS GET successful response doesn't have a status field, but body is fine
status = 200
} else {
status = (xhr.status === 1223 ? 204 : xhr.status)
}
var response = failureResponse
var err = null
if (status !== 0){
response = {
body: getBody(),
statusCode: status,
method: method,
headers: {},
url: uri,
rawRequest: xhr
}
if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
response.headers = parseHeaders(xhr.getAllResponseHeaders())
}
} else {
err = new Error("Internal XMLHttpRequest Error")
}
return callback(err, response, response.body)
}
var xhr = options.xhr || null
if (!xhr) {
if (options.cors || options.useXDR) {
xhr = new createXHR.XDomainRequest()
}else{
xhr = new createXHR.XMLHttpRequest()
}
}
var key
var aborted
var uri = options.uri || options.url
var method = options.method || "GET"
var body = options.body || options.data
var headers = options.headers || {}
var sync = !!options.sync
var isJson = false
var timeoutTimer
var failureResponse = {
body: undefined,
headers: {},
statusCode: 0,
method: method,
url: uri,
rawRequest: xhr
}
if ("json" in options && options.json !== false) {
isJson = true
headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
if (method !== "GET" && method !== "HEAD") {
headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
body = JSON.stringify(options.json === true ? body : options.json)
}
}
xhr.onreadystatechange = readystatechange
xhr.onload = loadFunc
xhr.onerror = errorFunc
// IE9 must have onprogress be set to a unique function.
xhr.onprogress = function () {
// IE must die
}
xhr.onabort = function(){
aborted = true;
}
xhr.ontimeout = errorFunc
xhr.open(method, uri, !sync, options.username, options.password)
//has to be after open
if(!sync) {
xhr.withCredentials = !!options.withCredentials
}
// Cannot set timeout with sync request
// not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
// both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
if (!sync && options.timeout > 0 ) {
timeoutTimer = setTimeout(function(){
if (aborted) return
aborted = true//IE9 may still call readystatechange
xhr.abort("timeout")
var e = new Error("XMLHttpRequest timeout")
e.code = "ETIMEDOUT"
errorFunc(e)
}, options.timeout )
}
if (xhr.setRequestHeader) {
for(key in headers){
if(headers.hasOwnProperty(key)){
xhr.setRequestHeader(key, headers[key])
}
}
} else if (options.headers && !isEmpty(options.headers)) {
throw new Error("Headers cannot be set on an XDomainRequest object")
}
if ("responseType" in options) {
xhr.responseType = options.responseType
}
if ("beforeSend" in options &&
typeof options.beforeSend === "function"
) {
options.beforeSend(xhr)
}
// Microsoft Edge browser sends "undefined" when send is called with undefined value.
// XMLHttpRequest spec says to pass null as body to indicate no body
// See https://github.com/naugtur/xhr/issues/100.
xhr.send(body || null)
return xhr
}
function getXml(xhr) {
if (xhr.responseType === "document") {
return xhr.responseXML
}
var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
if (xhr.responseType === "" && !firefoxBugTakenEffect) {
return xhr.responseXML
}
return null
}
function noop() {}
|
module.exports = (function() {
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Test = Schema({
name:String,
age:Number,
job:Number
}, {
collection: 'test'
});
Test.statics.test = function() {
//this.testWrite();
this.testRead();
};
Test.statics.testWrite = function() {
var mongo = app.mongo;
var db = app.db;
var gridStore = new mongo.GridStore(db, new mongo.ObjectID(), 'w', {root: 'fs'});
gridStore.writeFile('app.js', function(err, fileInfo) {
console.log(err);
console.log(fileInfo._id);
});
};
Test.statics.testRead = function() {
var mongo = app.mongo;
var db = app.db;
var readGrid = new mongo.GridStore(db, '550b71d11d34cd0409a4b70e', 'r');
readGrid.open(function(err, gridStore) {
readGrid.read(function(err, data) {
console.log(data);
app.exit();
});
});
};
return mongoose.model('TestGridFS', Test);
})();
|
export const initialState = {
query: ''
};
const setAutocompleteSearch = (state, { payload }) => ({
...state,
query: payload
});
export default {
setAutocompleteSearch
};
|
import React from 'react';
import PropTypes from 'prop-types';
import Footer from './../../../components/footer/footer';
function ErrorPage({ env, componentInfo, err }) {
const isDevelopment = env === 'development';
if (isDevelopment) {
console.error(err); // eslint-disable-line no-console
console.error(err.stack); // eslint-disable-line no-console
}
return (
<div className="error-page">
<h1>Error Occurred.</h1>
{isDevelopment ? (
<div>
<h2>Error Message: {err.message}</h2>
<h2>Error Stack: {JSON.stringify(err.stack, null, 2)}</h2>
<h2>Component Info: {JSON.stringify(componentInfo, null, 2)}</h2>
</div>
) : (
<p>We\'re sorry please try again later.</p>
)}
<Footer />
</div>
);
}
ErrorPage.propTypes = {
err: PropTypes.shape({}),
componentInfo: PropTypes.shape({}),
env: PropTypes.string.isRequired
};
ErrorPage.defaultProps = {
err: {},
componentInfo: {}
};
export default ErrorPage;
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.15-2-17
description: >
Array.prototype.lastIndexOf applied to Arguments object which
implements its own property get method
includes: [runTestCase.js]
---*/
function testcase() {
var targetObj = function () { };
var func = function (a, b) {
arguments[2] = function () { };
return Array.prototype.lastIndexOf.call(arguments, targetObj) === 1 &&
Array.prototype.lastIndexOf.call(arguments, arguments[2]) === -1;
};
return func(0, targetObj);
}
runTestCase(testcase);
|
import Promise from "bluebird";
import moment from "moment";
export default class Source {
constructor(data) {
this.title = data.title;
this.interval = data.interval || 60;
}
getInterval() {
return this.interval;
}
getStatus() {
return Promise.resolve({
title: this.title,
link: "http://example.com",
status: "success",
messages: [{
name: "Example",
link: "http://example.com",
detailName: "Example",
message: "Example"
}],
progress: {
percent: () => 50,
remaining: () => moment.duration(5, "minutes")
}
});
}
}
Source.type = ""; |
(function($) {
"use strict";
// Smooth scrolling using jQuery easing
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - 48)
}, 1000, "easeInOutExpo");
return false;
}
}
});
// Activate scrollspy to add active class to navbar items on scroll
$('body').scrollspy({
target: '#mainNav',
offset: 54
});
// Closes responsive menu when a link is clicked
$('.navbar-collapse>ul>li>a').click(function() {
$('.navbar-collapse').collapse('hide');
});
// Collapse the navbar when page is scrolled
$(window).scroll(function() {
if ($("#mainNav").offset().top > 100) {
$("#mainNav").addClass("navbar-shrink");
} else {
$("#mainNav").removeClass("navbar-shrink");
}
});
var mcSignup = $('#mc-signup');
var modal = $('#modal');
mcSignup.find('#close span').click(function() {
modal.fadeOut();
mcSignup.animate({
top: '200%',
}, 200, 'linear');
});
$('.mc-signup-btn').click(function() {
modal.fadeIn();
mcSignup.animate({
top: '50%'
}, 200, 'linear');
});
})(jQuery); |
"use strict"
var program = require('commander'),
Q = require('q'),
fs = require('fs'),
Datastore = require('nedb');
var configDb = new Datastore({
filename: 'data/node-catch.config',
autoload: true });
var configFind = Q.denodeify(configDb.find.bind(configDb));
var commandList = ['list','remove','refresh','add'];
configFind({})
.then(function (configs) {
var defaultConfig = {
db: 'data/node-catch.data',
maxCurrency: 4,
storageDirectory: 'podcasts'
};
var config = configs[0] || defaultConfig;
if (configs.length == 0) {
configDb.insert(defaultConfig);
}
var db = new Datastore({
filename: config.db,
autoload: true
});
for (var i = 0; i < commandList.length; i++) {
require('./commands/' + commandList[i] + '.js').configureCommand(program, db, config);
}
fs.readdir(config.storageDirectory, function (err, files) {
if (err) {
fs.mkdir(config.storageDirectory, function (err) {
if (err) {
console.log(err)
process.exit(1);
}
program.parse(process.argv);
});
}
else {
program.parse(process.argv);
}
});
program.version('0.0.1');
})
.catch(function (err) {
console.log(err);
})
|
var expect = require("chai").expect;
var db = require("../index");
var setup = require("./setup");
var conti = require("conti");
var util = require("./util");
var wqueueStateWaitExam = util.WqueueStateWaitExam;
var wqueueStateInExam = util.WqueueStateInExam;
var wqueueStateWaitCashier = util.WqueueStateWaitCashier;
var wqueueStateWaitDrug = util.WqueueStateWaitCashier;
var wqueueStateWaitReExam = util.WqueueStateWaitCashier;
var wqueueStateWaitAppoint = util.WqueueStateWaitCashier;
function insertPatients(conn, patients, cb){
conti.exec([
function(done){
conti.forEach(patients, function(patient, done){
db.insertPatient(conn, patient, done);
}, done);
}
], cb);
}
function insertVisits(conn, visits, cb){
conti.exec([
function(done){
conti.forEach(visits, function(visit, cb){
db.insertVisit(conn, visit, cb);
}, done)
}
], cb);
}
function insertWqueueList(conn, wqueueList, cb){
conti.exec([
function(done){
conti.forEach(wqueueList, function(wqueue, cb){
db.insertWqueue(conn, wqueue, cb);
}, done)
}
], cb);
}
function resetTables(done){
util.withConnect(function(conn, done){
util.initTables(conn, ["wqueue"], ["patient", "visit"], done);
}, done);
}
describe("Testing listFullWqueue", function(){
var conn;
beforeEach(resetTables);
beforeEach(function(done){
setup.connect(function(err, conn_){
if( err ){
done(err);
return;
}
conn = conn_;
done();
});
});
afterEach(function(done){
setup.release(conn, done);
});
afterEach(resetTables);
it("list empty", function(done){
db.listFullWqueue(conn, function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql([]);
done();
})
});
it("list 10", function(done){
var list = util.range(0, 10).map(function(i){
var patient = util.mockPatient();
patient.last_name += i;
return {patient: patient};
});
conti.exec([
function(done){
var patients = list.map(function(item){ return item.patient; });
insertPatients(conn, patients, done);
},
function(done){
list.forEach(function(item){
item.visit = util.mockVisit({patient_id: item.patient.patient_id});
});
var visits = list.map(function(item){ return item.visit; });
insertVisits(conn, visits, done);
},
function(done){
list.forEach(function(item){
item.wqueue = util.mockWqueue({visit_id: item.visit.visit_id, wait_state: wqueueStateWaitExam});
});
var wqueueList = list.map(function(item){ return item.wqueue; });
insertWqueueList(conn, wqueueList, done);
}
], function(err){
if( err ){
done(err);
return;
}
var ans = list.map(function(item){
var o = util.assign({}, item.wqueue);
return util.assign(o, item.patient);
});
db.listFullWqueue(conn, function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql(ans);
done();
})
})
});
it("variable wait states", function(done){
var list = util.range(0, 10).map(function(i){
var patient = util.mockPatient();
patient.last_name += i;
return {patient: patient};
});
conti.exec([
function(done){
var patients = list.map(function(item){ return item.patient; });
insertPatients(conn, patients, done);
},
function(done){
list.forEach(function(item){
item.visit = util.mockVisit({patient_id: item.patient.patient_id});
});
var visits = list.map(function(item){ return item.visit; });
insertVisits(conn, visits, done);
},
function(done){
list.forEach(function(item, i){
var wait_state;
switch(i){
case 1: case 8: wait_state = wqueueStateInExam; break;
case 3: wait_state = wqueueStateWaitCashier; break;
case 4: wait_state = wqueueStateWaitDrug; break;
case 5: case 7: wait_state = wqueueStateWaitReExam; break;
default: wait_state = wqueueStateWaitExam; break;
}
item.wqueue = util.mockWqueue({visit_id: item.visit.visit_id, wait_state: wait_state});
});
var wqueueList = list.map(function(item){ return item.wqueue; });
insertWqueueList(conn, wqueueList, done);
}
], function(err){
if( err ){
done(err);
return;
}
var ans = list.map(function(item){
var o = util.assign({}, item.wqueue);
return util.assign(o, item.patient);
});
db.listFullWqueue(conn, function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql(ans);
done();
})
})
})
});
describe("Testing listFullWqueueForExam", function(){
var conn;
beforeEach(resetTables);
beforeEach(function(done){
setup.connect(function(err, conn_){
if( err ){
done(err);
return;
}
conn = conn_;
done();
});
});
afterEach(function(done){
setup.release(conn, done);
});
afterEach(resetTables);
it("list empty", function(done){
db.listFullWqueueForExam(conn, function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql([]);
done();
})
});
it("all wait exam", function(done){
var list = util.range(0, 10).map(function(i){
var patient = util.mockPatient();
patient.last_name += i;
return {patient: patient};
});
conti.exec([
function(done){
var patients = list.map(function(item){ return item.patient; });
insertPatients(conn, patients, done);
},
function(done){
list.forEach(function(item){
item.visit = util.mockVisit({patient_id: item.patient.patient_id});
});
var visits = list.map(function(item){ return item.visit; });
insertVisits(conn, visits, done);
},
function(done){
list.forEach(function(item){
item.wqueue = util.mockWqueue({visit_id: item.visit.visit_id, wait_state: wqueueStateWaitExam});
});
var wqueueList = list.map(function(item){ return item.wqueue; });
insertWqueueList(conn, wqueueList, done);
}
], function(err){
if( err ){
done(err);
return;
}
var ans = list.map(function(item){
var o = util.assign({}, item.wqueue);
return util.assign(o, item.patient);
});
db.listFullWqueueForExam(conn, function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql(ans);
done();
})
})
});
it("variable wait states", function(done){
var list = util.range(0, 10).map(function(i){
var patient = util.mockPatient();
patient.last_name += i;
return {patient: patient};
});
var ansItems = [];
conti.exec([
function(done){
var patients = list.map(function(item){ return item.patient; });
insertPatients(conn, patients, done);
},
function(done){
list.forEach(function(item){
item.visit = util.mockVisit({patient_id: item.patient.patient_id});
});
var visits = list.map(function(item){ return item.visit; });
insertVisits(conn, visits, done);
},
function(done){
list.forEach(function(item, i){
var wait_state;
switch(i){
case 1: case 8: wait_state = wqueueStateInExam; break;
case 3: wait_state = wqueueStateWaitCashier; break;
case 4: wait_state = wqueueStateWaitDrug; break;
case 5: case 7: wait_state = wqueueStateWaitReExam; break;
default: wait_state = wqueueStateWaitExam; break;
}
item.wqueue = util.mockWqueue({visit_id: item.visit.visit_id, wait_state: wait_state});
if( wait_state !== wqueueStateWaitCashier && wait_state !== wqueueStateWaitDrug ){
ansItems.push(item);
}
});
var wqueueList = list.map(function(item){ return item.wqueue; });
insertWqueueList(conn, wqueueList, done);
}
], function(err){
if( err ){
done(err);
return;
}
var ans = ansItems.map(function(item){
var o = util.assign({}, item.wqueue);
return util.assign(o, item.patient);
});
db.listFullWqueueForExam(conn, function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql(ans);
done();
})
})
});
it("multiple visits for single patient", function(done){
var patients = util.range(0, 10).map(function(i){
var p = util.mockPatient();
p.last_name += i;
return p;
});
var items = [];
conti.exec([
function(done){
insertPatients(conn, patients, done);
},
function(done){
patients.forEach(function(patient, i){
var n = 1;
if( i === 2 ){
n = 2;
} else if( i === 6 ){
n = 3;
}
for(var j = 0; j<n; j++){
items.push({
patient: patient,
visit: util.mockVisit({patient_id: patient.patient_id})
});
}
});
var visits = items.map(function(item){ return item.visit; });
insertVisits(conn, visits, done);
},
function(done){
items.forEach(function(item){
item.wqueue = util.mockWqueue({visit_id: item.visit.visit_id, wait_state: wqueueStateWaitExam});
});
[2, 5].forEach(function(i){
items[i].wqueue.wait_state = wqueueStateWaitDrug;
});
[8].forEach(function(i){
items[i].wqueue.wait_state = wqueueStateWaitReExam;
});
[6].forEach(function(i){
items[i].wqueue.wait_state = wqueueStateWaitCashier;
});
var wqueueList = items.map(function(item){ return item.wqueue; });
insertWqueueList(conn, wqueueList, done);
}
], function(err){
if( err ){
done(err);
return;
}
var ans = items.filter(function(item){
return item.wqueue.wait_state !== wqueueStateWaitDrug && item.wqueue.wait_state !== wqueueStateWaitCashier;
}).map(function(item){
var o = util.assign({}, item.wqueue);
return util.assign(o, item.patient);
})
db.listFullWqueueForExam(conn, function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql(ans);
done();
})
})
})
}); |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require_directory .
|
/**
* @warning: the ordering is important
*/
const sharedPlugins = webpack => ([
require('postcss-import')({
addDependencyTo: webpack,
path: ['node_modules', 'src/app']
// plugins: []
}),
require('postcss-url')(),
require('postcss-cssnext')(),
require('postcss-font-magician')(),
require('postcss-autoreset')(),
require('postcss-discard-duplicates')(),
require('lost')()
])
export default webpack => {
return {
development: [
require('postcss-devtools')(),
...sharedPlugins(webpack),
require('postcss-reporter')(),
require('postcss-browser-reporter')()
],
production: [
...sharedPlugins(webpack)
]
}
}
|
import { len5, len4, len3, len2 } from './dict';
export default {
split(phoneNumber) {
const unkown = [ phoneNumber ];
for (let dict of [ len5, len4, len3, len2 ]) {
const prefix = dict.prefixFrom(phoneNumber);
if (dict.contains(prefix) === false) {
continue;
}
const prefixLength = dict.prefixLength;
const secondaryLength = dict.lengthOfSecondary(prefix);
return [
prefix,
phoneNumber.substr(prefixLength, secondaryLength),
phoneNumber.substr(prefixLength + secondaryLength)
];
}
return unkown;
},
format(phoneNumber) {
return this.split(phoneNumber).join('-');
}
};
|
export { default as useQuery } from './hooks/useQuery';
export { default as ReactOrbitProvider } from './components/Provider';
export { default as useStore } from './hooks/useStore';
|
'use strict';
module.exports = {
AutoPrefix: require('./auto-prefix'),
Colors: require('./colors'),
CustomColors: require('./custom-colors'),
Spacing: require('./spacing'),
ThemeManager: require('./theme-manager'),
Transitions: require('./transitions'),
Typography: require('./typography')
}; |
var searchData=
[
['ok_5fstatus_991',['OK_STATUS',['../classparsers_1_1pddl_1_1solver__planning__domains_1_1spd__grammar__visitor__implementation_1_1SPDGrammarVisitorImplementation.html#aae83243fa85a9104864fafc375fe1ac6',1,'parsers::pddl::solver_planning_domains::spd_grammar_visitor_implementation::SPDGrammarVisitorImplementation']]],
['open_5fsquare_5fbracket_992',['OPEN_SQUARE_BRACKET',['../classparsers_1_1asp_1_1dlv_1_1DLVLexer_1_1DLVLexer.html#a9d7c77b1aec650a0fdfc4b63cb728f58',1,'parsers.asp.dlv.DLVLexer.DLVLexer.OPEN_SQUARE_BRACKET()'],['../classparsers_1_1asp_1_1dlv_1_1DLVParser_1_1DLVParser.html#ab9304bbc3a0f295674be6972cdb49288',1,'parsers.asp.dlv.DLVParser.DLVParser.OPEN_SQUARE_BRACKET()']]]
];
|
var server = require('./server').http,
player = require('./player'),
port = 8000,
filesToLoad = [];
function printHelp(exitp) {
process.stdout.write("\n_____________________________________________________________________________________ \n ");
process.stdout.write(" superplay by Jalal Hejazi 2014 ( sourcecode: github.com/jalalhejazi/superplay ) ");
process.stdout.write("\n_____________________________________________________________________________________ \n ");
process.stdout.write("\n Usage: superplay [options] --add path1 -add path2 ...\n");
process.stdout.write("\n Eks.1: ./bin/superplay --add ~/ --port 1234 \n");
process.stdout.write("\n Eks.2: ./bin/superplay --add ~/home/video --port 8888 \n");
process.stdout.write("\n Options:\n");
process.stdout.write(" -a, --add Add a directory or media file to serve\n");
process.stdout.write(" -p, --port Port to run the HTTP server on [" + port + "]\n");
process.stdout.write(" --background Background processes won't prompt for user input\n");
process.stdout.write(" -h, --help Print help\n\n");
if (exitp) {
process.exit(0);
}
}
/* Parse command-line options, first two args are the process.
*/
for (var i = 2, argv = process.argv, len = argv.length; i < len; i++) {
switch (argv[i]) {
case '-h':
case '--help':
printHelp(true);
break;
case '-p':
case '--port':
var p = parseInt(argv[i + 1]);
if (isFinite(p)) {
port = p;
i += 1;
} else {
process.stderr.write("Invalid port number: " + argv[i + 1] + "\n");
process.exit(1);
}
break
case '-a':
case '--add':
filesToLoad.push(argv[i + 1]);
i += 1;
break;
case '--background':
break; //used in shell-script wrapper, ignore
default:
process.stderr.write("Invalid option: " + argv[i] + "\n");
printHelp();
process.exit(1);
}
}
/* Set up cleanup
*/
process.on('exit', function() {
process.stdout.write("\nShutting down the server, ");
if (typeof player.cleanup === 'function') {
player.cleanup();
}
process.stdout.write("buh-bye!\n");
});
process.on('SIGINT', function() {
process.exit(1);
});
/* And off we go ...
*/
if (typeof player.setup === 'function') {
player.setup();
}
filesToLoad.forEach(player.addFile);
process.stdout.write("Firing up the superplay HTTP server on port " + port + "\n");
server.listen(port);
if (player.files.length === 0) {
process.stderr.write("No media files served! \n");
process.stderr.write("Add some media at the command-line: use cp or scp \n");
} |
/*!
* Flagwind.UI v1.0.0
* Copyright 2014 Flagwind Inc. All rights reserved.
* Licensed under the MIT License.
* https://github.com/Flagwind/Flagwind.UI/blob/master/LICENSE
!*/
// @codekit-append "core.js";
// @codekit-append "animation.js";
// @codekit-append "dropdown.js";
// @codekit-append "alert.js";
/*!
* Flagwind.UI [Core] v1.0.0
* Copyright 2014 Flagwind Inc. All rights reserved.
* Licensed under the MIT License.
* https://github.com/Flagwind/Flagwind.UI/blob/master/LICENSE
!*/
+function($, window, document, undefined)
{
"use strict";
String.prototype.trim = function()
{
return this.replace(/^\s+/g,"").replace(/\s+$/g,"");
};
String.prototype.escape = function()
{
return this.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
$.fw = $.fw || {};
$.extend($.fw,
{
/**
* @public 版本号。
* @type {String}
*/
version : "1.0.1",
/**
* @public 用于展示不同浏览器的特性。
* @type {Object}
*/
support :
{
/**
* @public 是否支持触摸。
* @type {Boolean}
*/
hasTouch : ("ontouchstart" in document.documentElement)
},
/**
* @public 键盘值。
* @type {Object}
*/
keyCodes:
{
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
},
/**
* @public 空函数。
* @type {Function}
*/
empty : function(){},
/**
* @public 动态执行函数调用。
* @param {Object} instance 实例
* @param {String} name 函数名称
* @param {Object} parameters 函数参数
* @param {Object} scope 作用域实例
* @return {Object} 函数执行后的返回值
*/
invoke : function(instance, name, parameters, scope)
{
var names,
maxDepth,
found,
response;
if(typeof name === "string")
{
names = name.split(/[\. ]/);
maxDepth = names.length - 1;
$.each(names, function(depth, value)
{
var camelCaseValue = (depth !== maxDepth) ? value + names[depth + 1].charAt(0).toUpperCase() + names[depth + 1].slice(1) : names[0];
if($.isPlainObject(instance[camelCaseValue]) && (depth !== maxDepth))
{
instance = instance[camelCaseValue];
}
else if(instance[camelCaseValue] !== undefined)
{
found = instance[camelCaseValue];
return false;
}
else if($.isPlainObject(instance[value]) && (depth !== maxDepth))
{
instance = instance[value];
}
else if(instance[value] !== undefined)
{
found = instance[value];
return false;
}
else
{
return false;
}
});
}
if($.isFunction(found))
{
response = found.apply(scope || instance, parameters);
}
else if(found !== undefined)
{
response = found;
}
return response;
},
/**
* @public 解析JSON参数。
* @param {String} parameters 参数
* @return {Object} 解析后的JSON对象
*/
parseOptions : function(parameters)
{
if($.isPlainObject(parameters))
{
return parameters;
}
var start = (parameters ? parameters.indexOf("{") : -1);
var result = {};
if(start != -1)
{
result = (new Function("", "var json = " + parameters.substr(start) +"; return JSON.parse(JSON.stringify(json));"))();
}
return result;
}
});
}(jQuery, window, document);
/*!
* Flagwind.UI [Animation] v1.0.3
* Copyright 2014 Flagwind Inc. All rights reserved.
* Licensed under the MIT License.
* https://github.com/Flagwind/Flagwind.UI/blob/master/LICENSE
!*/
+function($, window, document, undefined)
{
"use strict";
/*
* @private @typedef 插件所需样式类名。
* @type {Object}
*/
var className =
{
animation: "animation",
disabled: "disabled",
animating: "animating",
visible: "visible",
hidden: "hidden",
looping: "looping",
inward: "in",
outward: "out"
};
/**
* @private @typedef 插件所需辅助实例。
* @type {Object}
* @property {String} animationEnd 动画完成后触发的事件名称
* @property {String} animationName 动画规定名称
*/
var support = (function()
{
var getAnimationInfo = function(animations)
{
var element = document.body || document.documentElement;
for(var animation in animations)
{
if(element.style[animation] !== undefined)
{
return animations[animation];
}
}
return null;
};
var getAnimationName = function()
{
var animations =
{
"animation": "animationName",
"OAnimation": "oAnimationName",
"MozAnimation": "mozAnimationName",
"WebkitAnimation": "webkitAnimationName"
};
return getAnimationInfo(animations);
};
var getAnimationEnd = function()
{
var animations =
{
"animation": "animationend",
"OAnimation": "oAnimationEnd",
"MozAnimation": "mozAnimationEnd",
"WebkitAnimation": "webkitAnimationEnd"
};
return getAnimationInfo(animations);
};
var combineUnit = function(value, units)
{
if ((typeof value === "string") && (!value.match(/^[\-0-9\.]+$/)))
{
return value;
}
else
{
return "" + value + units;
}
}
var parseDuration = function(duration)
{
if (typeof duration === "string" && (!duration.match(/^[\-0-9\.]+/)))
{
duration = $.fx.speeds[duration] || $.fx.speeds._default;
}
return combineUnit(duration, "ms");
}
return {
animationEnd : getAnimationEnd(),
animationName : getAnimationName(),
parseDuration : parseDuration
};
})();
/**
* @private @class 初始化 Animation 类的新实例。
* @param {Object} element 元素实例
*/
var Animation = function(element)
{
this.$element = $(element);
};
/**
* @public @static @property 受插件支持的动画名称表。
* @type {Object}
*/
Animation.animations = {};
/**
* Animation 类的原型实例。
* @type {Object}
*/
Animation.prototype =
{
/**
* @private 重新指定原型的构造函数。
* @type {function}
*/
constructor : Animation,
/**
* @public 初始化函数。
* @param {Object} options 选项配置
* @return {Void}
*/
initialize : function(options)
{
var parameters = arguments,
methodName = parameters[0], //截取第一个参数作为函数名
methodInvoked = (typeof methodName === "string"); //根据函数名判断是否为函数调用
// 合并选项
this.options = $.extend(true, {}, $.fn.animation.settings, options);
if(!methodInvoked)
{
// 执行动画
this.animate();
}
else
{
// 执行函数调用
$.fw.invoke(this, methodName, ([].slice.call(parameters, 1)));
}
},
/**
* @private 执行动画效果。
* @return {Void}
*/
animate : function()
{
// 检测是否支持 CSS 动画
if(!this.isSupport())
{
this.onNoSupport();
return;
}
// 检测是否需要加入队列
if(this.isAnimating())
{
if(this.options.queue)
{
if(this.options.allowRepeats || !this.hasDirection() || !this.isOccurring() || module.queuing !== false)
{
this.queue(this.options.animation);
}
return;
}
else if (!this.options.allowRepeats && this.isOccurring())
{
return;
}
else
{
this.complete();
}
}
// 检测是否可支持动画
if(this.canAnimate())
{
this.setAnimating(this.options.animation);
}
else
{
throw new Error("There is no css animation matching the one you specified.");
}
},
/**
* @private 将动画加入执行队列。
* @param {String} animation 动画名
* @return {Void}
*/
queue: function(animation)
{
var self = this;
self.queuing = true;
self.$element.one(support.animationEnd + ".queue" + this.options.eventSuffix, function(){ self.queuing = false; self.animate(); });
},
/**
* @public 刷新动画效果。
* @return {Void}
*/
refresh : function()
{
delete this.displayType;
},
/**
* @public 显示动画目标元素。
* @return {Void}
*/
show : function()
{
this.removeHidden();
this.setVisible();
this.setDisplay();
},
/**
* @public 隐藏动画目标元素。
* @return {Void}
*/
hide : function()
{
if(this.isAnimating())
{
this.reset();
}
this.removeDisplay();
this.removeVisible();
this.setHidden();
},
/**
* @public 切换动画目标元素。
* @return {Void}
*/
toggle : function()
{
if(this.isVisible())
{
this.hide();
}
else
{
this.show();
}
},
/**
* @public 停止当前正在执行的动画。
* @return {Void}
*/
stop : function()
{
this.$element.trigger(support.animationEnd);
},
/**
* @public 停止当前正在执行的所有动画。
* @return {Void}
*/
stopAll : function()
{
this.removeQueueCallback();
this.$element.trigger(support.animationEnd);
},
/**
* @public 清除当前待执行的所有动画。
* @return {Void}
*/
clear : function()
{
this.removeQueueCallback();
},
/**
* @public 启用动画目标元素。
* @return {Void}
*/
enable : function()
{
this.$element.removeClass(className.disabled);
},
/**
* @public 禁用动画目标元素。
* @return {Void}
*/
disable : function()
{
this.$element.addClass(className.disabled);
},
/**
* @public 重设动画目标元素。
* @return {Void}
*/
reset : function()
{
this.removeAnimationCallbacks();
this.restoreConditions();
this.removeAnimating();
},
/**
* @private 动画执行完毕时调用。
* @return {Void}
*/
complete : function()
{
this.removeCompleteCallback();
this.removeFailSafe();
if(!this.isLooping())
{
if(this.isOutward())
{
// 隐藏元素
this.restoreConditions();
this.hide();
this.onHide();
}
else if(this.isInward())
{
// 显示元素
this.restoreConditions();
this.show();
this.onShow();
}
else
{
this.restoreConditions();
}
this.removeAnimation();
this.removeAnimating();
}
this.onComplete();
},
/**
* @private 检测能否执行动画。
* @param {Boolean} forced 是否为强制的
* @return {Boolean} 能否执行动画
*/
canAnimate : function(forced)
{
var elementClass = this.$element.attr("class"), // 元素样式
tagName = this.$element.prop("tagName"), // 元素标签
animation = this.options.animation, // 动画效果名
animationExists = Animation.animations[animation],
$clone,
currentAnimation,
inAnimation,
directionExists,
displayType;
if(animationExists === undefined || forced)
{
$clone = $("<" + tagName + " />").addClass(elementClass).insertAfter(this.$element);
currentAnimation = $clone
.addClass(animation)
.removeClass(className.inward)
.removeClass(className.outward)
.addClass(className.animating)
.addClass(className.animation)
.css(support.animationName);
inAnimation = $clone
.addClass(className.inward)
.css(support.animationName);
displayType = $clone
.attr("class", elementClass)
.removeAttr("style")
.removeClass(className.hidden)
.removeClass(className.visible)
.show()
.css("display");
this.$element.data("display", displayType);
$clone.remove();
directionExists = currentAnimation !== inAnimation;
Animation.animations[animation] = directionExists;
}
return (animationExists !== undefined) ? animationExists : directionExists;
},
/**
* @private 检测指定的动画名是否包含方向。
* @param {String} animation 动画名
* @return {Boolean} 检测结果
*/
hasDirection : function(animation)
{
var result = false;
animation = animation || this.options.animation;
if(typeof animation === "string")
{
animation = animation.split(" ");
$.each(animation, function(index, word)
{
if(word === className.inward || word === className.outward)
{
result = true;
}
});
}
return result;
},
/**
* @private 开始执行动画。
* @param {String} animation 动画名
*/
setAnimating : function(animation)
{
var self = this;
animation = animation || self.options.animation;
if(!self.isAnimating())
{
self.saveConditions();
}
self.removeDirection();
self.removeCompleteCallback();
if(self.canAnimate() && !self.hasDirection())
{
self.setDirection();
}
self.removeHidden();
self.setDisplay();
self.$element.addClass(className.animating + " " + className.animation + " " + animation)
.addClass(animation)
.one(support.animationEnd + ".complete" + self.options.eventSuffix, function(){self.complete();});
if(self.options.useFailSafe)
{
self.addFailSafe();
}
self.setDuration(self.options.duration);
self.onStart();
},
/**
* @private 设置显示方式。
* @return {Void}
*/
setDisplay : function()
{
var style = this.getStyle(),
displayType = this.getDisplayType(),
overrideStyle = style + "display: " + displayType + " !important;";
this.$element.css("display", "");
this.refresh();
if(this.$element.css("display") !== displayType)
{
this.$element.attr("style", overrideStyle);
}
},
/**
* @private 设置为显示状态。
* @return {Void}
*/
setVisible : function()
{
this.$element.addClass(className.animation)
.addClass(className.visible);
},
/**
* @private 设置为隐藏状态。
* @return {Void}
*/
setHidden : function()
{
if(!this.isHidden())
{
this.$element.addClass(className.animation)
.addClass(className.hidden);
}
if(this.$element.css("display") !== "none")
{
this.$element.css("display", "none");
}
},
/**
* @private 设置方向。
* @return {Void}
*/
setDirection : function()
{
if(this.$element.is(":visible") && !this.isHidden())
{
this.$element.removeClass(className.inward)
.addClass(className.outward);
}
else
{
this.$element.removeClass(className.outward)
.addClass(className.inward);
}
},
/**
* @private 设置动画时长。
* @param {Number} duration 动画时长
* @return {Void}
*/
setDuration : function(duration)
{
duration = support.parseDuration(duration || this.options.duration);
if(duration || duration === 0)
{
this.$element
.css
({
"-webkit-animation-duration": duration,
"-moz-animation-duration": duration,
"-ms-animation-duration": duration,
"-o-animation-duration": duration,
"animation-duration": duration
});
}
},
/**
* @private 保存条件。
* @return {Void}
*/
saveConditions : function()
{
var options = this.options,
clasName = this.$element.attr("class") || false,
style = this.$element.attr("style") || "";
this.$element.removeClass(options.animation);
this.removeDirection();
this.cache =
{
className : this.$element.attr("class"),
style : this.getStyle()
};
},
/**
* @private 添加超时定时器。
* @return {Void}
*/
addFailSafe : function()
{
var self = this,
duration = self.getDuration() + self.options.failSafeDelay;
self.timer = setTimeout(function()
{
self.$element.trigger(support.animationEnd);
}, duration);
},
/**
* @private 移除正在动画中标示。
* @return {Void}
*/
removeAnimating : function()
{
this.$element.removeClass(className.animating);
},
/**
* @private 移除动画效果。
* @return {Void}
*/
removeAnimation : function()
{
this.$element.css
({
"-webkit-animation": "",
"-moz-animation": "",
"-ms-animation": "",
"-o-animation": "",
"animation": ""
});
},
/**
* @private 移除超时定时器。
* @return {Void}
*/
removeFailSafe : function()
{
if(this.timer)
{
clearTimeout(this.timer);
}
},
/**
* @private 移除显示方式。
* @return {Void}
*/
removeDisplay : function()
{
this.$element.css("display", "");
},
/**
* @private 移除隐藏模式。
* @return {Void}
*/
removeHidden : function()
{
this.$element.removeClass(className.hidden);
},
/**
* @private 移除显示模式。
* @return {Void}
*/
removeVisible : function()
{
this.$element.removeClass(className.visible);
},
/**
* @private 移除循环。
* @return {Void}
*/
removeLooping : function()
{
if(this.isLooping())
{
this.reset();
this.$element.removeClass(className.looping)
}
},
/**
* @private 移除过渡。
* @return {Void}
*/
removeTransition : function()
{
this.$element.removeClass(className.visible)
.removeClass(className.hidden);
},
/**
* @private 移除方向。
* @return {Void}
*/
removeDirection : function()
{
this.$element.removeClass(className.inward)
.removeClass(className.outward);
},
/**
* @private 移除队列回调。
* @return {Void}
*/
removeQueueCallback : function()
{
this.$element.off(".queue" + this.options.eventSuffix);
},
/**
* @private 移除完成回调。
* @return {Void}
*/
removeCompleteCallback : function()
{
this.$element.off(".complete" + this.options.eventSuffix);
},
/**
* @private 移除所有回调。
* @return {Void}
*/
removeAnimationCallbacks : function()
{
this.removeQueueCallback();
this.removeCompleteCallback();
},
/**
* @private 重置条件。
* @return {Void}
*/
restoreConditions : function()
{
var self = this;
if(self.cache === undefined)
{
return;
}
if(self.cache.className)
{
self.$element.attr("class", self.cache.className);
}
else
{
self.$element.removeAttr("class");
}
if(self.cache.style)
{
self.$element.attr("style", self.cache.style);
}
else
{
self.$element.removeAttr("style");
}
},
/**
* @private 获取 Style 内容。
* @return {String}
*/
getStyle : function()
{
var self = this,
style = self.$element.attr("style") || "";
return style.replace(/display.*?;/, "");
},
/**
* @private 获取显示方式。
* @return {String}
*/
getDisplayType : function()
{
var self = this;
if(self.options.displayType !== null)
{
return self.options.displayType;
}
if(self.$element.data("display") === undefined)
{
self.canAnimate(true);
}
return self.$element.data("display");
},
/**
* @private 获取动画时长。
* @return {String}
*/
getDuration : function(duration)
{
duration = duration || this.options.duration;
if(!duration)
{
duration = this.$element.css("animation-duration") || 0;
}
return parseFloat(support.parseDuration(duration));
},
/**
* @private 判断是否正在执行动画中。
* @return {Boolean}
*/
isAnimating : function()
{
return this.$element.hasClass(className.animating);
},
/**
* @private 判断是否为 in 模式。
* @return {Boolean}
*/
isInward : function()
{
return this.$element.hasClass(className.inward);
},
/**
* @private 判断是否为 out 模式。
* @return {Boolean}
*/
isOutward : function()
{
return this.$element.hasClass(className.outward);
},
/**
* @private 判断是否为循环模式。
* @return {Boolean}
*/
isLooping : function()
{
return this.$element.hasClass(className.looping);
},
/**
* @private 判断是否为事故模式。
* @return {Boolean}
*/
isOccurring : function(animation)
{
animation = animation || this.options.animation;
animation = "." + animation.replace(" ", ".");
return (this.$element.filter(animation).length > 0);
},
/**
* @private 判断是否为显示模式。
* @return {Boolean}
*/
isVisible : function()
{
return this.$element.is(":visible");
},
/**
* @private 判断是否为隐藏模式。
* @return {Boolean}
*/
isHidden : function()
{
return this.$element.css("visibility") === "hidden";
},
/**
* @private 判断是否支持CSS动画。
* @return {Boolean}
*/
isSupport : function()
{
return(support.animationName !== null && support.animationEnd !== null);
},
/**
* @private 当动画开始时调用。
* @return {Void}
*/
onStart : function()
{
// 触发元素事件
this.$element.trigger("start" + this.options.eventSuffix);
// 回调回调函数
this.options.onStart.call(this);
},
/**
* @private 当动画目标元素显示时调用。
* @return {Void}
*/
onShow : function()
{
// 触发元素事件
this.$element.trigger("show" + this.options.eventSuffix);
// 调用回调函数
this.options.onShow.call(this);
},
/**
* @private 当动画目标元素隐藏时调用。
* @return {Void}
*/
onHide : function()
{
// 触发元素事件
this.$element.trigger("hide" + this.options.eventSuffix);
// 调用回调函数
this.options.onHide.call(this);
},
/**
* @private 当动画完毕时调用。
* @return {Void}
*/
onComplete : function()
{
// 触发元素事件
this.$element.trigger("complete" + this.options.eventSuffix);
// 调用回调函数
this.options.onComplete.call(this);
},
/**
* @private 当CSS动画不支持时时调用。
* @return {Void}
*/
onNoSupport : function()
{
// 触发元素事件
this.$element.trigger("nosupport" + this.options.eventSuffix);
// 调用回调函数
this.options.noSupport.call(this);
}
};
$.fn.animation = function(options)
{
var parameters = arguments;
return this.each(function()
{
var $element = $(this),
instance = $element.data($.fn.animation.settings.namespace);
if(!instance)
{
$element.data($.fn.animation.settings.namespace, (instance = new Animation(this)));
}
instance.initialize.apply(instance, parameters);
});
};
$.fn.animation.settings =
{
namespace : "fw.animation",
eventSuffix : ".animation",
displayType : null,
useFailSafe : true,
failSafeDelay : 100,
allowRepeats : false,
queue : true,
duration : "normal",
onStart : $.fw.empty,
onShow : $.fw.empty,
onHide : $.fw.empty,
onComplete : $.fw.empty,
noSupport : $.fw.empty
};
}(jQuery, window, document);
/*!
* Flagwind.UI [Dropdown] v1.0.1
* Copyright 2014 Flagwind Inc. All rights reserved.
* Licensed under the MIT License.
* https://github.com/Flagwind/Flagwind.UI/blob/master/LICENSE
!*/
+function($, window, document, undefined)
{
"use strict";
/**
* @private @class 初始化 Dropdown 类的新实例。
* @param {Object} element 元素实例
*/
var Dropdown = function(element, options)
{
this.options = options;
this.$element = $(element);
this.$toggle = this.$element.children(options.selector.toggle);
this.$content = this.$element.children(options.selector.content);
this.$menu = this.$element.children(options.selector.menu);
this.$items = this.$menu.find(options.selector.item);
this.$text = this.$element.find(options.selector.text);
this.$icon = this.$element.find(options.selector.icon);
this.$search = this.$element.find(options.selector.search);
this.$input = this.$element.find(options.selector.input);
this.activated = false;
this.setTabbable();
this.saveDefaults();
this.setSelected();
this.bindMouseEvents();
this.bindKeyboardEvents();
};
/**
* Dropdown 类的原型实例。
* @type {Object}
*/
Dropdown.prototype =
{
/**
* @private 重新指定原型的构造函数。
* @type {function}
*/
constructor : Dropdown,
/**
* @public 初始化函数。
* @param {Object} options 选项配置
* @return {Void}
*/
initialize : function(options)
{
var parameters = arguments,
methodName = parameters[0], //截取第一个参数作为函数名
methodInvoked = (typeof methodName === "string"); //根据函数名判断是否为函数调用
// 执行函数调用
if(methodInvoked)
{
$.fw.invoke(this, methodName, ([].slice.call(parameters, 1)));
}
},
/**
* @public 切换下拉内容的显示或隐藏。
* @return {Void}
*/
toggle : function()
{
if(this.isActive())
{
this.hide();
}
else
{
this.show();
}
},
/**
* 显示下拉内容。
* @param {Function} callback 回调函数
* @return {Void}
*/
show : function(callback)
{
var self = this;
if(this.isSearchable() && this.isAllFiltered())
{
return;
}
if(!this.canShow() || this.isActive())
{
return;
}
// 添加焦点样式
this.setFocus();
// 隐藏其他菜单
this.hideMenus();
// 设置滚动条位置
this.setScrollPosition(this.getActiveItem(), true);
// 动画完毕回调函数
var complete = function()
{
// 添加激活样式
self.$element.addClass(self.options.className.active);
// 绑定清除其他下拉组件事件
if(self.canClick())
{
self.bindIntent();
}
// 调用回调函数
$.isFunction(callback) && callback.call(self);
// 激发"show"相关事件
self.onShow();
};
// 执行展开动画效果
this.$content.animation
({
animation : this.isUpward() ? "slide up in" : "slide down in",
duration : this.options.duration,
noSupport : complete,
onComplete : complete
});
},
/**
* 隐藏下拉内容。
* @param {Function} callback 回调函数
* @return {Void}
*/
hide : function(callback)
{
var self = this;
if(!this.isActive())
{
return;
}
// 取消焦点样式
this.setBlur();
// 取消绑定清除其他下拉组件事件
if(self.canClick())
{
self.unbindIntent();
}
// 动画完毕回调函数
var complete = function()
{
// 移除激活样式
self.$element.removeClass(self.options.className.active);
// 调用回调函数
$.isFunction(callback) && callback.call(self);
// 激发"hide"相关事件
self.onHide();
};
// 执行隐藏动画效果
this.$content.animation
({
animation : this.isUpward() ? "slide up out" : "slide down out",
duration : this.options.duration,
noSupport : complete,
onComplete : complete
});
},
/**
* 隐藏其他下拉菜单。
* @return {Void}
*/
hideMenus : function()
{
$(".dropdown").not(this.$element).has(this.options.selector.content + ":visible:not(." + this.options.className.animating + ")").dropdown("hide");
},
/**
* 激活菜单项。
* @param {String} text 文本
* @param {String} value 值
* @param {Boolean} isBubbled 是否为冒泡的
* @return {Void}
*/
activate : function(text, value, isBubbled)
{
value = (value !== undefined) ? value : text;
// 选中指定项
this.setSelected(value);
if(!isBubbled)
{
// 隐藏下拉菜单
this.hide(function()
{
this.removeFilteredItem();
});
}
else
{
this.removeFilteredItem();
}
},
/**
* 搜索菜单项。
* @return {Void}
*/
search : function()
{
var keywords = this.$search.val();
this.filter(keywords);
if(this.canShow())
{
this.show();
}
},
/**
* 过滤搜索条件。
* @param {String} keywords 关键字
* @return {Void}
*/
filter : function(keywords)
{
var self = this,
$results = $(),
escapedKeywords = keywords.escape(),
exactRegExp = new RegExp("^" + escapedKeywords, "igm"),
fullTextRegExp = new RegExp(escapedKeywords, "ig"),
allItemsFiltered;
this.$items.each(function()
{
var $choice = $(this),
text = String(self.getChoiceText($choice, false)),
value = String(self.getChoiceValue($choice, text));
if(text.match(exactRegExp) || value.match(exactRegExp))
{
$results = $results.add($choice);
}
});
this.removeFilteredItem();
this.$items.not($results).addClass(this.options.className.filtered);
this.removeSelectedItem();
$results.eq(0).addClass(this.options.className.selected);
if(this.isAllFiltered())
{
this.hide();
this.onNoResults();
}
},
/**
* 选中搜索项。
* @return {Void|
*/
forceSelection : function()
{
var $currentlySelected = this.$items.not(this.options.className.filtered).filter("." + this.options.className.selected).eq(0),
$activeItem = this.$items.filter("." + this.options.className.active).eq(0),
$selectedItem = ($currentlySelected.length > 0) ? $currentlySelected : $activeItem,
hasSelected = ($selectedItem.size() > 0);
if(hasSelected)
{
this.onItemClick({target : $selectedItem.context}, $selectedItem);
this.removeFilteredItem();
}
else
{
this.hide();
}
},
/**
* 设置选择选择元素为获得焦点状态。
* @return {Void}
*/
setFocus : function()
{
// 添加焦点样式
this.$toggle.addClass(this.options.className.focus);
},
/**
* 设置选择选择元素为失去焦点状态。
* @return {Void}
*/
setBlur : function()
{
// 移除焦点样式
this.$toggle.removeClass(this.options.className.focus);
},
/**
* 设置组件的 tabindex。
* @return {Void}
*/
setTabbable : function()
{
if(this.isSearchable())
{
// 获取触发元素的 tabindex
var tabindex = this.isDisabled() ? "-1" : (this.$toggle.attr("tabindex") || 0);
// 设置搜索框的 tabindex
this.$search.val("").attr("tabindex", tabindex);
// 删除触发元素的 tabindex
this.$toggle.removeAttr("tabindex");
}
else
{
if(!this.$toggle.attr("tabindex"))
{
this.$toggle.attr("tabindex", this.isDisabled() ? "-1" : "0");
this.$toggle.siblings("button").attr("tabindex", "-1");
}
}
//this.$content.attr("tabindex", "-1");
},
/**
* 根据指定的值选中菜单项。
* @param {String} value 值
* @return {Void}
*/
setSelected : function(value)
{
var selectedText,
selectedValue,
$selectedItem = this.getItem(value);
if($selectedItem && !$selectedItem.hasClass(this.options.className.active))
{
// 移除选中项样式
this.removeActiveItem();
this.removeSelectedItem();
// 添加选中项选中样式
$selectedItem.addClass(this.options.className.active)
.addClass(this.options.className.selected);
selectedText = this.getChoiceText($selectedItem);
selectedValue = this.getChoiceValue($selectedItem, selectedText);
// 设置文本和值
this.setText(selectedText);
this.setValue(selectedValue);
// 激发"change"相关事件
this.onChange(selectedValue, selectedText, $selectedItem);
}
},
/**
* 设置组件文本。
* @param {String} text 文本
* @return {Void}
*/
setText : function(text)
{
if(this.options.action !== "combobox")
{
// 移除文本样式
this.$text.removeClass(this.options.className.filtered)
.removeClass(this.options.className.placeholder);
// 设置文本内容
if(this.options.preserveHTML)
{
this.$text.html(text);
}
else
{
this.$text.text(text);
}
}
},
/**
* 设置组件值。
* @param {String} value 值
* @return {Void}
*/
setValue : function(value)
{
if(this.$input.length > 0)
{
// 触发隐藏域的"change"事件
this.$input.val(value).trigger("change");
}
else
{
this.$element.data(this.options.metadata.value, value);
}
},
/**
* 设置菜单滚动条的位置。
* @param {Object} $item 菜单项
* @param {Boolean} forceScroll 是否强制滚动
* @return {Void}
*/
setScrollPosition : function($item, forceScroll)
{
var edgeTolerance = 5,
hasActive,
offset,
itemHeight,
itemOffset,
menuOffset,
menuScroll,
menuHeight,
abovePage,
belowPage;
$item = $item || this.getActiveItem();
hasActive = ($item && $item.length > 0);
forceScroll = (forceScroll !== undefined) ? forceScroll : false;
if($item && hasActive)
{
if(!this.$menu.hasClass(this.options.className.visible))
{
this.$menu.addClass(this.options.className.loading);
}
menuHeight = this.$menu.height();
itemHeight = $item.height();
menuScroll = this.$menu.scrollTop();
menuOffset = this.$menu.offset().top;
itemOffset = $item.offset().top;
offset = menuScroll - menuOffset + itemOffset;
belowPage = menuScroll + menuHeight < (offset + edgeTolerance);
abovePage = ((offset - edgeTolerance) < menuScroll);
if(abovePage || belowPage || forceScroll)
{
this.$menu.scrollTop(offset)
.removeClass(this.options.className.loading);
}
}
},
/**
* 设置过滤文本。
* @return {Void}
*/
setFiltered : function()
{
var searchValue = this.$search.val(),
hasSearchValue = (typeof searchValue === "string" && searchValue.length > 0);
if(hasSearchValue)
{
this.$text.addClass(this.options.className.filtered);
}
else
{
this.$text.removeClass(this.options.className.filtered);
}
},
/**
* 获取文本。
* @return {String} 文本内容
*/
getText : function()
{
return this.$text.text();
},
/**
* 获取值。
* @return {String} 值
*/
getValue : function()
{
return String((this.$input.length > 0) ? this.$input.val() : this.$element.data(this.options.metadata.value));
},
/**
* 根据指定的值获取菜单项。
* @param {String} value 值
* @return {Object} 菜单项
*/
getItem : function(value)
{
var self = this,
$item = null;
value = (value !== undefined) ? value : (this.getValue() !== undefined) ? this.getValue() : this.getText();
if(value !== undefined)
{
this.$items.each(function()
{
var $choice = $(this),
itemText = self.getChoiceText($choice),
itemValue = self.getChoiceValue($choice, itemText);
if(itemValue === value)
{
$item = $(this);
return true;
}
else if(!$item && itemText === value)
{
$item = $(this);
return true;
}
});
}
return $item;
},
/**
* 获取当前选择的菜单项。
* @return {Object} 菜单项
*/
getSelectedItem : function()
{
return this.$items.filter("." + this.options.className.selected);
},
/**
* 获取当前激活的菜单项。
* @return {Object} 菜单项
*/
getActiveItem : function()
{
return this.$items.filter("." + this.options.className.active);
},
/**
* 获取菜单项的文本。
* @param {Object} $item 菜单项
* @param {Boolean} preserveHTML 是否保存HTML
* @return {String} 菜单项文本
*/
getChoiceText : function($item, preserveHTML)
{
preserveHTML = (preserveHTML !== undefined) ? preserveHTML : this.options.preserveHTML;
if($item !== undefined)
{
// 获取"data-text"属性中的内容
if($item.data(this.options.metadata.text) !== undefined)
{
return $item.data(this.options.metadata.text);
}
return preserveHTML ? $item.html().trim() : $item.text().trim();
}
},
/**
* 获取菜单项的值,如果值为空,则返回文本。
* @param {Object} $item 菜单项
* @param {String} text 菜单项文本
* @return {String} 菜单项值
*/
getChoiceValue : function($item, text)
{
// 解析菜单项文本
text = text || this.getChoiceText($item);
// 获取"data-value"属性中的内容
if($item.data(this.options.metadata.value) !== undefined)
{
return String($item.data(this.options.metadata.value));
}
return text;
},
/**
* 获取搜索框的事件名。
* @return {[type]} [description]
*/
getSearchEventName : function()
{
var input = this.$search[0];
if(input)
{
return (input.oninput !== undefined) ? "input" : "keyup";
}
return null;
},
/**
* 移除搜索框的文本。
* @return {Void}
*/
removeSearchText : function()
{
this.$search.val("");
},
/**
* 移除选择的菜单项。
* @return {Void}
*/
removeSelectedItem : function()
{
this.$items.removeClass(this.options.className.selected);
},
/**
* 移除激活的选择项。
* @return {Void}
*/
removeActiveItem : function()
{
this.$items.removeClass(this.options.className.active);
},
/**
* 移除过滤的菜单项。
* @return {Void}
*/
removeFilteredItem : function()
{
this.$items.removeClass(this.options.className.filtered);
},
/**
* 保存默认数据。
* @return {Void}
*/
saveDefaults : function()
{
this.saveDefaultText();
this.savePlaceholderText();
this.saveDefaultValue();
},
/**
* 保存默认文本。
* @return {Void}
*/
saveDefaultText : function()
{
this.$element.data(this.options.metadata.defaultText, this.getText());
},
/**
* 保存默认值。
* @return {Void}
*/
saveDefaultValue : function()
{
this.$element.data(this.options.metadata.defaultValue, this.getValue());
},
/**
* 保存占位文本。
* @return {Void}
*/
savePlaceholderText : function()
{
if(this.$text.hasClass(this.options.className.placeholder))
{
this.$element.data(this.options.metadata.placeholderText, this.$text.text());
}
},
/**
* 检测当前下拉菜单是否为激活的。
* @return {Boolean}
*/
isActive : function()
{
return this.$element.hasClass(this.options.className.active);
},
/**
* 检测当前菜单方向是否为向上。
* @return {Boolean}
*/
isUpward : function()
{
return this.$element.hasClass(this.options.className.upward);
},
/**
* 检测当前下拉内容是否为隐藏状态。
* @return {Boolean}
*/
isHidden : function()
{
return this.$content.is(":hidden");
},
/**
* 检测当前组件是否为支持下拉选择。
* @return {Boolean}
*/
isSelection : function()
{
return this.$element.hasClass(this.options.className.selection);
},
/**
* 检测当前下拉组件是否支持查找。
* @return {Boolean}
*/
isSearchable : function()
{
return this.$search.length > 0;
},
/**
* 检测菜单项是否全过滤。
* @return {Boolean}
*/
isAllFiltered : function()
{
return (this.$items.filter("." + this.options.className.filtered).length === this.$items.length);
},
/**
* 检测组件是否为禁用状态。
* @return {Boolean}
*/
isDisabled : function()
{
return this.$toggle.hasClass(this.options.className.disabled) || this.$toggle.attr("disabled") === "disabled";
},
/**
* 检测当前触发元素是否为可点击的。
* @return {Boolean}
*/
canClick : function()
{
return ($.fw.support.hasTouch || this.options.trigger === "click");
},
/**
* 检测菜单项是否能被选中。
* @param {Object} $item 菜单项
* @return {Boolean}
*/
canSelect : function($item)
{
return !$item.hasClass(this.options.className.disabled) && !$item.hasClass(this.options.className.divider);
},
/**
* 检测菜单是否为可呈现的。
* @return {Boolean}
*/
canShow : function()
{
return !this.$toggle.hasClass(this.options.className.disabled) && this.$toggle.attr("disabled") !== "disabled";
},
/**
* 绑定清除其他下拉组件事件
* @return {Void}
*/
bindIntent : function()
{
var self = this;
if($.fw.support.hasTouch)
{
$(document).on("touchstart" + this.options.eventSuffix, $.proxy(self.onTouch, this))
.on("touchmove" + this.options.eventSuffix, $.proxy(self.onTouch, this));
}
$(document).on("click" + this.options.eventSuffix, function(e)
{
if($(e.target).closest(self.$element).length === 0)
{
self.hide();
}
});
},
/**
* 解除绑定清除其他下拉组件事件。
* @return {Void}
*/
unbindIntent : function()
{
if($.fw.support.hasTouch)
{
$(document).off("touchstart" + this.options.eventSuffix)
.off("touchmove" + this.options.eventSuffix);
}
$(document).off("click" + this.options.eventSuffix);
},
/**
* 绑定鼠标相关事件。
* @return {Void}
*/
bindMouseEvents : function()
{
var self = this,
trigger = this.options.trigger;
// 绑定下拉组件鼠标事件
this.$element.on("mousedown" + this.options.eventSuffix, $.proxy(this.onMousedown, this))
.on("mouseup" + this.options.eventSuffix, $.proxy(this.onMouseup, this));
if(this.isSelection())
{
this.$icon.on("click" + this.options.eventSuffix, $.proxy(function(e)
{
e.preventDefault();
e.stopPropagation();
self.toggle();
}, this));
}
if(this.isSearchable())
{
// 绑定搜索文本框焦点事件
this.$search.on("focus" + this.options.eventSuffix, $.proxy(this.onFocus, this))
.on("blur" + this.options.eventSuffix, $.proxy(this.onBlur, this))
.on("click" + this.options.eventSuffix, $.proxy(this.onSearchClick, this));
this.$element.on("click" + this.options.eventSuffix, this.options.selector.text, $.proxy(this.onSearchClick, this));
}
else
{
// 点击触发处理
if(trigger === "click")
{
this.$toggle.on("click" + this.options.eventSuffix, function(e)
{
e.preventDefault();
self.toggle();
});
}
// 移入触发处理
else if(trigger === "hover")
{
this.$element.on("mouseenter" + this.options.eventSuffix, function(e)
{
e.preventDefault();
clearTimeout(self.timer);
self.timer = setTimeout($.proxy(self.show, self), self.options.delay.show);
});
this.$element.on("mouseleave" + this.options.eventSuffix, function(e)
{
e.preventDefault();
clearTimeout(self.timer);
self.timer = setTimeout($.proxy(self.hide, self), self.options.delay.hide);
});
}
// 绑定触发元素焦点事件
this.$toggle.on("focus" + this.options.eventSuffix, $.proxy(this.onFocus, this))
.on("blur" + this.options.eventSuffix, $.proxy(this.onBlur, this));
}
// 绑定菜单项点击事件
this.$menu.on("click" + this.options.eventSuffix, this.options.selector.item, $.proxy(this.onItemClick, this));
},
/**
* 绑定键盘相关事件。
* @return {Void}
*/
bindKeyboardEvents : function()
{
// 绑定键盘(上/下/回车)事件。
this.$element.on("keydown" + this.options.eventSuffix, $.proxy(this.onKeydown, this));
//绑定搜索事件。
if(this.isSearchable())
{
this.$element.on(this.getSearchEventName(), this.options.selector.search, $.proxy(this.onSearch, this));
}
},
/**
* 当触摸屏幕时调用。
* @param {Object} e 事件对象
* @return {Void}
*/
onTouch : function(e)
{
var self = this;
if($(e.target).closest(self.$element).length === 0)
{
if(e.type == "touchstart")
{
self.timer = setTimeout(function()
{
if(self.isSearchable())
{
self.hide();
}
else
{
self.$toggle.blur();
}
}, this.options.delay.touch);
}
else if(e.type == "touchmove")
{
clearTimeout(self.timer);
}
}
e.stopPropagation();
},
/**
* 当菜单激活时调用。
* @return {Void}
*/
onMenuActivate : function()
{
this.itemActivated = true;
},
/**
* 当菜单取消激活时调用。
* @return {Void}
*/
onMenuDeactivate : function()
{
this.itemActivated = false;
},
/**
* 当菜单项点击时调用。
* @param {Object} e 事件参数
* @return {Void}
*/
onItemClick : function(e, $selectedItem)
{
var $choice = $selectedItem || $(e.currentTarget),
isBubbled = $(e.target).is("button"),
text = this.getChoiceText($choice),
value = this.getChoiceValue($choice, text);
// 检测是否能被选中
if(!this.canSelect($choice))
{
return;
}
this.removeSearchText();
// 选择处理动作
if($.isFunction(this[this.options.action]))
{
this[this.options.action](text, value, isBubbled);
}
else if($.isFunction(this.options.action))
{
this.options.action.call(this, text, value, isBubbled);
}
},
/**
* 当键盘按下时调用。
* @param {Object} e 事件参数
* @return {Void}
*/
onKeydown : function(e)
{
var $nextItem,
pressedKey = e.which,
$currentlySelected = this.$items.not(this.options.className.filtered).filter("." + this.options.className.selected).eq(0),
$activeItem = this.$menu.children("." + this.options.className.active).eq(0),
$selectedItem = ($currentlySelected.length > 0) ? $currentlySelected : $activeItem,
$visibleItems = ($selectedItem.length > 0) ? $selectedItem.siblings(":not(." + this.options.className.filtered + ")").andSelf() : this.$menu.children(":not(." + this.options.className.filtered + ")"),
hasSelectedItem = ($selectedItem.length > 0);
if(this.isActive())
{
// 向上键
if(pressedKey == $.fw.keyCodes.UP)
{
$nextItem = hasSelectedItem ? $selectedItem.prevAll(this.options.selector.item + ":not(." + this.options.className.filtered + ")").eq(0) : this.$items.eq(0);
if ($visibleItems.index($nextItem) < 0)
{
return;
}
else
{
$selectedItem.removeClass(this.options.className.selected);
$nextItem.addClass(this.options.className.selected);
this.setScrollPosition($nextItem);
}
e.preventDefault();
}
// 向下键
else if(pressedKey == $.fw.keyCodes.DOWN)
{
$nextItem = hasSelectedItem ? $selectedItem.nextAll(this.options.selector.item + ":not(." + this.options.className.filtered + ")").eq(0) : this.$items.eq(0);
if($nextItem.length === 0)
{
return;
}
else
{
this.$items.removeClass(this.options.className.selected);
$nextItem.addClass(this.options.className.selected);
this.setScrollPosition($nextItem);
}
}
// 回车键
else if(pressedKey == $.fw.keyCodes.ENTER)
{
this.onItemClick(e, $selectedItem);
if(this.isSearchable())
{
e.preventDefault();
}
}
// ESC 键
else if(pressedKey == $.fw.keyCodes.ESCAPE)
{
this.hide();
}
}
else
{
// 内容朝上时按上键显示内容
if(this.isUpward() && (pressedKey == $.fw.keyCodes.UP || pressedKey == $.fw.keyCodes.DOWN))
{
this.show();
}
// 内容朝下时按下键显示内容
if(!this.isUpward() && pressedKey == $.fw.keyCodes.DOWN)
{
this.show();
}
}
},
/**
* 当触发搜索时调用。
* @param {Object} e 事件参数
* @return {Void}
*/
onSearch : function(e)
{
var pressedKey = e.which;
if(pressedKey == $.fw.keyCodes.UP || pressedKey == $.fw.keyCodes.DOWN || pressedKey == $.fw.keyCodes.ENTER)
{
return;
}
// 设置过滤样式。
this.setFiltered();
clearTimeout(this.timer);
this.timer = setTimeout($.proxy(this.search, this), this.options.delay.search);
},
/**
* 当搜索框点击时调用。
* @param {Object} e 事件参数
* @return {Void}
*/
onSearchClick : function(e)
{
this.$search.focus();
},
/**
* 当下拉组件鼠标按下时调用。
* @return {Void}
*/
onMousedown : function()
{
this.activated = true;
},
/**
* 当下拉组件鼠标弹起时调用。
* @return {Void}
*/
onMouseup : function()
{
this.activated = false;
},
/**
* 当触发元素获得焦点时调用。
* @return {Void}
*/
onFocus : function()
{
if(!this.activated && this.isHidden())
{
this.show();
}
},
/**
* 当触发元素失去焦点时调用。
* @return {Void}
*/
onBlur : function(e)
{
var pageLostFocus = (document.activeElement === e.target);
if(!this.activated && !pageLostFocus)
{
if(this.isSearchable() && this.options.forceSelection)
{
this.forceSelection();
}
else
{
this.hide();
}
}
},
/**
* 当下拉菜单发生改变时调用。
* @param {String} value 值
* @param {String} text 文本
* @param {Object} $item 菜单项
* @return {Void}
*/
onChange : function(value, text, $item)
{
// 触发元素事件
this.$element.trigger("change" + this.options.eventSuffix, [value, text, $item]);
// 调用回调函数
this.options.onChange.call(this, value, text, $item);
},
/**
* 当下拉菜单显示时调用。
* @return {Void}
*/
onShow : function()
{
// 触发元素事件
this.$element.trigger("show" + this.options.eventSuffix);
// 调用回调函数
this.options.onShow.call(this);
},
/**
* 当下拉菜单隐藏时调用。
* @return {Void}
*/
onHide : function()
{
// 触发元素事件
this.$element.trigger("hide" + this.options.eventSuffix);
// 调用回调函数
this.options.onHide.call(this);
},
/**
* 当没有搜索结果时调用。
* @return {Void}
*/
onNoResults : function()
{
// 触发元素事件
this.$element.trigger("noresults" + this.options.eventSuffix);
// 调用回调函数
this.options.onNoResults.call(this);
}
};
$.fn.dropdown = function(options)
{
var parameters = arguments;
return this.each(function()
{
var plainObject,
$element = $(this),
instance = $element.data($.fn.dropdown.settings.namespace);
if(!instance)
{
plainObject = $.extend(true, {}, $.fn.dropdown.settings, $.fw.parseOptions($element.data("dropdown")), options);
$element.data($.fn.dropdown.settings.namespace, (instance = new Dropdown(this, plainObject)));
}
instance.initialize.apply(instance, parameters);
});
};
$.fn.dropdown.settings =
{
namespace : "fw.dropdown",
eventSuffix : ".dropdown",
trigger : "click", // 触发类型:click(点击) | hover(移入)
action : "activate", // 点击动作:activate(激活)
duration : 250, // 动画时长
preserveHTML : false, // 是否支持HTML
forceSelection : true,
className :
{
focus : "focus",
active : "active",
animating : "animating",
selected : "selected",
disabled : "disabled",
filtered : "filtered",
placeholder : "default",
loading : "loading",
visible : "visible",
divider : "divider",
upward : "dropdown-up",
selection : "dropdown-selection"
},
selector :
{
toggle : ".dropdown-toggle",
content : ".dropdown-content",
text : ".text:not(.icon)",
icon : ".dropdown-toggle > .icon",
search : ".search",
input : "> input[type='hidden'], > select",
menu : "ul.dropdown-content",
item : "li:not(.divider):not(.disabled)"
},
metadata :
{
defaultText : "defaultText",
defaultValue : "defaultValue",
placeholderText : "placeholderText",
text : "text",
value : "value"
},
delay :
{
show : 150,
hide : 250,
search : 50,
touch : 50
},
onShow : $.fw.empty,
onHide : $.fw.empty,
onChange : $.fw.empty,
onNoResults : $.fw.empty
};
}(jQuery, window, document);
$(function()
{
$(".dropdown").dropdown();
});
/*!
* Flagwind.UI [Alert] v1.0.0
* Copyright 2014 Flagwind Inc. All rights reserved.
* Licensed under the MIT License.
* https://github.com/Flagwind/Flagwind.UI/blob/master/LICENSE
!*/
+function($, window, document, undefined)
{
'use strict';
/**
* [Alert 构造函数]
* @param {[type]} element [DOM元素]
* @param {[type]} options [参数]
*/
var Alert = function(element, options)
{
this.options = options;
this.$element = $(element);
this.$close = this.$element.find(this.options.selector.close);
this.bindEvents();
};
/**
* [prototype 原型]
* @type {[type]}
*/
Alert.prototype =
{
constructor: Alert,
initialize: function(options)
{
var parameters = arguments,
methodName = parameters[0],
methodInvoked = (typeof methodName === "string");
if(methodInvoked)
{
$.fw.invoke(this, methodName, ([].slice.call(parameters, 1)));
}
},
close: function(callback)
{
var self = this;
// 删除元素
var complete = function()
{
self.$element.remove();
self.onClose();
};
// 动画完毕执行回调函数
this.$element.animation
({
animation: 'fade out',
duration: this.options.duration,
queue: false,
noSupport: complete,
onComplete: complete
});
},
onClose: function()
{
// 触发元素事件
this.$element.trigger("close" + this.options.eventSuffix);
// 调用回调函数
this.options.onClose.call(this);
},
bindEvents: function()
{
this.$close.on('click' + this.options.eventSuffix, $.proxy(this.close, this));
}
};
/**
* [alert 扩展到jQuery]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
$.fn.alert = function(options)
{
var parameters = arguments;
return this.each(function()
{
var plainObject,
$element = $(this),
instance = $element.data($.fn.alert.settings.namespace);
if(!instance)
{
plainObject = $.extend(true, {}, $.fn.alert.settings, $.fw.parseOptions($element.data("alert")), options);
instance = new Alert(this, plainObject);
$element.data($.fn.alert.settings.namespace, instance);
}
instance.initialize.apply(instance, parameters);
});
};
/**
* [settings 默认设置]
* @type {[type]}
*/
$.fn.alert.settings =
{
namespace: 'fw.alert',
eventSuffix: '.alert',
duration: 1000,
selector:
{
close: '.close'
},
onClose : $.fw.empty
};
}(jQuery, window, document);
// 调用插件
// $('.alert').alert(
// {
// onClose: function()
// {
// console.log('已关闭');
// }
// });
|
// 9000ポートで開始
var BinaryServer = require('binaryjs').BinaryServer,
binaryServer = BinaryServer({
port: 9000
});
var clients = [];
exports.start = function () {
binaryServer.on('connection', function (client) {
client.on('stream', function (stream) {
clients.push(client);
//Streamデータ受信時
stream.on('data', function (data) {
clients.forEach(function(client) {
var responseStream = client.createStream('fromserver');
// pipe didnt work :(
responseStream.write(data);
});
});
//クライアントConnction切断時
stream.on('close', function(){
clients = clients.filter(function(item){
return client.id != item.id;
});
});
});
});
};
|
particlesJS("blood", {
"particles": {
"number": {
"value": 300,
"density": {
"enable": true,
"value_area": 1800
}
},
"color": {
"value": "#ab0505"
},
"shape": {
"type": "circle",
"stroke": {
"width": 0,
"color": "#444"
},
"polygon": {
"nb_sides": 4
}
},
"opacity": {
"value": 0.5,
"random": true,
"anim": {
"enable": false,
"speed": 1,
"opacity_min": 0.1,
"sync": false
}
},
"size": {
"value": 40,
"random": false,
"anim": {
"enable": true,
"speed": 10,
"size_min": 40,
"sync": false
}
},
"line_linked": {
"enable": false,
"distance": 200,
"color": "#ffffff",
"opacity": 1,
"width": 2
},
"move": {
"enable": true,
"speed": 8,
"direction": "none",
"random": false,
"straight": false,
"out_mode": "out",
"bounce": false,
"attract": {
"enable": false,
"rotateX": 600,
"rotateY": 1200
}
}
},
"interactivity": {
"detect_on": "canvas",
"events": {
"onhover": {
"enable": false,
"mode": "grab"
},
"onclick": {
"enable": false,
"mode": "push"
},
"resize": true
},
"modes": {
"grab": {
"distance": 400,
"line_linked": {
"opacity": 1
}
},
"bubble": {
"distance": 400,
"size": 40,
"duration": 2,
"opacity": 8,
"speed": 3
},
"repulse": {
"distance": 200,
"duration": 0.4
},
"push": {
"particles_nb": 4
},
"remove": {
"particles_nb": 2
}
}
},
"retina_detect": true
}); |
/**
* Cesium - https://github.com/AnalyticalGraphicsInc/cesium
*
* Copyright 2011-2017 Cesium Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Columbus View (Pat. Pend.)
*
* Portions licensed separately.
* See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
*/
(function () {
/*global define*/
define('Core/defined',[],function() {
'use strict';
/**
* @exports defined
*
* @param {Object} value The object.
* @returns {Boolean} Returns true if the object is defined, returns false otherwise.
*
* @example
* if (Cesium.defined(positions)) {
* doSomething();
* } else {
* doSomethingElse();
* }
*/
function defined(value) {
return value !== undefined && value !== null;
}
return defined;
});
/*global define*/
define('Core/DeveloperError',[
'./defined'
], function(
defined) {
'use strict';
/**
* Constructs an exception object that is thrown due to a developer error, e.g., invalid argument,
* argument out of range, etc. This exception should only be thrown during development;
* it usually indicates a bug in the calling code. This exception should never be
* caught; instead the calling code should strive not to generate it.
* <br /><br />
* On the other hand, a {@link RuntimeError} indicates an exception that may
* be thrown at runtime, e.g., out of memory, that the calling code should be prepared
* to catch.
*
* @alias DeveloperError
* @constructor
* @extends Error
*
* @param {String} [message] The error message for this exception.
*
* @see RuntimeError
*/
function DeveloperError(message) {
/**
* 'DeveloperError' indicating that this exception was thrown due to a developer error.
* @type {String}
* @readonly
*/
this.name = 'DeveloperError';
/**
* The explanation for why this exception was thrown.
* @type {String}
* @readonly
*/
this.message = message;
//Browsers such as IE don't have a stack property until you actually throw the error.
var stack;
try {
throw new Error();
} catch (e) {
stack = e.stack;
}
/**
* The stack trace of this exception, if available.
* @type {String}
* @readonly
*/
this.stack = stack;
}
if (defined(Object.create)) {
DeveloperError.prototype = Object.create(Error.prototype);
DeveloperError.prototype.constructor = DeveloperError;
}
DeveloperError.prototype.toString = function() {
var str = this.name + ': ' + this.message;
if (defined(this.stack)) {
str += '\n' + this.stack.toString();
}
return str;
};
/**
* @private
*/
DeveloperError.throwInstantiationError = function() {
throw new DeveloperError('This function defines an interface and should not be called directly.');
};
return DeveloperError;
});
/*global define*/
define('Core/Check',[
'./defined',
'./DeveloperError'
], function(
defined,
DeveloperError) {
'use strict';
/**
* Contains functions for checking that supplied arguments are of a specified type
* or meet specified conditions
* @private
*/
var Check = {};
/**
* Contains type checking functions, all using the typeof operator
*/
Check.typeOf = {};
function getUndefinedErrorMessage(name) {
return name + ' is required, actual value was undefined';
}
function getFailedTypeErrorMessage(actual, expected, name) {
return 'Expected ' + name + ' to be typeof ' + expected + ', actual typeof was ' + actual;
}
/**
* Throws if test is not defined
*
* @param {String} name The name of the variable being tested
* @param {*} test The value that is to be checked
* @exception {DeveloperError} test must be defined
*/
Check.defined = function (name, test) {
if (!defined(test)) {
throw new DeveloperError(getUndefinedErrorMessage(name));
}
};
/**
* Throws if test is not typeof 'function'
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @exception {DeveloperError} test must be typeof 'function'
*/
Check.typeOf.func = function (name, test) {
if (typeof test !== 'function') {
throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'function', name));
}
};
/**
* Throws if test is not typeof 'string'
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @exception {DeveloperError} test must be typeof 'string'
*/
Check.typeOf.string = function (name, test) {
if (typeof test !== 'string') {
throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'string', name));
}
};
/**
* Throws if test is not typeof 'number'
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @exception {DeveloperError} test must be typeof 'number'
*/
Check.typeOf.number = function (name, test) {
if (typeof test !== 'number') {
throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'number', name));
}
};
/**
* Throws if test is not typeof 'number' and less than limit
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @param {Number} limit The limit value to compare against
* @exception {DeveloperError} test must be typeof 'number' and less than limit
*/
Check.typeOf.number.lessThan = function (name, test, limit) {
Check.typeOf.number(name, test);
if (test >= limit) {
throw new DeveloperError('Expected ' + name + ' to be less than ' + limit + ', actual value was ' + test);
}
};
/**
* Throws if test is not typeof 'number' and less than or equal to limit
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @param {Number} limit The limit value to compare against
* @exception {DeveloperError} test must be typeof 'number' and less than or equal to limit
*/
Check.typeOf.number.lessThanOrEquals = function (name, test, limit) {
Check.typeOf.number(name, test);
if (test > limit) {
throw new DeveloperError('Expected ' + name + ' to be less than or equal to ' + limit + ', actual value was ' + test);
}
};
/**
* Throws if test is not typeof 'number' and greater than limit
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @param {Number} limit The limit value to compare against
* @exception {DeveloperError} test must be typeof 'number' and greater than limit
*/
Check.typeOf.number.greaterThan = function (name, test, limit) {
Check.typeOf.number(name, test);
if (test <= limit) {
throw new DeveloperError('Expected ' + name + ' to be greater than ' + limit + ', actual value was ' + test);
}
};
/**
* Throws if test is not typeof 'number' and greater than or equal to limit
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @param {Number} limit The limit value to compare against
* @exception {DeveloperError} test must be typeof 'number' and greater than or equal to limit
*/
Check.typeOf.number.greaterThanOrEquals = function (name, test, limit) {
Check.typeOf.number(name, test);
if (test < limit) {
throw new DeveloperError('Expected ' + name + ' to be greater than or equal to' + limit + ', actual value was ' + test);
}
};
/**
* Throws if test is not typeof 'object'
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @exception {DeveloperError} test must be typeof 'object'
*/
Check.typeOf.object = function (name, test) {
if (typeof test !== 'object') {
throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'object', name));
}
};
/**
* Throws if test is not typeof 'boolean'
*
* @param {String} name The name of the variable being tested
* @param {*} test The value to test
* @exception {DeveloperError} test must be typeof 'boolean'
*/
Check.typeOf.bool = function (name, test) {
if (typeof test !== 'boolean') {
throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'boolean', name));
}
};
return Check;
});
/*global define*/
define('Core/freezeObject',[
'./defined'
], function(
defined) {
'use strict';
/**
* Freezes an object, using Object.freeze if available, otherwise returns
* the object unchanged. This function should be used in setup code to prevent
* errors from completely halting JavaScript execution in legacy browsers.
*
* @private
*
* @exports freezeObject
*/
var freezeObject = Object.freeze;
if (!defined(freezeObject)) {
freezeObject = function(o) {
return o;
};
}
return freezeObject;
});
/*global define*/
define('Core/defaultValue',[
'./freezeObject'
], function(
freezeObject) {
'use strict';
/**
* Returns the first parameter if not undefined, otherwise the second parameter.
* Useful for setting a default value for a parameter.
*
* @exports defaultValue
*
* @param {*} a
* @param {*} b
* @returns {*} Returns the first parameter if not undefined, otherwise the second parameter.
*
* @example
* param = Cesium.defaultValue(param, 'default');
*/
function defaultValue(a, b) {
if (a !== undefined) {
return a;
}
return b;
}
/**
* A frozen empty object that can be used as the default value for options passed as
* an object literal.
*/
defaultValue.EMPTY_OBJECT = freezeObject({});
return defaultValue;
});
/*
I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
so it's better encapsulated. Now you can have multiple random number generators
and they won't stomp all over eachother's state.
If you want to use this as a substitute for Math.random(), use the random()
method like so:
var m = new MersenneTwister();
var randomNumber = m.random();
You can also call the other genrand_{foo}() methods on the instance.
If you want to use a specific seed in order to get a repeatable random
sequence, pass an integer into the constructor:
var m = new MersenneTwister(123);
and that will always produce the same random sequence.
Sean McCullough (banksean@gmail.com)
*/
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
*/
/**
@license
mersenne-twister.js - https://gist.github.com/banksean/300494
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The names of its contributors may not 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.
*/
/*
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
define('ThirdParty/mersenne-twister',[],function() {
var MersenneTwister = function(seed) {
if (seed == undefined) {
seed = new Date().getTime();
}
/* Period parameters */
this.N = 624;
this.M = 397;
this.MATRIX_A = 0x9908b0df; /* constant vector a */
this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
this.mt = new Array(this.N); /* the array for the state vector */
this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */
this.init_genrand(seed);
}
/* initializes mt[N] with a seed */
MersenneTwister.prototype.init_genrand = function(s) {
this.mt[0] = s >>> 0;
for (this.mti=1; this.mti<this.N; this.mti++) {
var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
+ this.mti;
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
this.mt[this.mti] >>>= 0;
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
//MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
// var i, j, k;
// this.init_genrand(19650218);
// i=1; j=0;
// k = (this.N>key_length ? this.N : key_length);
// for (; k; k--) {
// var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
// this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
// + init_key[j] + j; /* non linear */
// this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
// i++; j++;
// if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
// if (j>=key_length) j=0;
// }
// for (k=this.N-1; k; k--) {
// var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
// this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
// - i; /* non linear */
// this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
// i++;
// if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
// }
//
// this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
//}
/* generates a random number on [0,0xffffffff]-interval */
MersenneTwister.prototype.genrand_int32 = function() {
var y;
var mag01 = new Array(0x0, this.MATRIX_A);
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (this.mti >= this.N) { /* generate N words at one time */
var kk;
if (this.mti == this.N+1) /* if init_genrand() has not been called, */
this.init_genrand(5489); /* a default initial seed is used */
for (kk=0;kk<this.N-this.M;kk++) {
y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
}
for (;kk<this.N-1;kk++) {
y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
}
y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];
this.mti = 0;
}
y = this.mt[this.mti++];
/* Tempering */
y ^= (y >>> 11);
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= (y >>> 18);
return y >>> 0;
}
/* generates a random number on [0,0x7fffffff]-interval */
//MersenneTwister.prototype.genrand_int31 = function() {
// return (this.genrand_int32()>>>1);
//}
/* generates a random number on [0,1]-real-interval */
//MersenneTwister.prototype.genrand_real1 = function() {
// return this.genrand_int32()*(1.0/4294967295.0);
// /* divided by 2^32-1 */
//}
/* generates a random number on [0,1)-real-interval */
MersenneTwister.prototype.random = function() {
return this.genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
//MersenneTwister.prototype.genrand_real3 = function() {
// return (this.genrand_int32() + 0.5)*(1.0/4294967296.0);
// /* divided by 2^32 */
//}
/* generates a random number on [0,1) with 53-bit resolution*/
//MersenneTwister.prototype.genrand_res53 = function() {
// var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
// return(a*67108864.0+b)*(1.0/9007199254740992.0);
//}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
return MersenneTwister;
});
/*global define*/
define('Core/Math',[
'../ThirdParty/mersenne-twister',
'./defaultValue',
'./defined',
'./DeveloperError'
], function(
MersenneTwister,
defaultValue,
defined,
DeveloperError) {
'use strict';
/**
* Math functions.
*
* @exports CesiumMath
*/
var CesiumMath = {};
/**
* 0.1
* @type {Number}
* @constant
*/
CesiumMath.EPSILON1 = 0.1;
/**
* 0.01
* @type {Number}
* @constant
*/
CesiumMath.EPSILON2 = 0.01;
/**
* 0.001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON3 = 0.001;
/**
* 0.0001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON4 = 0.0001;
/**
* 0.00001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON5 = 0.00001;
/**
* 0.000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON6 = 0.000001;
/**
* 0.0000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON7 = 0.0000001;
/**
* 0.00000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON8 = 0.00000001;
/**
* 0.000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON9 = 0.000000001;
/**
* 0.0000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON10 = 0.0000000001;
/**
* 0.00000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON11 = 0.00000000001;
/**
* 0.000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON12 = 0.000000000001;
/**
* 0.0000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON13 = 0.0000000000001;
/**
* 0.00000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON14 = 0.00000000000001;
/**
* 0.000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON15 = 0.000000000000001;
/**
* 0.0000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON16 = 0.0000000000000001;
/**
* 0.00000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON17 = 0.00000000000000001;
/**
* 0.000000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON18 = 0.000000000000000001;
/**
* 0.0000000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON19 = 0.0000000000000000001;
/**
* 0.00000000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON20 = 0.00000000000000000001;
/**
* 3.986004418e14
* @type {Number}
* @constant
*/
CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;
/**
* Radius of the sun in meters: 6.955e8
* @type {Number}
* @constant
*/
CesiumMath.SOLAR_RADIUS = 6.955e8;
/**
* The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
* Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
* Celestial Mechanics 82: 83-110, 2002.
* @type {Number}
* @constant
*/
CesiumMath.LUNAR_RADIUS = 1737400.0;
/**
* 64 * 1024
* @type {Number}
* @constant
*/
CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;
/**
* Returns the sign of the value; 1 if the value is positive, -1 if the value is
* negative, or 0 if the value is 0.
*
* @param {Number} value The value to return the sign of.
* @returns {Number} The sign of value.
*/
CesiumMath.sign = function(value) {
if (value > 0) {
return 1;
}
if (value < 0) {
return -1;
}
return 0;
};
/**
* Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
* This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
* 0.0 when the input value is 0.0.
* @param {Number} value The value to return the sign of.
* @returns {Number} The sign of value.
*/
CesiumMath.signNotZero = function(value) {
return value < 0.0 ? -1.0 : 1.0;
};
/**
* Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMax]
* @param {Number} value The scalar value in the range [-1.0, 1.0]
* @param {Number} [rangeMax=255] The maximum value in the mapped range, 255 by default.
* @returns {Number} A SNORM value, where 0 maps to -1.0 and rangeMax maps to 1.0.
*
* @see CesiumMath.fromSNorm
*/
CesiumMath.toSNorm = function(value, rangeMax) {
rangeMax = defaultValue(rangeMax, 255);
return Math.round((CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * rangeMax);
};
/**
* Converts a SNORM value in the range [0, rangeMax] to a scalar in the range [-1.0, 1.0].
* @param {Number} value SNORM value in the range [0, 255]
* @param {Number} [rangeMax=255] The maximum value in the SNORM range, 255 by default.
* @returns {Number} Scalar in the range [-1.0, 1.0].
*
* @see CesiumMath.toSNorm
*/
CesiumMath.fromSNorm = function(value, rangeMax) {
rangeMax = defaultValue(rangeMax, 255);
return CesiumMath.clamp(value, 0.0, rangeMax) / rangeMax * 2.0 - 1.0;
};
/**
* Returns the hyperbolic sine of a number.
* The hyperbolic sine of <em>value</em> is defined to be
* (<em>e<sup>x</sup> - e<sup>-x</sup></em>)/2.0
* where <i>e</i> is Euler's number, approximately 2.71828183.
*
* <p>Special cases:
* <ul>
* <li>If the argument is NaN, then the result is NaN.</li>
*
* <li>If the argument is infinite, then the result is an infinity
* with the same sign as the argument.</li>
*
* <li>If the argument is zero, then the result is a zero with the
* same sign as the argument.</li>
* </ul>
*</p>
*
* @param {Number} value The number whose hyperbolic sine is to be returned.
* @returns {Number} The hyperbolic sine of <code>value</code>.
*/
CesiumMath.sinh = function(value) {
var part1 = Math.pow(Math.E, value);
var part2 = Math.pow(Math.E, -1.0 * value);
return (part1 - part2) * 0.5;
};
/**
* Returns the hyperbolic cosine of a number.
* The hyperbolic cosine of <strong>value</strong> is defined to be
* (<em>e<sup>x</sup> + e<sup>-x</sup></em>)/2.0
* where <i>e</i> is Euler's number, approximately 2.71828183.
*
* <p>Special cases:
* <ul>
* <li>If the argument is NaN, then the result is NaN.</li>
*
* <li>If the argument is infinite, then the result is positive infinity.</li>
*
* <li>If the argument is zero, then the result is 1.0.</li>
* </ul>
*</p>
*
* @param {Number} value The number whose hyperbolic cosine is to be returned.
* @returns {Number} The hyperbolic cosine of <code>value</code>.
*/
CesiumMath.cosh = function(value) {
var part1 = Math.pow(Math.E, value);
var part2 = Math.pow(Math.E, -1.0 * value);
return (part1 + part2) * 0.5;
};
/**
* Computes the linear interpolation of two values.
*
* @param {Number} p The start value to interpolate.
* @param {Number} q The end value to interpolate.
* @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
* @returns {Number} The linearly interpolated value.
*
* @example
* var n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
*/
CesiumMath.lerp = function(p, q, time) {
return ((1.0 - time) * p) + (time * q);
};
/**
* pi
*
* @type {Number}
* @constant
*/
CesiumMath.PI = Math.PI;
/**
* 1/pi
*
* @type {Number}
* @constant
*/
CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
/**
* pi/2
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_TWO = Math.PI * 0.5;
/**
* pi/3
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
/**
* pi/4
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
/**
* pi/6
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
/**
* 3pi/2
*
* @type {Number}
* @constant
*/
CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) * 0.5;
/**
* 2pi
*
* @type {Number}
* @constant
*/
CesiumMath.TWO_PI = 2.0 * Math.PI;
/**
* 1/2pi
*
* @type {Number}
* @constant
*/
CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
/**
* The number of radians in a degree.
*
* @type {Number}
* @constant
* @default Math.PI / 180.0
*/
CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;
/**
* The number of degrees in a radian.
*
* @type {Number}
* @constant
* @default 180.0 / Math.PI
*/
CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;
/**
* The number of radians in an arc second.
*
* @type {Number}
* @constant
* @default {@link CesiumMath.RADIANS_PER_DEGREE} / 3600.0
*/
CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;
/**
* Converts degrees to radians.
* @param {Number} degrees The angle to convert in degrees.
* @returns {Number} The corresponding angle in radians.
*/
CesiumMath.toRadians = function(degrees) {
if (!defined(degrees)) {
throw new DeveloperError('degrees is required.');
}
return degrees * CesiumMath.RADIANS_PER_DEGREE;
};
/**
* Converts radians to degrees.
* @param {Number} radians The angle to convert in radians.
* @returns {Number} The corresponding angle in degrees.
*/
CesiumMath.toDegrees = function(radians) {
if (!defined(radians)) {
throw new DeveloperError('radians is required.');
}
return radians * CesiumMath.DEGREES_PER_RADIAN;
};
/**
* Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
*
* @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
* @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
*
* @example
* // Convert 270 degrees to -90 degrees longitude
* var longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
*/
CesiumMath.convertLongitudeRange = function(angle) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
var twoPi = CesiumMath.TWO_PI;
var simplified = angle - Math.floor(angle / twoPi) * twoPi;
if (simplified < -Math.PI) {
return simplified + twoPi;
}
if (simplified >= Math.PI) {
return simplified - twoPi;
}
return simplified;
};
/**
* Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
* Useful for sanitizing data before use in objects requiring correct range.
*
* @param {Number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
* @returns {Number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
*
* @example
* // Clamp 108 degrees latitude to 90 degrees latitude
* var latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
*/
CesiumMath.clampToLatitudeRange = function(angle) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
return CesiumMath.clamp(angle, -1*CesiumMath.PI_OVER_TWO, CesiumMath.PI_OVER_TWO);
};
/**
* Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
*
* @param {Number} angle in radians
* @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
*/
CesiumMath.negativePiToPi = function(angle) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
return CesiumMath.zeroToTwoPi(angle + CesiumMath.PI) - CesiumMath.PI;
};
/**
* Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
*
* @param {Number} angle in radians
* @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
*/
CesiumMath.zeroToTwoPi = function(angle) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
var mod = CesiumMath.mod(angle, CesiumMath.TWO_PI);
if (Math.abs(mod) < CesiumMath.EPSILON14 && Math.abs(angle) > CesiumMath.EPSILON14) {
return CesiumMath.TWO_PI;
}
return mod;
};
/**
* The modulo operation that also works for negative dividends.
*
* @param {Number} m The dividend.
* @param {Number} n The divisor.
* @returns {Number} The remainder.
*/
CesiumMath.mod = function(m, n) {
if (!defined(m)) {
throw new DeveloperError('m is required.');
}
if (!defined(n)) {
throw new DeveloperError('n is required.');
}
return ((m % n) + n) % n;
};
/**
* Determines if two values are equal using an absolute or relative tolerance test. This is useful
* to avoid problems due to roundoff error when comparing floating-point values directly. The values are
* first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
* Use this test if you are unsure of the magnitudes of left and right.
*
* @param {Number} left The first value to compare.
* @param {Number} right The other value to compare.
* @param {Number} relativeEpsilon The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
* @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
*
* @example
* var a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
* var b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
* var c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
* var d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
*/
CesiumMath.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
if (!defined(left)) {
throw new DeveloperError('left is required.');
}
if (!defined(right)) {
throw new DeveloperError('right is required.');
}
if (!defined(relativeEpsilon)) {
throw new DeveloperError('relativeEpsilon is required.');
}
absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
var absDiff = Math.abs(left - right);
return absDiff <= absoluteEpsilon || absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right));
};
var factorials = [1];
/**
* Computes the factorial of the provided number.
*
* @param {Number} n The number whose factorial is to be computed.
* @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
*
* @example
* //Compute 7!, which is equal to 5040
* var computedFactorial = Cesium.Math.factorial(7);
*
* @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
*/
CesiumMath.factorial = function(n) {
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
var length = factorials.length;
if (n >= length) {
var sum = factorials[length - 1];
for (var i = length; i <= n; i++) {
factorials.push(sum * i);
}
}
return factorials[n];
};
/**
* Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
*
* @param {Number} [n] The number to be incremented.
* @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
* @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
* @returns {Number} The incremented number.
*
* @exception {DeveloperError} Maximum value must be greater than minimum value.
*
* @example
* var n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
* var n = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
*/
CesiumMath.incrementWrap = function(n, maximumValue, minimumValue) {
minimumValue = defaultValue(minimumValue, 0.0);
if (!defined(n)) {
throw new DeveloperError('n is required.');
}
if (maximumValue <= minimumValue) {
throw new DeveloperError('maximumValue must be greater than minimumValue.');
}
++n;
if (n > maximumValue) {
n = minimumValue;
}
return n;
};
/**
* Determines if a positive integer is a power of two.
*
* @param {Number} n The positive integer to test.
* @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @example
* var t = Cesium.Math.isPowerOfTwo(16); // true
* var f = Cesium.Math.isPowerOfTwo(20); // false
*/
CesiumMath.isPowerOfTwo = function(n) {
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
return (n !== 0) && ((n & (n - 1)) === 0);
};
/**
* Computes the next power-of-two integer greater than or equal to the provided positive integer.
*
* @param {Number} n The positive integer to test.
* @returns {Number} The next power-of-two integer.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @example
* var n = Cesium.Math.nextPowerOfTwo(29); // 32
* var m = Cesium.Math.nextPowerOfTwo(32); // 32
*/
CesiumMath.nextPowerOfTwo = function(n) {
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
// From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
--n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
++n;
return n;
};
/**
* Constraint a value to lie between two values.
*
* @param {Number} value The value to constrain.
* @param {Number} min The minimum value.
* @param {Number} max The maximum value.
* @returns {Number} The value clamped so that min <= value <= max.
*/
CesiumMath.clamp = function(value, min, max) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(min)) {
throw new DeveloperError('min is required.');
}
if (!defined(max)) {
throw new DeveloperError('max is required.');
}
return value < min ? min : value > max ? max : value;
};
var randomNumberGenerator = new MersenneTwister();
/**
* Sets the seed used by the random number generator
* in {@link CesiumMath#nextRandomNumber}.
*
* @param {Number} seed An integer used as the seed.
*/
CesiumMath.setRandomNumberSeed = function(seed) {
if (!defined(seed)) {
throw new DeveloperError('seed is required.');
}
randomNumberGenerator = new MersenneTwister(seed);
};
/**
* Generates a random number in the range of [0.0, 1.0)
* using a Mersenne twister.
*
* @returns {Number} A random number in the range of [0.0, 1.0).
*
* @see CesiumMath.setRandomNumberSeed
* @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
*/
CesiumMath.nextRandomNumber = function() {
return randomNumberGenerator.random();
};
/**
* Computes <code>Math.acos(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
* so that the function will never return NaN.
*
* @param {Number} value The value for which to compute acos.
* @returns {Number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
* whichever is closer, if the value is outside the range.
*/
CesiumMath.acosClamped = function(value) {
if (!defined(value)) {
throw new DeveloperError('value is required.');
}
return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
};
/**
* Computes <code>Math.asin(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
* so that the function will never return NaN.
*
* @param {Number} value The value for which to compute asin.
* @returns {Number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
* whichever is closer, if the value is outside the range.
*/
CesiumMath.asinClamped = function(value) {
if (!defined(value)) {
throw new DeveloperError('value is required.');
}
return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
};
/**
* Finds the chord length between two points given the circle's radius and the angle between the points.
*
* @param {Number} angle The angle between the two points.
* @param {Number} radius The radius of the circle.
* @returns {Number} The chord length.
*/
CesiumMath.chordLength = function(angle, radius) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
if (!defined(radius)) {
throw new DeveloperError('radius is required.');
}
return 2.0 * radius * Math.sin(angle * 0.5);
};
/**
* Finds the logarithm of a number to a base.
*
* @param {Number} number The number.
* @param {Number} base The base.
* @returns {Number} The result.
*/
CesiumMath.logBase = function(number, base) {
if (!defined(number)) {
throw new DeveloperError('number is required.');
}
if (!defined(base)) {
throw new DeveloperError('base is required.');
}
return Math.log(number) / Math.log(base);
};
/**
* @private
*/
CesiumMath.fog = function(distanceToCamera, density) {
var scalar = distanceToCamera * density;
return 1.0 - Math.exp(-(scalar * scalar));
};
return CesiumMath;
});
/*global define*/
define('Core/Cartesian3',[
'./Check',
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
Check,
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
'use strict';
/**
* A 3D Cartesian point.
* @alias Cartesian3
* @constructor
*
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
* @param {Number} [z=0.0] The Z component.
*
* @see Cartesian2
* @see Cartesian4
* @see Packable
*/
function Cartesian3(x, y, z) {
/**
* The X component.
* @type {Number}
* @default 0.0
*/
this.x = defaultValue(x, 0.0);
/**
* The Y component.
* @type {Number}
* @default 0.0
*/
this.y = defaultValue(y, 0.0);
/**
* The Z component.
* @type {Number}
* @default 0.0
*/
this.z = defaultValue(z, 0.0);
}
/**
* Converts the provided Spherical into Cartesian3 coordinates.
*
* @param {Spherical} spherical The Spherical to be converted to Cartesian3.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.fromSpherical = function(spherical, result) {
Check.typeOf.object('spherical', spherical);
if (!defined(result)) {
result = new Cartesian3();
}
var clock = spherical.clock;
var cone = spherical.cone;
var magnitude = defaultValue(spherical.magnitude, 1.0);
var radial = magnitude * Math.sin(cone);
result.x = radial * Math.cos(clock);
result.y = radial * Math.sin(clock);
result.z = magnitude * Math.cos(cone);
return result;
};
/**
* Creates a Cartesian3 instance from x, y and z coordinates.
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.fromElements = function(x, y, z, result) {
if (!defined(result)) {
return new Cartesian3(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Duplicates a Cartesian3 instance.
*
* @param {Cartesian3} cartesian The Cartesian to duplicate.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
Cartesian3.clone = function(cartesian, result) {
if (!defined(cartesian)) {
return undefined;
}
if (!defined(result)) {
return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
}
result.x = cartesian.x;
result.y = cartesian.y;
result.z = cartesian.z;
return result;
};
/**
* Creates a Cartesian3 instance from an existing Cartesian4. This simply takes the
* x, y, and z properties of the Cartesian4 and drops w.
* @function
*
* @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.fromCartesian4 = Cartesian3.clone;
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Cartesian3.packedLength = 3;
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian3} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Cartesian3.pack = function(value, array, startingIndex) {
Check.typeOf.object('value', value);
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex] = value.z;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian3} [result] The object into which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.unpack = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Cartesian3();
}
result.x = array[startingIndex++];
result.y = array[startingIndex++];
result.z = array[startingIndex];
return result;
};
/**
* Flattens an array of Cartesian3s into an array of components.
*
* @param {Cartesian3[]} array The array of cartesians to pack.
* @param {Number[]} result The array onto which to store the result.
* @returns {Number[]} The packed array.
*/
Cartesian3.packArray = function(array, result) {
Check.defined('array', array);
var length = array.length;
if (!defined(result)) {
result = new Array(length * 3);
} else {
result.length = length * 3;
}
for (var i = 0; i < length; ++i) {
Cartesian3.pack(array[i], result, i * 3);
}
return result;
};
/**
* Unpacks an array of cartesian components into an array of Cartesian3s.
*
* @param {Number[]} array The array of components to unpack.
* @param {Cartesian3[]} result The array onto which to store the result.
* @returns {Cartesian3[]} The unpacked array.
*/
Cartesian3.unpackArray = function(array, result) {
Check.defined('array', array);
Check.typeOf.number.greaterThanOrEquals('array.length', array.length, 3);
if (array.length % 3 !== 0) {
throw new DeveloperError('array length must be a multiple of 3.');
}
var length = array.length;
if (!defined(result)) {
result = new Array(length / 3);
} else {
result.length = length / 3;
}
for (var i = 0; i < length; i += 3) {
var index = i / 3;
result[index] = Cartesian3.unpack(array, i, result[index]);
}
return result;
};
/**
* Creates a Cartesian3 from three consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*
* @example
* // Create a Cartesian3 with (1.0, 2.0, 3.0)
* var v = [1.0, 2.0, 3.0];
* var p = Cesium.Cartesian3.fromArray(v);
*
* // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
* var p2 = Cesium.Cartesian3.fromArray(v2, 2);
*/
Cartesian3.fromArray = Cartesian3.unpack;
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian3} cartesian The cartesian to use.
* @returns {Number} The value of the maximum component.
*/
Cartesian3.maximumComponent = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return Math.max(cartesian.x, cartesian.y, cartesian.z);
};
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian3} cartesian The cartesian to use.
* @returns {Number} The value of the minimum component.
*/
Cartesian3.minimumComponent = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return Math.min(cartesian.x, cartesian.y, cartesian.z);
};
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian3} first A cartesian to compare.
* @param {Cartesian3} second A cartesian to compare.
* @param {Cartesian3} result The object into which to store the result.
* @returns {Cartesian3} A cartesian with the minimum components.
*/
Cartesian3.minimumByComponent = function(first, second, result) {
Check.typeOf.object('first', first);
Check.typeOf.object('second', second);
Check.typeOf.object('result', result);
result.x = Math.min(first.x, second.x);
result.y = Math.min(first.y, second.y);
result.z = Math.min(first.z, second.z);
return result;
};
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian3} first A cartesian to compare.
* @param {Cartesian3} second A cartesian to compare.
* @param {Cartesian3} result The object into which to store the result.
* @returns {Cartesian3} A cartesian with the maximum components.
*/
Cartesian3.maximumByComponent = function(first, second, result) {
Check.typeOf.object('first', first);
Check.typeOf.object('second', second);
Check.typeOf.object('result', result);
result.x = Math.max(first.x, second.x);
result.y = Math.max(first.y, second.y);
result.z = Math.max(first.z, second.z);
return result;
};
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {Number} The squared magnitude.
*/
Cartesian3.magnitudeSquared = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z;
};
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {Number} The magnitude.
*/
Cartesian3.magnitude = function(cartesian) {
return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
};
var distanceScratch = new Cartesian3();
/**
* Computes the distance between two points.
*
* @param {Cartesian3} left The first point to compute the distance from.
* @param {Cartesian3} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 1.0
* var d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
*/
Cartesian3.distance = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Cartesian3.subtract(left, right, distanceScratch);
return Cartesian3.magnitude(distanceScratch);
};
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
*
* @param {Cartesian3} left The first point to compute the distance from.
* @param {Cartesian3} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* var d = Cesium.Cartesian3.distanceSquared(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
*/
Cartesian3.distanceSquared = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Cartesian3.subtract(left, right, distanceScratch);
return Cartesian3.magnitudeSquared(distanceScratch);
};
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian to be normalized.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.normalize = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var magnitude = Cartesian3.magnitude(cartesian);
result.x = cartesian.x / magnitude;
result.y = cartesian.y / magnitude;
result.z = cartesian.z / magnitude;
if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) {
throw new DeveloperError('normalized result is not a number');
}
return result;
};
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @returns {Number} The dot product.
*/
Cartesian3.dot = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
return left.x * right.x + left.y * right.y + left.z * right.z;
};
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.multiplyComponents = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x * right.x;
result.y = left.y * right.y;
result.z = left.z * right.z;
return result;
};
/**
* Computes the componentwise quotient of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.divideComponents = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x / right.x;
result.y = left.y / right.y;
result.z = left.z / right.z;
return result;
};
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.add = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x + right.x;
result.y = left.y + right.y;
result.z = left.z + right.z;
return result;
};
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.subtract = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x - right.x;
result.y = left.y - right.y;
result.z = left.z - right.z;
return result;
};
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian3} cartesian The Cartesian to be scaled.
* @param {Number} scalar The scalar to multiply with.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.multiplyByScalar = function(cartesian, scalar, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result.x = cartesian.x * scalar;
result.y = cartesian.y * scalar;
result.z = cartesian.z * scalar;
return result;
};
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian3} cartesian The Cartesian to be divided.
* @param {Number} scalar The scalar to divide by.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.divideByScalar = function(cartesian, scalar, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result.x = cartesian.x / scalar;
result.y = cartesian.y / scalar;
result.z = cartesian.z / scalar;
return result;
};
/**
* Negates the provided Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian to be negated.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.negate = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result.x = -cartesian.x;
result.y = -cartesian.y;
result.z = -cartesian.z;
return result;
};
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.abs = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result.x = Math.abs(cartesian.x);
result.y = Math.abs(cartesian.y);
result.z = Math.abs(cartesian.z);
return result;
};
var lerpScratch = new Cartesian3();
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian3} start The value corresponding to t at 0.0.
* @param {Cartesian3} end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.lerp = function(start, end, t, result) {
Check.typeOf.object('start', start);
Check.typeOf.object('end', end);
Check.typeOf.number('t', t);
Check.typeOf.object('result', result);
Cartesian3.multiplyByScalar(end, t, lerpScratch);
result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
return Cartesian3.add(lerpScratch, result, result);
};
var angleBetweenScratch = new Cartesian3();
var angleBetweenScratch2 = new Cartesian3();
/**
* Returns the angle, in radians, between the provided Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @returns {Number} The angle between the Cartesians.
*/
Cartesian3.angleBetween = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Cartesian3.normalize(left, angleBetweenScratch);
Cartesian3.normalize(right, angleBetweenScratch2);
var cosine = Cartesian3.dot(angleBetweenScratch, angleBetweenScratch2);
var sine = Cartesian3.magnitude(Cartesian3.cross(angleBetweenScratch, angleBetweenScratch2, angleBetweenScratch));
return Math.atan2(sine, cosine);
};
var mostOrthogonalAxisScratch = new Cartesian3();
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The most orthogonal axis.
*/
Cartesian3.mostOrthogonalAxis = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch);
Cartesian3.abs(f, f);
if (f.x <= f.y) {
if (f.x <= f.z) {
result = Cartesian3.clone(Cartesian3.UNIT_X, result);
} else {
result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
}
} else {
if (f.y <= f.z) {
result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
} else {
result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
}
}
return result;
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian3} [left] The first Cartesian.
* @param {Cartesian3} [right] The second Cartesian.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartesian3.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.x === right.x) &&
(left.y === right.y) &&
(left.z === right.z));
};
/**
* @private
*/
Cartesian3.equalsArray = function(cartesian, array, offset) {
return cartesian.x === array[offset] &&
cartesian.y === array[offset + 1] &&
cartesian.z === array[offset + 2];
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian3} [left] The first Cartesian.
* @param {Cartesian3} [right] The second Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian3.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return (left === right) ||
(defined(left) &&
defined(right) &&
CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon));
};
/**
* Computes the cross (outer) product of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The cross product.
*/
Cartesian3.cross = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
var leftX = left.x;
var leftY = left.y;
var leftZ = left.z;
var rightX = right.x;
var rightY = right.y;
var rightZ = right.z;
var x = leftY * rightZ - leftZ * rightY;
var y = leftZ * rightX - leftX * rightZ;
var z = leftX * rightY - leftY * rightX;
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Returns a Cartesian3 position from longitude and latitude values given in degrees.
*
* @param {Number} longitude The longitude, in degrees
* @param {Number} latitude The latitude, in degrees
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The position
*
* @example
* var position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
*/
Cartesian3.fromDegrees = function(longitude, latitude, height, ellipsoid, result) {
Check.typeOf.number('longitude', longitude);
Check.typeOf.number('latitude', latitude);
longitude = CesiumMath.toRadians(longitude);
latitude = CesiumMath.toRadians(latitude);
return Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result);
};
var scratchN = new Cartesian3();
var scratchK = new Cartesian3();
var wgs84RadiiSquared = new Cartesian3(6378137.0 * 6378137.0, 6378137.0 * 6378137.0, 6356752.3142451793 * 6356752.3142451793);
/**
* Returns a Cartesian3 position from longitude and latitude values given in radians.
*
* @param {Number} longitude The longitude, in radians
* @param {Number} latitude The latitude, in radians
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The position
*
* @example
* var position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
*/
Cartesian3.fromRadians = function(longitude, latitude, height, ellipsoid, result) {
Check.typeOf.number('longitude', longitude);
Check.typeOf.number('latitude', latitude);
height = defaultValue(height, 0.0);
var radiiSquared = defined(ellipsoid) ? ellipsoid.radiiSquared : wgs84RadiiSquared;
var cosLatitude = Math.cos(latitude);
scratchN.x = cosLatitude * Math.cos(longitude);
scratchN.y = cosLatitude * Math.sin(longitude);
scratchN.z = Math.sin(latitude);
scratchN = Cartesian3.normalize(scratchN, scratchN);
Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
var gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.add(scratchK, scratchN, result);
};
/**
* Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
*
* @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
*/
Cartesian3.fromDegreesArray = function(coordinates, ellipsoid, result) {
Check.defined('coordinates', coordinates);
if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
}
var length = coordinates.length;
if (!defined(result)) {
result = new Array(length / 2);
} else {
result.length = length / 2;
}
for (var i = 0; i < length; i += 2) {
var longitude = coordinates[i];
var latitude = coordinates[i + 1];
var index = i / 2;
result[index] = Cartesian3.fromDegrees(longitude, latitude, 0, ellipsoid, result[index]);
}
return result;
};
/**
* Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
*
* @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
*/
Cartesian3.fromRadiansArray = function(coordinates, ellipsoid, result) {
Check.defined('coordinates', coordinates);
if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
}
var length = coordinates.length;
if (!defined(result)) {
result = new Array(length / 2);
} else {
result.length = length / 2;
}
for (var i = 0; i < length; i += 2) {
var longitude = coordinates[i];
var latitude = coordinates[i + 1];
var index = i / 2;
result[index] = Cartesian3.fromRadians(longitude, latitude, 0, ellipsoid, result[index]);
}
return result;
};
/**
* Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
*
* @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
*/
Cartesian3.fromDegreesArrayHeights = function(coordinates, ellipsoid, result) {
Check.defined('coordinates', coordinates);
if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
}
var length = coordinates.length;
if (!defined(result)) {
result = new Array(length / 3);
} else {
result.length = length / 3;
}
for (var i = 0; i < length; i += 3) {
var longitude = coordinates[i];
var latitude = coordinates[i + 1];
var height = coordinates[i + 2];
var index = i / 3;
result[index] = Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid, result[index]);
}
return result;
};
/**
* Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
*
* @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
*/
Cartesian3.fromRadiansArrayHeights = function(coordinates, ellipsoid, result) {
Check.defined('coordinates', coordinates);
if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
}
var length = coordinates.length;
if (!defined(result)) {
result = new Array(length / 3);
} else {
result.length = length / 3;
}
for (var i = 0; i < length; i += 3) {
var longitude = coordinates[i];
var latitude = coordinates[i + 1];
var height = coordinates[i + 2];
var index = i / 3;
result[index] = Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result[index]);
}
return result;
};
/**
* An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.ZERO = freezeObject(new Cartesian3(0.0, 0.0, 0.0));
/**
* An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.UNIT_X = freezeObject(new Cartesian3(1.0, 0.0, 0.0));
/**
* An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.UNIT_Y = freezeObject(new Cartesian3(0.0, 1.0, 0.0));
/**
* An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.UNIT_Z = freezeObject(new Cartesian3(0.0, 0.0, 1.0));
/**
* Duplicates this Cartesian3 instance.
*
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.prototype.clone = function(result) {
return Cartesian3.clone(this, result);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian3} [right] The right hand side Cartesian.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Cartesian3.prototype.equals = function(right) {
return Cartesian3.equals(this, right);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian3} [right] The right hand side Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian3.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return Cartesian3.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
};
/**
* Creates a string representing this Cartesian in the format '(x, y, z)'.
*
* @returns {String} A string representing this Cartesian in the format '(x, y, z)'.
*/
Cartesian3.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
};
return Cartesian3;
});
/*global define*/
define('Core/scaleToGeodeticSurface',[
'./Cartesian3',
'./defined',
'./DeveloperError',
'./Math'
], function(
Cartesian3,
defined,
DeveloperError,
CesiumMath) {
'use strict';
var scaleToGeodeticSurfaceIntersection = new Cartesian3();
var scaleToGeodeticSurfaceGradient = new Cartesian3();
/**
* Scales the provided Cartesian position along the geodetic surface normal
* so that it is on the surface of this ellipsoid. If the position is
* at the center of the ellipsoid, this function returns undefined.
*
* @param {Cartesian3} cartesian The Cartesian position to scale.
* @param {Cartesian3} oneOverRadii One over radii of the ellipsoid.
* @param {Cartesian3} oneOverRadiiSquared One over radii squared of the ellipsoid.
* @param {Number} centerToleranceSquared Tolerance for closeness to the center.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
*
* @exports scaleToGeodeticSurface
*
* @private
*/
function scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
if (!defined(oneOverRadii)) {
throw new DeveloperError('oneOverRadii is required.');
}
if (!defined(oneOverRadiiSquared)) {
throw new DeveloperError('oneOverRadiiSquared is required.');
}
if (!defined(centerToleranceSquared)) {
throw new DeveloperError('centerToleranceSquared is required.');
}
var positionX = cartesian.x;
var positionY = cartesian.y;
var positionZ = cartesian.z;
var oneOverRadiiX = oneOverRadii.x;
var oneOverRadiiY = oneOverRadii.y;
var oneOverRadiiZ = oneOverRadii.z;
var x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
var y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
var z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
// Compute the squared ellipsoid norm.
var squaredNorm = x2 + y2 + z2;
var ratio = Math.sqrt(1.0 / squaredNorm);
// As an initial approximation, assume that the radial intersection is the projection point.
var intersection = Cartesian3.multiplyByScalar(cartesian, ratio, scaleToGeodeticSurfaceIntersection);
// If the position is near the center, the iteration will not converge.
if (squaredNorm < centerToleranceSquared) {
return !isFinite(ratio) ? undefined : Cartesian3.clone(intersection, result);
}
var oneOverRadiiSquaredX = oneOverRadiiSquared.x;
var oneOverRadiiSquaredY = oneOverRadiiSquared.y;
var oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
// Use the gradient at the intersection point in place of the true unit normal.
// The difference in magnitude will be absorbed in the multiplier.
var gradient = scaleToGeodeticSurfaceGradient;
gradient.x = intersection.x * oneOverRadiiSquaredX * 2.0;
gradient.y = intersection.y * oneOverRadiiSquaredY * 2.0;
gradient.z = intersection.z * oneOverRadiiSquaredZ * 2.0;
// Compute the initial guess at the normal vector multiplier, lambda.
var lambda = (1.0 - ratio) * Cartesian3.magnitude(cartesian) / (0.5 * Cartesian3.magnitude(gradient));
var correction = 0.0;
var func;
var denominator;
var xMultiplier;
var yMultiplier;
var zMultiplier;
var xMultiplier2;
var yMultiplier2;
var zMultiplier2;
var xMultiplier3;
var yMultiplier3;
var zMultiplier3;
do {
lambda -= correction;
xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
xMultiplier2 = xMultiplier * xMultiplier;
yMultiplier2 = yMultiplier * yMultiplier;
zMultiplier2 = zMultiplier * zMultiplier;
xMultiplier3 = xMultiplier2 * xMultiplier;
yMultiplier3 = yMultiplier2 * yMultiplier;
zMultiplier3 = zMultiplier2 * zMultiplier;
func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
// "denominator" here refers to the use of this expression in the velocity and acceleration
// computations in the sections to follow.
denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
var derivative = -2.0 * denominator;
correction = func / derivative;
} while (Math.abs(func) > CesiumMath.EPSILON12);
if (!defined(result)) {
return new Cartesian3(positionX * xMultiplier, positionY * yMultiplier, positionZ * zMultiplier);
}
result.x = positionX * xMultiplier;
result.y = positionY * yMultiplier;
result.z = positionZ * zMultiplier;
return result;
}
return scaleToGeodeticSurface;
});
/*global define*/
define('Core/Cartographic',[
'./Cartesian3',
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math',
'./scaleToGeodeticSurface'
], function(
Cartesian3,
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath,
scaleToGeodeticSurface) {
'use strict';
/**
* A position defined by longitude, latitude, and height.
* @alias Cartographic
* @constructor
*
* @param {Number} [longitude=0.0] The longitude, in radians.
* @param {Number} [latitude=0.0] The latitude, in radians.
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
*
* @see Ellipsoid
*/
function Cartographic(longitude, latitude, height) {
/**
* The longitude, in radians.
* @type {Number}
* @default 0.0
*/
this.longitude = defaultValue(longitude, 0.0);
/**
* The latitude, in radians.
* @type {Number}
* @default 0.0
*/
this.latitude = defaultValue(latitude, 0.0);
/**
* The height, in meters, above the ellipsoid.
* @type {Number}
* @default 0.0
*/
this.height = defaultValue(height, 0.0);
}
/**
* Creates a new Cartographic instance from longitude and latitude
* specified in radians.
*
* @param {Number} longitude The longitude, in radians.
* @param {Number} latitude The latitude, in radians.
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
Cartographic.fromRadians = function(longitude, latitude, height, result) {
if (!defined(longitude)) {
throw new DeveloperError('longitude is required.');
}
if (!defined(latitude)) {
throw new DeveloperError('latitude is required.');
}
height = defaultValue(height, 0.0);
if (!defined(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
/**
* Creates a new Cartographic instance from longitude and latitude
* specified in degrees. The values in the resulting object will
* be in radians.
*
* @param {Number} longitude The longitude, in degrees.
* @param {Number} latitude The latitude, in degrees.
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
Cartographic.fromDegrees = function(longitude, latitude, height, result) {
if (!defined(longitude)) {
throw new DeveloperError('longitude is required.');
}
if (!defined(latitude)) {
throw new DeveloperError('latitude is required.');
}
longitude = CesiumMath.toRadians(longitude);
latitude = CesiumMath.toRadians(latitude);
return Cartographic.fromRadians(longitude, latitude, height, result);
};
var cartesianToCartographicN = new Cartesian3();
var cartesianToCartographicP = new Cartesian3();
var cartesianToCartographicH = new Cartesian3();
var wgs84OneOverRadii = new Cartesian3(1.0 / 6378137.0, 1.0 / 6378137.0, 1.0 / 6356752.3142451793);
var wgs84OneOverRadiiSquared = new Cartesian3(1.0 / (6378137.0 * 6378137.0), 1.0 / (6378137.0 * 6378137.0), 1.0 / (6356752.3142451793 * 6356752.3142451793));
var wgs84CenterToleranceSquared = CesiumMath.EPSILON1;
/**
* Creates a new Cartographic instance from a Cartesian position. The values in the
* resulting object will be in radians.
*
* @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
*/
Cartographic.fromCartesian = function(cartesian, ellipsoid, result) {
var oneOverRadii = defined(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
var oneOverRadiiSquared = defined(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
var centerToleranceSquared = defined(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;
//`cartesian is required.` is thrown from scaleToGeodeticSurface
var p = scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP);
if (!defined(p)) {
return undefined;
}
var n = Cartesian3.multiplyComponents(p, oneOverRadiiSquared, cartesianToCartographicN);
n = Cartesian3.normalize(n, n);
var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
var longitude = Math.atan2(n.y, n.x);
var latitude = Math.asin(n.z);
var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
if (!defined(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
/**
* Duplicates a Cartographic instance.
*
* @param {Cartographic} cartographic The cartographic to duplicate.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
*/
Cartographic.clone = function(cartographic, result) {
if (!defined(cartographic)) {
return undefined;
}
if (!defined(result)) {
return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
}
result.longitude = cartographic.longitude;
result.latitude = cartographic.latitude;
result.height = cartographic.height;
return result;
};
/**
* Compares the provided cartographics componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartographic} [left] The first cartographic.
* @param {Cartographic} [right] The second cartographic.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartographic.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.longitude === right.longitude) &&
(left.latitude === right.latitude) &&
(left.height === right.height));
};
/**
* Compares the provided cartographics componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Cartographic} [left] The first cartographic.
* @param {Cartographic} [right] The second cartographic.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartographic.equalsEpsilon = function(left, right, epsilon) {
if (typeof epsilon !== 'number') {
throw new DeveloperError('epsilon is required and must be a number.');
}
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(Math.abs(left.longitude - right.longitude) <= epsilon) &&
(Math.abs(left.latitude - right.latitude) <= epsilon) &&
(Math.abs(left.height - right.height) <= epsilon));
};
/**
* An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
*
* @type {Cartographic}
* @constant
*/
Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));
/**
* Duplicates this instance.
*
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
Cartographic.prototype.clone = function(result) {
return Cartographic.clone(this, result);
};
/**
* Compares the provided against this cartographic componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartographic} [right] The second cartographic.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartographic.prototype.equals = function(right) {
return Cartographic.equals(this, right);
};
/**
* Compares the provided against this cartographic componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Cartographic} [right] The second cartographic.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
return Cartographic.equalsEpsilon(this, right, epsilon);
};
/**
* Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
*
* @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
*/
Cartographic.prototype.toString = function() {
return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
};
return Cartographic;
});
/*global define*/
define('Core/defineProperties',[
'./defined'
], function(
defined) {
'use strict';
var definePropertyWorks = (function() {
try {
return 'x' in Object.defineProperty({}, 'x', {});
} catch (e) {
return false;
}
})();
/**
* Defines properties on an object, using Object.defineProperties if available,
* otherwise returns the object unchanged. This function should be used in
* setup code to prevent errors from completely halting JavaScript execution
* in legacy browsers.
*
* @private
*
* @exports defineProperties
*/
var defineProperties = Object.defineProperties;
if (!definePropertyWorks || !defined(defineProperties)) {
defineProperties = function(o) {
return o;
};
}
return defineProperties;
});
/*global define*/
define('Core/Ellipsoid',[
'./Cartesian3',
'./Cartographic',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./freezeObject',
'./Math',
'./scaleToGeodeticSurface'
], function(
Cartesian3,
Cartographic,
defaultValue,
defined,
defineProperties,
DeveloperError,
freezeObject,
CesiumMath,
scaleToGeodeticSurface) {
'use strict';
function initialize(ellipsoid, x, y, z) {
x = defaultValue(x, 0.0);
y = defaultValue(y, 0.0);
z = defaultValue(z, 0.0);
if (x < 0.0 || y < 0.0 || z < 0.0) {
throw new DeveloperError('All radii components must be greater than or equal to zero.');
}
ellipsoid._radii = new Cartesian3(x, y, z);
ellipsoid._radiiSquared = new Cartesian3(x * x,
y * y,
z * z);
ellipsoid._radiiToTheFourth = new Cartesian3(x * x * x * x,
y * y * y * y,
z * z * z * z);
ellipsoid._oneOverRadii = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / x,
y === 0.0 ? 0.0 : 1.0 / y,
z === 0.0 ? 0.0 : 1.0 / z);
ellipsoid._oneOverRadiiSquared = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / (x * x),
y === 0.0 ? 0.0 : 1.0 / (y * y),
z === 0.0 ? 0.0 : 1.0 / (z * z));
ellipsoid._minimumRadius = Math.min(x, y, z);
ellipsoid._maximumRadius = Math.max(x, y, z);
ellipsoid._centerToleranceSquared = CesiumMath.EPSILON1;
if (ellipsoid._radiiSquared.z !== 0) {
ellipsoid._sqauredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
}
}
/**
* A quadratic surface defined in Cartesian coordinates by the equation
* <code>(x / a)^2 + (y / b)^2 + (z / c)^2 = 1</code>. Primarily used
* by Cesium to represent the shape of planetary bodies.
*
* Rather than constructing this object directly, one of the provided
* constants is normally used.
* @alias Ellipsoid
* @constructor
*
* @param {Number} [x=0] The radius in the x direction.
* @param {Number} [y=0] The radius in the y direction.
* @param {Number} [z=0] The radius in the z direction.
*
* @exception {DeveloperError} All radii components must be greater than or equal to zero.
*
* @see Ellipsoid.fromCartesian3
* @see Ellipsoid.WGS84
* @see Ellipsoid.UNIT_SPHERE
*/
function Ellipsoid(x, y, z) {
this._radii = undefined;
this._radiiSquared = undefined;
this._radiiToTheFourth = undefined;
this._oneOverRadii = undefined;
this._oneOverRadiiSquared = undefined;
this._minimumRadius = undefined;
this._maximumRadius = undefined;
this._centerToleranceSquared = undefined;
this._sqauredXOverSquaredZ = undefined;
initialize(this, x, y, z);
}
defineProperties(Ellipsoid.prototype, {
/**
* Gets the radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
radii : {
get: function() {
return this._radii;
}
},
/**
* Gets the squared radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
radiiSquared : {
get : function() {
return this._radiiSquared;
}
},
/**
* Gets the radii of the ellipsoid raise to the fourth power.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
radiiToTheFourth : {
get : function() {
return this._radiiToTheFourth;
}
},
/**
* Gets one over the radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
oneOverRadii : {
get : function() {
return this._oneOverRadii;
}
},
/**
* Gets one over the squared radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
oneOverRadiiSquared : {
get : function() {
return this._oneOverRadiiSquared;
}
},
/**
* Gets the minimum radius of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Number}
* @readonly
*/
minimumRadius : {
get : function() {
return this._minimumRadius;
}
},
/**
* Gets the maximum radius of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Number}
* @readonly
*/
maximumRadius : {
get : function() {
return this._maximumRadius;
}
}
});
/**
* Duplicates an Ellipsoid instance.
*
* @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
*/
Ellipsoid.clone = function(ellipsoid, result) {
if (!defined(ellipsoid)) {
return undefined;
}
var radii = ellipsoid._radii;
if (!defined(result)) {
return new Ellipsoid(radii.x, radii.y, radii.z);
}
Cartesian3.clone(radii, result._radii);
Cartesian3.clone(ellipsoid._radiiSquared, result._radiiSquared);
Cartesian3.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
Cartesian3.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
Cartesian3.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
result._minimumRadius = ellipsoid._minimumRadius;
result._maximumRadius = ellipsoid._maximumRadius;
result._centerToleranceSquared = ellipsoid._centerToleranceSquared;
return result;
};
/**
* Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
*
* @param {Cartesian3} [cartesian=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} A new Ellipsoid instance.
*
* @exception {DeveloperError} All radii components must be greater than or equal to zero.
*
* @see Ellipsoid.WGS84
* @see Ellipsoid.UNIT_SPHERE
*/
Ellipsoid.fromCartesian3 = function(cartesian, result) {
if (!defined(result)) {
result = new Ellipsoid();
}
if (!defined(cartesian)) {
return result;
}
initialize(result, cartesian.x, cartesian.y, cartesian.z);
return result;
};
/**
* An Ellipsoid instance initialized to the WGS84 standard.
*
* @type {Ellipsoid}
* @constant
*/
Ellipsoid.WGS84 = freezeObject(new Ellipsoid(6378137.0, 6378137.0, 6356752.3142451793));
/**
* An Ellipsoid instance initialized to radii of (1.0, 1.0, 1.0).
*
* @type {Ellipsoid}
* @constant
*/
Ellipsoid.UNIT_SPHERE = freezeObject(new Ellipsoid(1.0, 1.0, 1.0));
/**
* An Ellipsoid instance initialized to a sphere with the lunar radius.
*
* @type {Ellipsoid}
* @constant
*/
Ellipsoid.MOON = freezeObject(new Ellipsoid(CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS));
/**
* Duplicates an Ellipsoid instance.
*
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} The cloned Ellipsoid.
*/
Ellipsoid.prototype.clone = function(result) {
return Ellipsoid.clone(this, result);
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Ellipsoid.packedLength = Cartesian3.packedLength;
/**
* Stores the provided instance into the provided array.
*
* @param {Ellipsoid} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Ellipsoid.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
Cartesian3.pack(value._radii, array, startingIndex);
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Ellipsoid} [result] The object into which to store the result.
* @returns {Ellipsoid} The modified result parameter or a new Ellipsoid instance if one was not provided.
*/
Ellipsoid.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
var radii = Cartesian3.unpack(array, startingIndex);
return Ellipsoid.fromCartesian3(radii, result);
};
/**
* Computes the unit vector directed from the center of this ellipsoid toward the provided Cartesian position.
* @function
*
* @param {Cartesian3} cartesian The Cartesian for which to to determine the geocentric normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3.normalize;
/**
* Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
*
* @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function(cartographic, result) {
if (!defined(cartographic)) {
throw new DeveloperError('cartographic is required.');
}
var longitude = cartographic.longitude;
var latitude = cartographic.latitude;
var cosLatitude = Math.cos(latitude);
var x = cosLatitude * Math.cos(longitude);
var y = cosLatitude * Math.sin(longitude);
var z = Math.sin(latitude);
if (!defined(result)) {
result = new Cartesian3();
}
result.x = x;
result.y = y;
result.z = z;
return Cartesian3.normalize(result, result);
};
/**
* Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
*
* @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.geodeticSurfaceNormal = function(cartesian, result) {
if (!defined(result)) {
result = new Cartesian3();
}
result = Cartesian3.multiplyComponents(cartesian, this._oneOverRadiiSquared, result);
return Cartesian3.normalize(result, result);
};
var cartographicToCartesianNormal = new Cartesian3();
var cartographicToCartesianK = new Cartesian3();
/**
* Converts the provided cartographic to Cartesian representation.
*
* @param {Cartographic} cartographic The cartographic position.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*
* @example
* //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
* var position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
* var cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
*/
Ellipsoid.prototype.cartographicToCartesian = function(cartographic, result) {
//`cartographic is required` is thrown from geodeticSurfaceNormalCartographic.
var n = cartographicToCartesianNormal;
var k = cartographicToCartesianK;
this.geodeticSurfaceNormalCartographic(cartographic, n);
Cartesian3.multiplyComponents(this._radiiSquared, n, k);
var gamma = Math.sqrt(Cartesian3.dot(n, k));
Cartesian3.divideByScalar(k, gamma, k);
Cartesian3.multiplyByScalar(n, cartographic.height, n);
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.add(k, n, result);
};
/**
* Converts the provided array of cartographics to an array of Cartesians.
*
* @param {Cartographic[]} cartographics An array of cartographic positions.
* @param {Cartesian3[]} [result] The object onto which to store the result.
* @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
*
* @example
* //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
* var positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
* new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
* new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)];
* var cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
*/
Ellipsoid.prototype.cartographicArrayToCartesianArray = function(cartographics, result) {
if (!defined(cartographics)) {
throw new DeveloperError('cartographics is required.');
}
var length = cartographics.length;
if (!defined(result)) {
result = new Array(length);
} else {
result.length = length;
}
for ( var i = 0; i < length; i++) {
result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
}
return result;
};
var cartesianToCartographicN = new Cartesian3();
var cartesianToCartographicP = new Cartesian3();
var cartesianToCartographicH = new Cartesian3();
/**
* Converts the provided cartesian to cartographic representation.
* The cartesian is undefined at the center of the ellipsoid.
*
* @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
*
* @example
* //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
* var position = new Cesium.Cartesian3(17832.12, 83234.52, 952313.73);
* var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
*/
Ellipsoid.prototype.cartesianToCartographic = function(cartesian, result) {
//`cartesian is required.` is thrown from scaleToGeodeticSurface
var p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP);
if (!defined(p)) {
return undefined;
}
var n = this.geodeticSurfaceNormal(p, cartesianToCartographicN);
var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
var longitude = Math.atan2(n.y, n.x);
var latitude = Math.asin(n.z);
var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
if (!defined(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
/**
* Converts the provided array of cartesians to an array of cartographics.
*
* @param {Cartesian3[]} cartesians An array of Cartesian positions.
* @param {Cartographic[]} [result] The object onto which to store the result.
* @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
*
* @example
* //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
* var positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
* new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
* new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
* var cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
*/
Ellipsoid.prototype.cartesianArrayToCartographicArray = function(cartesians, result) {
if (!defined(cartesians)) {
throw new DeveloperError('cartesians is required.');
}
var length = cartesians.length;
if (!defined(result)) {
result = new Array(length);
} else {
result.length = length;
}
for ( var i = 0; i < length; ++i) {
result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
}
return result;
};
/**
* Scales the provided Cartesian position along the geodetic surface normal
* so that it is on the surface of this ellipsoid. If the position is
* at the center of the ellipsoid, this function returns undefined.
*
* @param {Cartesian3} cartesian The Cartesian position to scale.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
*/
Ellipsoid.prototype.scaleToGeodeticSurface = function(cartesian, result) {
return scaleToGeodeticSurface(cartesian, this._oneOverRadii, this._oneOverRadiiSquared, this._centerToleranceSquared, result);
};
/**
* Scales the provided Cartesian position along the geocentric surface normal
* so that it is on the surface of this ellipsoid.
*
* @param {Cartesian3} cartesian The Cartesian position to scale.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.scaleToGeocentricSurface = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
if (!defined(result)) {
result = new Cartesian3();
}
var positionX = cartesian.x;
var positionY = cartesian.y;
var positionZ = cartesian.z;
var oneOverRadiiSquared = this._oneOverRadiiSquared;
var beta = 1.0 / Math.sqrt((positionX * positionX) * oneOverRadiiSquared.x +
(positionY * positionY) * oneOverRadiiSquared.y +
(positionZ * positionZ) * oneOverRadiiSquared.z);
return Cartesian3.multiplyByScalar(cartesian, beta, result);
};
/**
* Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
* its components by the result of {@link Ellipsoid#oneOverRadii}.
*
* @param {Cartesian3} position The position to transform.
* @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian3} The position expressed in the scaled space. The returned instance is the
* one passed as the result parameter if it is not undefined, or a new instance of it is.
*/
Ellipsoid.prototype.transformPositionToScaledSpace = function(position, result) {
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.multiplyComponents(position, this._oneOverRadii, result);
};
/**
* Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
* its components by the result of {@link Ellipsoid#radii}.
*
* @param {Cartesian3} position The position to transform.
* @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian3} The position expressed in the unscaled space. The returned instance is the
* one passed as the result parameter if it is not undefined, or a new instance of it is.
*/
Ellipsoid.prototype.transformPositionFromScaledSpace = function(position, result) {
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.multiplyComponents(position, this._radii, result);
};
/**
* Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Ellipsoid} [right] The other Ellipsoid.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Ellipsoid.prototype.equals = function(right) {
return (this === right) ||
(defined(right) &&
Cartesian3.equals(this._radii, right._radii));
};
/**
* Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
*
* @returns {String} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
*/
Ellipsoid.prototype.toString = function() {
return this._radii.toString();
};
/**
* Computes a point which is the intersection of the surface normal with the z-axis.
*
* @param {Cartesian3} position the position. must be on the surface of the ellipsoid.
* @param {Number} [buffer = 0.0] A buffer to subtract from the ellipsoid size when checking if the point is inside the ellipsoid.
* In earth case, with common earth datums, there is no need for this buffer since the intersection point is always (relatively) very close to the center.
* In WGS84 datum, intersection point is at max z = +-42841.31151331382 (0.673% of z-axis).
* Intersection point could be outside the ellipsoid if the ratio of MajorAxis / AxisOfRotation is bigger than the square root of 2
* @param {Cartesian} [result] The cartesian to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian | undefined} the intersection point if it's inside the ellipsoid, undefined otherwise
*
* @exception {DeveloperError} position is required.
* @exception {DeveloperError} Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y).
* @exception {DeveloperError} Ellipsoid.radii.z must be greater than 0.
*/
Ellipsoid.prototype.getSurfaceNormalIntersectionWithZAxis = function(position, buffer, result) {
if (!defined(position)) {
throw new DeveloperError('position is required.');
}
if (!CesiumMath.equalsEpsilon(this._radii.x, this._radii.y, CesiumMath.EPSILON15)) {
throw new DeveloperError('Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)');
}
if (this._radii.z === 0) {
throw new DeveloperError('Ellipsoid.radii.z must be greater than 0');
}
buffer = defaultValue(buffer, 0.0);
var sqauredXOverSquaredZ = this._sqauredXOverSquaredZ;
if (!defined(result)) {
result = new Cartesian3();
}
result.x = 0.0;
result.y = 0.0;
result.z = position.z * (1 - sqauredXOverSquaredZ);
if (Math.abs(result.z) >= this._radii.z - buffer) {
return undefined;
}
return result;
};
return Ellipsoid;
});
/*global define*/
define('Core/GeographicProjection',[
'./Cartesian3',
'./Cartographic',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./Ellipsoid'
], function(
Cartesian3,
Cartographic,
defaultValue,
defined,
defineProperties,
DeveloperError,
Ellipsoid) {
'use strict';
/**
* A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
* them by the {@link Ellipsoid#maximumRadius}. This projection
* is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
* is also known as EPSG:4326.
*
* @alias GeographicProjection
* @constructor
*
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
*
* @see WebMercatorProjection
*/
function GeographicProjection(ellipsoid) {
this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
}
defineProperties(GeographicProjection.prototype, {
/**
* Gets the {@link Ellipsoid}.
*
* @memberof GeographicProjection.prototype
*
* @type {Ellipsoid}
* @readonly
*/
ellipsoid : {
get : function() {
return this._ellipsoid;
}
}
});
/**
* Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
* X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
* ellipsoid. Z is the unmodified height.
*
* @param {Cartographic} cartographic The coordinates to project.
* @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
GeographicProjection.prototype.project = function(cartographic, result) {
// Actually this is the special case of equidistant cylindrical called the plate carree
var semimajorAxis = this._semimajorAxis;
var x = cartographic.longitude * semimajorAxis;
var y = cartographic.latitude * semimajorAxis;
var z = cartographic.height;
if (!defined(result)) {
return new Cartesian3(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
* coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
* divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
*
* @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
* @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
GeographicProjection.prototype.unproject = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
var longitude = cartesian.x * oneOverEarthSemimajorAxis;
var latitude = cartesian.y * oneOverEarthSemimajorAxis;
var height = cartesian.z;
if (!defined(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
return GeographicProjection;
});
/*global define*/
define('Core/Intersect',[
'./freezeObject'
], function(
freezeObject) {
'use strict';
/**
* This enumerated type is used in determining where, relative to the frustum, an
* object is located. The object can either be fully contained within the frustum (INSIDE),
* partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
* outside of the frustum's 6 planes (OUTSIDE).
*
* @exports Intersect
*/
var Intersect = {
/**
* Represents that an object is not contained within the frustum.
*
* @type {Number}
* @constant
*/
OUTSIDE : -1,
/**
* Represents that an object intersects one of the frustum's planes.
*
* @type {Number}
* @constant
*/
INTERSECTING : 0,
/**
* Represents that an object is fully within the frustum.
*
* @type {Number}
* @constant
*/
INSIDE : 1
};
return freezeObject(Intersect);
});
/*global define*/
define('Core/Interval',[
'./defaultValue'
], function(
defaultValue) {
'use strict';
/**
* Represents the closed interval [start, stop].
* @alias Interval
* @constructor
*
* @param {Number} [start=0.0] The beginning of the interval.
* @param {Number} [stop=0.0] The end of the interval.
*/
function Interval(start, stop) {
/**
* The beginning of the interval.
* @type {Number}
* @default 0.0
*/
this.start = defaultValue(start, 0.0);
/**
* The end of the interval.
* @type {Number}
* @default 0.0
*/
this.stop = defaultValue(stop, 0.0);
}
return Interval;
});
/*global define*/
define('Core/Matrix3',[
'./Cartesian3',
'./Check',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
Cartesian3,
Check,
defaultValue,
defined,
defineProperties,
DeveloperError,
freezeObject,
CesiumMath) {
'use strict';
/**
* A 3x3 matrix, indexable as a column-major order array.
* Constructor parameters are in row-major order for code readability.
* @alias Matrix3
* @constructor
*
* @param {Number} [column0Row0=0.0] The value for column 0, row 0.
* @param {Number} [column1Row0=0.0] The value for column 1, row 0.
* @param {Number} [column2Row0=0.0] The value for column 2, row 0.
* @param {Number} [column0Row1=0.0] The value for column 0, row 1.
* @param {Number} [column1Row1=0.0] The value for column 1, row 1.
* @param {Number} [column2Row1=0.0] The value for column 2, row 1.
* @param {Number} [column0Row2=0.0] The value for column 0, row 2.
* @param {Number} [column1Row2=0.0] The value for column 1, row 2.
* @param {Number} [column2Row2=0.0] The value for column 2, row 2.
*
* @see Matrix3.fromColumnMajorArray
* @see Matrix3.fromRowMajorArray
* @see Matrix3.fromQuaternion
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix2
* @see Matrix4
*/
function Matrix3(column0Row0, column1Row0, column2Row0,
column0Row1, column1Row1, column2Row1,
column0Row2, column1Row2, column2Row2) {
this[0] = defaultValue(column0Row0, 0.0);
this[1] = defaultValue(column0Row1, 0.0);
this[2] = defaultValue(column0Row2, 0.0);
this[3] = defaultValue(column1Row0, 0.0);
this[4] = defaultValue(column1Row1, 0.0);
this[5] = defaultValue(column1Row2, 0.0);
this[6] = defaultValue(column2Row0, 0.0);
this[7] = defaultValue(column2Row1, 0.0);
this[8] = defaultValue(column2Row2, 0.0);
}
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Matrix3.packedLength = 9;
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix3} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Matrix3.pack = function(value, array, startingIndex) {
Check.typeOf.object('value', value);
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex++] = value[3];
array[startingIndex++] = value[4];
array[startingIndex++] = value[5];
array[startingIndex++] = value[6];
array[startingIndex++] = value[7];
array[startingIndex++] = value[8];
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix3} [result] The object into which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
*/
Matrix3.unpack = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Matrix3();
}
result[0] = array[startingIndex++];
result[1] = array[startingIndex++];
result[2] = array[startingIndex++];
result[3] = array[startingIndex++];
result[4] = array[startingIndex++];
result[5] = array[startingIndex++];
result[6] = array[startingIndex++];
result[7] = array[startingIndex++];
result[8] = array[startingIndex++];
return result;
};
/**
* Duplicates a Matrix3 instance.
*
* @param {Matrix3} matrix The matrix to duplicate.
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
*/
Matrix3.clone = function(matrix, result) {
if (!defined(matrix)) {
return undefined;
}
if (!defined(result)) {
return new Matrix3(matrix[0], matrix[3], matrix[6],
matrix[1], matrix[4], matrix[7],
matrix[2], matrix[5], matrix[8]);
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
return result;
};
/**
* Creates a Matrix3 from 9 consecutive elements in an array.
*
* @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
*
* @example
* // Create the Matrix3:
* // [1.0, 2.0, 3.0]
* // [1.0, 2.0, 3.0]
* // [1.0, 2.0, 3.0]
*
* var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
* var m = Cesium.Matrix3.fromArray(v);
*
* // Create same Matrix3 with using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
* var m2 = Cesium.Matrix3.fromArray(v2, 2);
*/
Matrix3.fromArray = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Matrix3();
}
result[0] = array[startingIndex];
result[1] = array[startingIndex + 1];
result[2] = array[startingIndex + 2];
result[3] = array[startingIndex + 3];
result[4] = array[startingIndex + 4];
result[5] = array[startingIndex + 5];
result[6] = array[startingIndex + 6];
result[7] = array[startingIndex + 7];
result[8] = array[startingIndex + 8];
return result;
};
/**
* Creates a Matrix3 instance from a column-major order array.
*
* @param {Number[]} values The column-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
Matrix3.fromColumnMajorArray = function(values, result) {
Check.defined('values', values);
return Matrix3.clone(values, result);
};
/**
* Creates a Matrix3 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {Number[]} values The row-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
Matrix3.fromRowMajorArray = function(values, result) {
Check.defined('values', values);
if (!defined(result)) {
return new Matrix3(values[0], values[1], values[2],
values[3], values[4], values[5],
values[6], values[7], values[8]);
}
result[0] = values[0];
result[1] = values[3];
result[2] = values[6];
result[3] = values[1];
result[4] = values[4];
result[5] = values[7];
result[6] = values[2];
result[7] = values[5];
result[8] = values[8];
return result;
};
/**
* Computes a 3x3 rotation matrix from the provided quaternion.
*
* @param {Quaternion} quaternion the quaternion to use.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
*/
Matrix3.fromQuaternion = function(quaternion, result) {
Check.typeOf.object('quaternion', quaternion);
var x2 = quaternion.x * quaternion.x;
var xy = quaternion.x * quaternion.y;
var xz = quaternion.x * quaternion.z;
var xw = quaternion.x * quaternion.w;
var y2 = quaternion.y * quaternion.y;
var yz = quaternion.y * quaternion.z;
var yw = quaternion.y * quaternion.w;
var z2 = quaternion.z * quaternion.z;
var zw = quaternion.z * quaternion.w;
var w2 = quaternion.w * quaternion.w;
var m00 = x2 - y2 - z2 + w2;
var m01 = 2.0 * (xy - zw);
var m02 = 2.0 * (xz + yw);
var m10 = 2.0 * (xy + zw);
var m11 = -x2 + y2 - z2 + w2;
var m12 = 2.0 * (yz - xw);
var m20 = 2.0 * (xz - yw);
var m21 = 2.0 * (yz + xw);
var m22 = -x2 - y2 + z2 + w2;
if (!defined(result)) {
return new Matrix3(m00, m01, m02,
m10, m11, m12,
m20, m21, m22);
}
result[0] = m00;
result[1] = m10;
result[2] = m20;
result[3] = m01;
result[4] = m11;
result[5] = m21;
result[6] = m02;
result[7] = m12;
result[8] = m22;
return result;
};
/**
* Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
*
* @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
*/
Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
Check.typeOf.object('headingPitchRoll', headingPitchRoll);
var cosTheta = Math.cos(-headingPitchRoll.pitch);
var cosPsi = Math.cos(-headingPitchRoll.heading);
var cosPhi = Math.cos(headingPitchRoll.roll);
var sinTheta = Math.sin(-headingPitchRoll.pitch);
var sinPsi = Math.sin(-headingPitchRoll.heading);
var sinPhi = Math.sin(headingPitchRoll.roll);
var m00 = cosTheta * cosPsi;
var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
var m10 = cosTheta * sinPsi;
var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
var m12 = -sinPhi * cosPsi + cosPhi * sinTheta * sinPsi;
var m20 = -sinTheta;
var m21 = sinPhi * cosTheta;
var m22 = cosPhi * cosTheta;
if (!defined(result)) {
return new Matrix3(m00, m01, m02,
m10, m11, m12,
m20, m21, m22);
}
result[0] = m00;
result[1] = m10;
result[2] = m20;
result[3] = m01;
result[4] = m11;
result[5] = m21;
result[6] = m02;
result[7] = m12;
result[8] = m22;
return result;
};
/**
* Computes a Matrix3 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0]
* // [0.0, 0.0, 9.0]
* var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix3.fromScale = function(scale, result) {
Check.typeOf.object('scale', scale);
if (!defined(result)) {
return new Matrix3(
scale.x, 0.0, 0.0,
0.0, scale.y, 0.0,
0.0, 0.0, scale.z);
}
result[0] = scale.x;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = scale.y;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = scale.z;
return result;
};
/**
* Computes a Matrix3 instance representing a uniform scale.
*
* @param {Number} scale The uniform scale factor.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0]
* // [0.0, 0.0, 2.0]
* var m = Cesium.Matrix3.fromUniformScale(2.0);
*/
Matrix3.fromUniformScale = function(scale, result) {
Check.typeOf.number('scale', scale);
if (!defined(result)) {
return new Matrix3(
scale, 0.0, 0.0,
0.0, scale, 0.0,
0.0, 0.0, scale);
}
result[0] = scale;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = scale;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = scale;
return result;
};
/**
* Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
*
* @param {Cartesian3} vector the vector on the left hand side of the cross product operation.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [0.0, -9.0, 8.0]
* // [9.0, 0.0, -7.0]
* // [-8.0, 7.0, 0.0]
* var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix3.fromCrossProduct = function(vector, result) {
Check.typeOf.object('vector', vector);
if (!defined(result)) {
return new Matrix3(
0.0, -vector.z, vector.y,
vector.z, 0.0, -vector.x,
-vector.y, vector.x, 0.0);
}
result[0] = 0.0;
result[1] = vector.z;
result[2] = -vector.y;
result[3] = -vector.z;
result[4] = 0.0;
result[5] = vector.x;
result[6] = vector.y;
result[7] = -vector.x;
result[8] = 0.0;
return result;
};
/**
* Creates a rotation matrix around the x-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the x-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
Matrix3.fromRotationX = function(angle, result) {
Check.typeOf.number('angle', angle);
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
if (!defined(result)) {
return new Matrix3(
1.0, 0.0, 0.0,
0.0, cosAngle, -sinAngle,
0.0, sinAngle, cosAngle);
}
result[0] = 1.0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = cosAngle;
result[5] = sinAngle;
result[6] = 0.0;
result[7] = -sinAngle;
result[8] = cosAngle;
return result;
};
/**
* Creates a rotation matrix around the y-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the y-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
Matrix3.fromRotationY = function(angle, result) {
Check.typeOf.number('angle', angle);
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
if (!defined(result)) {
return new Matrix3(
cosAngle, 0.0, sinAngle,
0.0, 1.0, 0.0,
-sinAngle, 0.0, cosAngle);
}
result[0] = cosAngle;
result[1] = 0.0;
result[2] = -sinAngle;
result[3] = 0.0;
result[4] = 1.0;
result[5] = 0.0;
result[6] = sinAngle;
result[7] = 0.0;
result[8] = cosAngle;
return result;
};
/**
* Creates a rotation matrix around the z-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the z-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
Matrix3.fromRotationZ = function(angle, result) {
Check.typeOf.number('angle', angle);
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
if (!defined(result)) {
return new Matrix3(
cosAngle, -sinAngle, 0.0,
sinAngle, cosAngle, 0.0,
0.0, 0.0, 1.0);
}
result[0] = cosAngle;
result[1] = sinAngle;
result[2] = 0.0;
result[3] = -sinAngle;
result[4] = cosAngle;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 1.0;
return result;
};
/**
* Creates an Array from the provided Matrix3 instance.
* The array will be in column-major order.
*
* @param {Matrix3} matrix The matrix to use..
* @param {Number[]} [result] The Array onto which to store the result.
* @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
*/
Matrix3.toArray = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
if (!defined(result)) {
return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
return result;
};
/**
* Computes the array index of the element at the provided row and column.
*
* @param {Number} row The zero-based index of the row.
* @param {Number} column The zero-based index of the column.
* @returns {Number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, or 2.
* @exception {DeveloperError} column must be 0, 1, or 2.
*
* @example
* var myMatrix = new Cesium.Matrix3();
* var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
* var column1Row0 = myMatrix[column1Row0Index]
* myMatrix[column1Row0Index] = 10.0;
*/
Matrix3.getElementIndex = function(column, row) {
Check.typeOf.number.greaterThanOrEquals('row', row, 0);
Check.typeOf.number.lessThanOrEquals('row', row, 2);
Check.typeOf.number.greaterThanOrEquals('column', column, 0);
Check.typeOf.number.lessThanOrEquals('column', column, 2);
return column * 3 + row;
};
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.getColumn = function(matrix, index, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 2);
Check.typeOf.object('result', result);
var startIndex = index * 3;
var x = matrix[startIndex];
var y = matrix[startIndex + 1];
var z = matrix[startIndex + 2];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.setColumn = function(matrix, index, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 2);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result = Matrix3.clone(matrix, result);
var startIndex = index * 3;
result[startIndex] = cartesian.x;
result[startIndex + 1] = cartesian.y;
result[startIndex + 2] = cartesian.z;
return result;
};
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.getRow = function(matrix, index, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 2);
Check.typeOf.object('result', result);
var x = matrix[index];
var y = matrix[index + 3];
var z = matrix[index + 6];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.setRow = function(matrix, index, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 2);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result = Matrix3.clone(matrix, result);
result[index] = cartesian.x;
result[index + 3] = cartesian.y;
result[index + 6] = cartesian.z;
return result;
};
var scratchColumn = new Cartesian3();
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix3.getScale = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
return result;
};
var scratchScale = new Cartesian3();
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors.
*
* @param {Matrix3} matrix The matrix.
* @returns {Number} The maximum scale.
*/
Matrix3.getMaximumScale = function(matrix) {
Matrix3.getScale(matrix, scratchScale);
return Cartesian3.maximumComponent(scratchScale);
};
/**
* Computes the product of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.multiply = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column1Row0;
result[4] = column1Row1;
result[5] = column1Row2;
result[6] = column2Row0;
result[7] = column2Row1;
result[8] = column2Row2;
return result;
};
/**
* Computes the sum of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.add = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result[0] = left[0] + right[0];
result[1] = left[1] + right[1];
result[2] = left[2] + right[2];
result[3] = left[3] + right[3];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
return result;
};
/**
* Computes the difference of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.subtract = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result[0] = left[0] - right[0];
result[1] = left[1] - right[1];
result[2] = left[2] - right[2];
result[3] = left[3] - right[3];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
return result;
};
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} cartesian The column.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix3.multiplyByVector = function(matrix, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix3} matrix The matrix.
* @param {Number} scalar The number to multiply by.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.multiplyByScalar = function(matrix, scalar, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
return result;
};
/**
* Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
*
* @param {Matrix3} matrix The matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
*
* @example
* // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
* Cesium.Matrix3.multiplyByScale(m, scale, m);
*
* @see Matrix3.fromScale
* @see Matrix3.multiplyByUniformScale
*/
Matrix3.multiplyByScale = function(matrix, scale, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('scale', scale);
Check.typeOf.object('result', result);
result[0] = matrix[0] * scale.x;
result[1] = matrix[1] * scale.x;
result[2] = matrix[2] * scale.x;
result[3] = matrix[3] * scale.y;
result[4] = matrix[4] * scale.y;
result[5] = matrix[5] * scale.y;
result[6] = matrix[6] * scale.z;
result[7] = matrix[7] * scale.z;
result[8] = matrix[8] * scale.z;
return result;
};
/**
* Creates a negated copy of the provided matrix.
*
* @param {Matrix3} matrix The matrix to negate.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.negate = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result[0] = -matrix[0];
result[1] = -matrix[1];
result[2] = -matrix[2];
result[3] = -matrix[3];
result[4] = -matrix[4];
result[5] = -matrix[5];
result[6] = -matrix[6];
result[7] = -matrix[7];
result[8] = -matrix[8];
return result;
};
/**
* Computes the transpose of the provided matrix.
*
* @param {Matrix3} matrix The matrix to transpose.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.transpose = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
var column0Row0 = matrix[0];
var column0Row1 = matrix[3];
var column0Row2 = matrix[6];
var column1Row0 = matrix[1];
var column1Row1 = matrix[4];
var column1Row2 = matrix[7];
var column2Row0 = matrix[2];
var column2Row1 = matrix[5];
var column2Row2 = matrix[8];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column1Row0;
result[4] = column1Row1;
result[5] = column1Row2;
result[6] = column2Row0;
result[7] = column2Row1;
result[8] = column2Row2;
return result;
};
function computeFrobeniusNorm(matrix) {
var norm = 0.0;
for (var i = 0; i < 9; ++i) {
var temp = matrix[i];
norm += temp * temp;
}
return Math.sqrt(norm);
}
var rowVal = [1, 0, 0];
var colVal = [2, 2, 1];
function offDiagonalFrobeniusNorm(matrix) {
// Computes the "off-diagonal" Frobenius norm.
// Assumes matrix is symmetric.
var norm = 0.0;
for (var i = 0; i < 3; ++i) {
var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
norm += 2.0 * temp * temp;
}
return Math.sqrt(norm);
}
function shurDecomposition(matrix, result) {
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.2 The 2by2 Symmetric Schur Decomposition.
//
// The routine takes a matrix, which is assumed to be symmetric, and
// finds the largest off-diagonal term, and then creates
// a matrix (result) which can be used to help reduce it
var tolerance = CesiumMath.EPSILON15;
var maxDiagonal = 0.0;
var rotAxis = 1;
// find pivot (rotAxis) based on max diagonal of matrix
for (var i = 0; i < 3; ++i) {
var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
if (temp > maxDiagonal) {
rotAxis = i;
maxDiagonal = temp;
}
}
var c = 1.0;
var s = 0.0;
var p = rowVal[rotAxis];
var q = colVal[rotAxis];
if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
var qq = matrix[Matrix3.getElementIndex(q, q)];
var pp = matrix[Matrix3.getElementIndex(p, p)];
var qp = matrix[Matrix3.getElementIndex(q, p)];
var tau = (qq - pp) / 2.0 / qp;
var t;
if (tau < 0.0) {
t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
} else {
t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
}
c = 1.0 / Math.sqrt(1.0 + t * t);
s = t * c;
}
result = Matrix3.clone(Matrix3.IDENTITY, result);
result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
result[Matrix3.getElementIndex(q, p)] = s;
result[Matrix3.getElementIndex(p, q)] = -s;
return result;
}
var jMatrix = new Matrix3();
var jMatrixTranspose = new Matrix3();
/**
* Computes the eigenvectors and eigenvalues of a symmetric matrix.
* <p>
* Returns a diagonal matrix and unitary matrix such that:
* <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
* </p>
* <p>
* The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
* of the unitary matrix are the corresponding eigenvectors.
* </p>
*
* @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
* @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
* @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
*
* @example
* var a = //... symetric matrix
* var result = {
* unitary : new Cesium.Matrix3(),
* diagonal : new Cesium.Matrix3()
* };
* Cesium.Matrix3.computeEigenDecomposition(a, result);
*
* var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
* var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
* Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
*
* var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
* var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
* var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
*/
Matrix3.computeEigenDecomposition = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.3 The Classical Jacobi Algorithm
var tolerance = CesiumMath.EPSILON20;
var maxSweeps = 10;
var count = 0;
var sweep = 0;
if (!defined(result)) {
result = {};
}
var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
shurDecomposition(diagMatrix, jMatrix);
Matrix3.transpose(jMatrix, jMatrixTranspose);
Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
if (++count > 2) {
++sweep;
count = 0;
}
}
return result;
};
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix3} matrix The matrix with signed elements.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.abs = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
return result;
};
/**
* Computes the determinant of the provided matrix.
*
* @param {Matrix3} matrix The matrix to use.
* @returns {Number} The value of the determinant of the matrix.
*/
Matrix3.determinant = function(matrix) {
Check.typeOf.object('matrix', matrix);
var m11 = matrix[0];
var m21 = matrix[3];
var m31 = matrix[6];
var m12 = matrix[1];
var m22 = matrix[4];
var m32 = matrix[7];
var m13 = matrix[2];
var m23 = matrix[5];
var m33 = matrix[8];
return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
};
/**
* Computes the inverse of the provided matrix.
*
* @param {Matrix3} matrix The matrix to invert.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} matrix is not invertible.
*/
Matrix3.inverse = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
var m11 = matrix[0];
var m21 = matrix[1];
var m31 = matrix[2];
var m12 = matrix[3];
var m22 = matrix[4];
var m32 = matrix[5];
var m13 = matrix[6];
var m23 = matrix[7];
var m33 = matrix[8];
var determinant = Matrix3.determinant(matrix);
if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
throw new DeveloperError('matrix is not invertible');
}
result[0] = m22 * m33 - m23 * m32;
result[1] = m23 * m31 - m21 * m33;
result[2] = m21 * m32 - m22 * m31;
result[3] = m13 * m32 - m12 * m33;
result[4] = m11 * m33 - m13 * m31;
result[5] = m12 * m31 - m11 * m32;
result[6] = m12 * m23 - m13 * m22;
result[7] = m13 * m21 - m11 * m23;
result[8] = m11 * m22 - m12 * m21;
var scale = 1.0 / determinant;
return Matrix3.multiplyByScalar(result, scale, result);
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix3} [left] The first matrix.
* @param {Matrix3} [right] The second matrix.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Matrix3.equals = function(left, right) {
return (left === right) ||
(defined(left) &&
defined(right) &&
left[0] === right[0] &&
left[1] === right[1] &&
left[2] === right[2] &&
left[3] === right[3] &&
left[4] === right[4] &&
left[5] === right[5] &&
left[6] === right[6] &&
left[7] === right[7] &&
left[8] === right[8]);
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix3} [left] The first matrix.
* @param {Matrix3} [right] The second matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Matrix3.equalsEpsilon = function(left, right, epsilon) {
Check.typeOf.number('epsilon', epsilon);
return (left === right) ||
(defined(left) &&
defined(right) &&
Math.abs(left[0] - right[0]) <= epsilon &&
Math.abs(left[1] - right[1]) <= epsilon &&
Math.abs(left[2] - right[2]) <= epsilon &&
Math.abs(left[3] - right[3]) <= epsilon &&
Math.abs(left[4] - right[4]) <= epsilon &&
Math.abs(left[5] - right[5]) <= epsilon &&
Math.abs(left[6] - right[6]) <= epsilon &&
Math.abs(left[7] - right[7]) <= epsilon &&
Math.abs(left[8] - right[8]) <= epsilon);
};
/**
* An immutable Matrix3 instance initialized to the identity matrix.
*
* @type {Matrix3}
* @constant
*/
Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0));
/**
* An immutable Matrix3 instance initialized to the zero matrix.
*
* @type {Matrix3}
* @constant
*/
Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 0.0, 0.0));
/**
* The index into Matrix3 for column 0, row 0.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN0ROW0 = 0;
/**
* The index into Matrix3 for column 0, row 1.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN0ROW1 = 1;
/**
* The index into Matrix3 for column 0, row 2.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN0ROW2 = 2;
/**
* The index into Matrix3 for column 1, row 0.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN1ROW0 = 3;
/**
* The index into Matrix3 for column 1, row 1.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN1ROW1 = 4;
/**
* The index into Matrix3 for column 1, row 2.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN1ROW2 = 5;
/**
* The index into Matrix3 for column 2, row 0.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN2ROW0 = 6;
/**
* The index into Matrix3 for column 2, row 1.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN2ROW1 = 7;
/**
* The index into Matrix3 for column 2, row 2.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN2ROW2 = 8;
defineProperties(Matrix3.prototype, {
/**
* Gets the number of items in the collection.
* @memberof Matrix3.prototype
*
* @type {Number}
*/
length : {
get : function() {
return Matrix3.packedLength;
}
}
});
/**
* Duplicates the provided Matrix3 instance.
*
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
*/
Matrix3.prototype.clone = function(result) {
return Matrix3.clone(this, result);
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix3} [right] The right hand side matrix.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Matrix3.prototype.equals = function(right) {
return Matrix3.equals(this, right);
};
/**
* @private
*/
Matrix3.equalsArray = function(matrix, array, offset) {
return matrix[0] === array[offset] &&
matrix[1] === array[offset + 1] &&
matrix[2] === array[offset + 2] &&
matrix[3] === array[offset + 3] &&
matrix[4] === array[offset + 4] &&
matrix[5] === array[offset + 5] &&
matrix[6] === array[offset + 6] &&
matrix[7] === array[offset + 7] &&
matrix[8] === array[offset + 8];
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix3} [right] The right hand side matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
return Matrix3.equalsEpsilon(this, right, epsilon);
};
/**
* Creates a string representing this Matrix with each row being
* on a separate line and in the format '(column0, column1, column2)'.
*
* @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
*/
Matrix3.prototype.toString = function() {
return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
'(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
'(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
};
return Matrix3;
});
/*global define*/
define('Core/Cartesian4',[
'./Check',
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
Check,
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
'use strict';
/**
* A 4D Cartesian point.
* @alias Cartesian4
* @constructor
*
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
* @param {Number} [z=0.0] The Z component.
* @param {Number} [w=0.0] The W component.
*
* @see Cartesian2
* @see Cartesian3
* @see Packable
*/
function Cartesian4(x, y, z, w) {
/**
* The X component.
* @type {Number}
* @default 0.0
*/
this.x = defaultValue(x, 0.0);
/**
* The Y component.
* @type {Number}
* @default 0.0
*/
this.y = defaultValue(y, 0.0);
/**
* The Z component.
* @type {Number}
* @default 0.0
*/
this.z = defaultValue(z, 0.0);
/**
* The W component.
* @type {Number}
* @default 0.0
*/
this.w = defaultValue(w, 0.0);
}
/**
* Creates a Cartesian4 instance from x, y, z and w coordinates.
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
* @param {Number} w The w coordinate.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.fromElements = function(x, y, z, w, result) {
if (!defined(result)) {
return new Cartesian4(x, y, z, w);
}
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
* and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
*
* @param {Color} color The source color.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.fromColor = function(color, result) {
Check.typeOf.object('color', color);
if (!defined(result)) {
return new Cartesian4(color.red, color.green, color.blue, color.alpha);
}
result.x = color.red;
result.y = color.green;
result.z = color.blue;
result.w = color.alpha;
return result;
};
/**
* Duplicates a Cartesian4 instance.
*
* @param {Cartesian4} cartesian The Cartesian to duplicate.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
Cartesian4.clone = function(cartesian, result) {
if (!defined(cartesian)) {
return undefined;
}
if (!defined(result)) {
return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
}
result.x = cartesian.x;
result.y = cartesian.y;
result.z = cartesian.z;
result.w = cartesian.w;
return result;
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Cartesian4.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian4} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Cartesian4.pack = function(value, array, startingIndex) {
Check.typeOf.object('value', value);
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex++] = value.z;
array[startingIndex] = value.w;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian4} [result] The object into which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.unpack = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Cartesian4();
}
result.x = array[startingIndex++];
result.y = array[startingIndex++];
result.z = array[startingIndex++];
result.w = array[startingIndex];
return result;
};
/**
* Flattens an array of Cartesian4s into and array of components.
*
* @param {Cartesian4[]} array The array of cartesians to pack.
* @param {Number[]} result The array onto which to store the result.
* @returns {Number[]} The packed array.
*/
Cartesian4.packArray = function(array, result) {
Check.defined('array', array);
var length = array.length;
if (!defined(result)) {
result = new Array(length * 4);
} else {
result.length = length * 4;
}
for (var i = 0; i < length; ++i) {
Cartesian4.pack(array[i], result, i * 4);
}
return result;
};
/**
* Unpacks an array of cartesian components into and array of Cartesian4s.
*
* @param {Number[]} array The array of components to unpack.
* @param {Cartesian4[]} result The array onto which to store the result.
* @returns {Cartesian4[]} The unpacked array.
*/
Cartesian4.unpackArray = function(array, result) {
Check.defined('array', array);
var length = array.length;
if (!defined(result)) {
result = new Array(length / 4);
} else {
result.length = length / 4;
}
for (var i = 0; i < length; i += 4) {
var index = i / 4;
result[index] = Cartesian4.unpack(array, i, result[index]);
}
return result;
};
/**
* Creates a Cartesian4 from four consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*
* @example
* // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
* var v = [1.0, 2.0, 3.0, 4.0];
* var p = Cesium.Cartesian4.fromArray(v);
*
* // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
* var p2 = Cesium.Cartesian4.fromArray(v2, 2);
*/
Cartesian4.fromArray = Cartesian4.unpack;
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian4} cartesian The cartesian to use.
* @returns {Number} The value of the maximum component.
*/
Cartesian4.maximumComponent = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
};
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian4} cartesian The cartesian to use.
* @returns {Number} The value of the minimum component.
*/
Cartesian4.minimumComponent = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
};
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian4} first A cartesian to compare.
* @param {Cartesian4} second A cartesian to compare.
* @param {Cartesian4} result The object into which to store the result.
* @returns {Cartesian4} A cartesian with the minimum components.
*/
Cartesian4.minimumByComponent = function(first, second, result) {
Check.typeOf.object('first', first);
Check.typeOf.object('second', second);
Check.typeOf.object('result', result);
result.x = Math.min(first.x, second.x);
result.y = Math.min(first.y, second.y);
result.z = Math.min(first.z, second.z);
result.w = Math.min(first.w, second.w);
return result;
};
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian4} first A cartesian to compare.
* @param {Cartesian4} second A cartesian to compare.
* @param {Cartesian4} result The object into which to store the result.
* @returns {Cartesian4} A cartesian with the maximum components.
*/
Cartesian4.maximumByComponent = function(first, second, result) {
Check.typeOf.object('first', first);
Check.typeOf.object('second', second);
Check.typeOf.object('result', result);
result.x = Math.max(first.x, second.x);
result.y = Math.max(first.y, second.y);
result.z = Math.max(first.z, second.z);
result.w = Math.max(first.w, second.w);
return result;
};
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {Number} The squared magnitude.
*/
Cartesian4.magnitudeSquared = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
};
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {Number} The magnitude.
*/
Cartesian4.magnitude = function(cartesian) {
return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
};
var distanceScratch = new Cartesian4();
/**
* Computes the 4-space distance between two points.
*
* @param {Cartesian4} left The first point to compute the distance from.
* @param {Cartesian4} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 1.0
* var d = Cesium.Cartesian4.distance(
* new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
* new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
*/
Cartesian4.distance = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Cartesian4.subtract(left, right, distanceScratch);
return Cartesian4.magnitude(distanceScratch);
};
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
*
* @param {Cartesian4} left The first point to compute the distance from.
* @param {Cartesian4} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* var d = Cesium.Cartesian4.distance(
* new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
* new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
*/
Cartesian4.distanceSquared = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Cartesian4.subtract(left, right, distanceScratch);
return Cartesian4.magnitudeSquared(distanceScratch);
};
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian to be normalized.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.normalize = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var magnitude = Cartesian4.magnitude(cartesian);
result.x = cartesian.x / magnitude;
result.y = cartesian.y / magnitude;
result.z = cartesian.z / magnitude;
result.w = cartesian.w / magnitude;
if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
throw new DeveloperError('normalized result is not a number');
}
return result;
};
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @returns {Number} The dot product.
*/
Cartesian4.dot = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
};
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.multiplyComponents = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x * right.x;
result.y = left.y * right.y;
result.z = left.z * right.z;
result.w = left.w * right.w;
return result;
};
/**
* Computes the componentwise quotient of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.divideComponents = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x / right.x;
result.y = left.y / right.y;
result.z = left.z / right.z;
result.w = left.w / right.w;
return result;
};
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.add = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x + right.x;
result.y = left.y + right.y;
result.z = left.z + right.z;
result.w = left.w + right.w;
return result;
};
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.subtract = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x - right.x;
result.y = left.y - right.y;
result.z = left.z - right.z;
result.w = left.w - right.w;
return result;
};
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian4} cartesian The Cartesian to be scaled.
* @param {Number} scalar The scalar to multiply with.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result.x = cartesian.x * scalar;
result.y = cartesian.y * scalar;
result.z = cartesian.z * scalar;
result.w = cartesian.w * scalar;
return result;
};
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian4} cartesian The Cartesian to be divided.
* @param {Number} scalar The scalar to divide by.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.divideByScalar = function(cartesian, scalar, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result.x = cartesian.x / scalar;
result.y = cartesian.y / scalar;
result.z = cartesian.z / scalar;
result.w = cartesian.w / scalar;
return result;
};
/**
* Negates the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian to be negated.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.negate = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result.x = -cartesian.x;
result.y = -cartesian.y;
result.z = -cartesian.z;
result.w = -cartesian.w;
return result;
};
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.abs = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result.x = Math.abs(cartesian.x);
result.y = Math.abs(cartesian.y);
result.z = Math.abs(cartesian.z);
result.w = Math.abs(cartesian.w);
return result;
};
var lerpScratch = new Cartesian4();
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian4} start The value corresponding to t at 0.0.
* @param {Cartesian4}end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.lerp = function(start, end, t, result) {
Check.typeOf.object('start', start);
Check.typeOf.object('end', end);
Check.typeOf.number('t', t);
Check.typeOf.object('result', result);
Cartesian4.multiplyByScalar(end, t, lerpScratch);
result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
return Cartesian4.add(lerpScratch, result, result);
};
var mostOrthogonalAxisScratch = new Cartesian4();
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The most orthogonal axis.
*/
Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
Cartesian4.abs(f, f);
if (f.x <= f.y) {
if (f.x <= f.z) {
if (f.x <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_X, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
} else if (f.z <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
} else if (f.y <= f.z) {
if (f.y <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
} else if (f.z <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
return result;
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian4} [left] The first Cartesian.
* @param {Cartesian4} [right] The second Cartesian.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartesian4.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.x === right.x) &&
(left.y === right.y) &&
(left.z === right.z) &&
(left.w === right.w));
};
/**
* @private
*/
Cartesian4.equalsArray = function(cartesian, array, offset) {
return cartesian.x === array[offset] &&
cartesian.y === array[offset + 1] &&
cartesian.z === array[offset + 2] &&
cartesian.w === array[offset + 3];
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian4} [left] The first Cartesian.
* @param {Cartesian4} [right] The second Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return (left === right) ||
(defined(left) &&
defined(right) &&
CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
};
/**
* An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
/**
* Duplicates this Cartesian4 instance.
*
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.prototype.clone = function(result) {
return Cartesian4.clone(this, result);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian4} [right] The right hand side Cartesian.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Cartesian4.prototype.equals = function(right) {
return Cartesian4.equals(this, right);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian4} [right] The right hand side Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
};
/**
* Creates a string representing this Cartesian in the format '(x, y)'.
*
* @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
*/
Cartesian4.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
};
return Cartesian4;
});
/*global define*/
define('Core/RuntimeError',[
'./defined'
], function(
defined) {
'use strict';
/**
* Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
* out of memory, could not compile shader, etc. If a function may throw this
* exception, the calling code should be prepared to catch it.
* <br /><br />
* On the other hand, a {@link DeveloperError} indicates an exception due
* to a developer error, e.g., invalid argument, that usually indicates a bug in the
* calling code.
*
* @alias RuntimeError
* @constructor
* @extends Error
*
* @param {String} [message] The error message for this exception.
*
* @see DeveloperError
*/
function RuntimeError(message) {
/**
* 'RuntimeError' indicating that this exception was thrown due to a runtime error.
* @type {String}
* @readonly
*/
this.name = 'RuntimeError';
/**
* The explanation for why this exception was thrown.
* @type {String}
* @readonly
*/
this.message = message;
//Browsers such as IE don't have a stack property until you actually throw the error.
var stack;
try {
throw new Error();
} catch (e) {
stack = e.stack;
}
/**
* The stack trace of this exception, if available.
* @type {String}
* @readonly
*/
this.stack = stack;
}
if (defined(Object.create)) {
RuntimeError.prototype = Object.create(Error.prototype);
RuntimeError.prototype.constructor = RuntimeError;
}
RuntimeError.prototype.toString = function() {
var str = this.name + ': ' + this.message;
if (defined(this.stack)) {
str += '\n' + this.stack.toString();
}
return str;
};
return RuntimeError;
});
/*global define*/
define('Core/Matrix4',[
'./Cartesian3',
'./Cartesian4',
'./Check',
'./defaultValue',
'./defined',
'./defineProperties',
'./freezeObject',
'./Math',
'./Matrix3',
'./RuntimeError'
], function(
Cartesian3,
Cartesian4,
Check,
defaultValue,
defined,
defineProperties,
freezeObject,
CesiumMath,
Matrix3,
RuntimeError) {
'use strict';
/**
* A 4x4 matrix, indexable as a column-major order array.
* Constructor parameters are in row-major order for code readability.
* @alias Matrix4
* @constructor
*
* @param {Number} [column0Row0=0.0] The value for column 0, row 0.
* @param {Number} [column1Row0=0.0] The value for column 1, row 0.
* @param {Number} [column2Row0=0.0] The value for column 2, row 0.
* @param {Number} [column3Row0=0.0] The value for column 3, row 0.
* @param {Number} [column0Row1=0.0] The value for column 0, row 1.
* @param {Number} [column1Row1=0.0] The value for column 1, row 1.
* @param {Number} [column2Row1=0.0] The value for column 2, row 1.
* @param {Number} [column3Row1=0.0] The value for column 3, row 1.
* @param {Number} [column0Row2=0.0] The value for column 0, row 2.
* @param {Number} [column1Row2=0.0] The value for column 1, row 2.
* @param {Number} [column2Row2=0.0] The value for column 2, row 2.
* @param {Number} [column3Row2=0.0] The value for column 3, row 2.
* @param {Number} [column0Row3=0.0] The value for column 0, row 3.
* @param {Number} [column1Row3=0.0] The value for column 1, row 3.
* @param {Number} [column2Row3=0.0] The value for column 2, row 3.
* @param {Number} [column3Row3=0.0] The value for column 3, row 3.
*
* @see Matrix4.fromColumnMajorArray
* @see Matrix4.fromRowMajorArray
* @see Matrix4.fromRotationTranslation
* @see Matrix4.fromTranslationRotationScale
* @see Matrix4.fromTranslationQuaternionRotationScale
* @see Matrix4.fromTranslation
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.fromCamera
* @see Matrix4.computePerspectiveFieldOfView
* @see Matrix4.computeOrthographicOffCenter
* @see Matrix4.computePerspectiveOffCenter
* @see Matrix4.computeInfinitePerspectiveOffCenter
* @see Matrix4.computeViewportTransformation
* @see Matrix4.computeView
* @see Matrix2
* @see Matrix3
* @see Packable
*/
function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
column0Row1, column1Row1, column2Row1, column3Row1,
column0Row2, column1Row2, column2Row2, column3Row2,
column0Row3, column1Row3, column2Row3, column3Row3) {
this[0] = defaultValue(column0Row0, 0.0);
this[1] = defaultValue(column0Row1, 0.0);
this[2] = defaultValue(column0Row2, 0.0);
this[3] = defaultValue(column0Row3, 0.0);
this[4] = defaultValue(column1Row0, 0.0);
this[5] = defaultValue(column1Row1, 0.0);
this[6] = defaultValue(column1Row2, 0.0);
this[7] = defaultValue(column1Row3, 0.0);
this[8] = defaultValue(column2Row0, 0.0);
this[9] = defaultValue(column2Row1, 0.0);
this[10] = defaultValue(column2Row2, 0.0);
this[11] = defaultValue(column2Row3, 0.0);
this[12] = defaultValue(column3Row0, 0.0);
this[13] = defaultValue(column3Row1, 0.0);
this[14] = defaultValue(column3Row2, 0.0);
this[15] = defaultValue(column3Row3, 0.0);
}
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Matrix4.packedLength = 16;
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix4} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Matrix4.pack = function(value, array, startingIndex) {
Check.typeOf.object('value', value);
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex++] = value[3];
array[startingIndex++] = value[4];
array[startingIndex++] = value[5];
array[startingIndex++] = value[6];
array[startingIndex++] = value[7];
array[startingIndex++] = value[8];
array[startingIndex++] = value[9];
array[startingIndex++] = value[10];
array[startingIndex++] = value[11];
array[startingIndex++] = value[12];
array[startingIndex++] = value[13];
array[startingIndex++] = value[14];
array[startingIndex] = value[15];
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix4} [result] The object into which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*/
Matrix4.unpack = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Matrix4();
}
result[0] = array[startingIndex++];
result[1] = array[startingIndex++];
result[2] = array[startingIndex++];
result[3] = array[startingIndex++];
result[4] = array[startingIndex++];
result[5] = array[startingIndex++];
result[6] = array[startingIndex++];
result[7] = array[startingIndex++];
result[8] = array[startingIndex++];
result[9] = array[startingIndex++];
result[10] = array[startingIndex++];
result[11] = array[startingIndex++];
result[12] = array[startingIndex++];
result[13] = array[startingIndex++];
result[14] = array[startingIndex++];
result[15] = array[startingIndex];
return result;
};
/**
* Duplicates a Matrix4 instance.
*
* @param {Matrix4} matrix The matrix to duplicate.
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
*/
Matrix4.clone = function(matrix, result) {
if (!defined(matrix)) {
return undefined;
}
if (!defined(result)) {
return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
matrix[1], matrix[5], matrix[9], matrix[13],
matrix[2], matrix[6], matrix[10], matrix[14],
matrix[3], matrix[7], matrix[11], matrix[15]);
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
};
/**
* Creates a Matrix4 from 16 consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*
* @example
* // Create the Matrix4:
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
*
* var v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
* var m = Cesium.Matrix4.fromArray(v);
*
* // Create same Matrix4 with using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
* var m2 = Cesium.Matrix4.fromArray(v2, 2);
*/
Matrix4.fromArray = Matrix4.unpack;
/**
* Computes a Matrix4 instance from a column-major order array.
*
* @param {Number[]} values The column-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromColumnMajorArray = function(values, result) {
Check.defined('values', values);
return Matrix4.clone(values, result);
};
/**
* Computes a Matrix4 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {Number[]} values The row-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromRowMajorArray = function(values, result) {
Check.defined('values', values);
if (!defined(result)) {
return new Matrix4(values[0], values[1], values[2], values[3],
values[4], values[5], values[6], values[7],
values[8], values[9], values[10], values[11],
values[12], values[13], values[14], values[15]);
}
result[0] = values[0];
result[1] = values[4];
result[2] = values[8];
result[3] = values[12];
result[4] = values[1];
result[5] = values[5];
result[6] = values[9];
result[7] = values[13];
result[8] = values[2];
result[9] = values[6];
result[10] = values[10];
result[11] = values[14];
result[12] = values[3];
result[13] = values[7];
result[14] = values[11];
result[15] = values[15];
return result;
};
/**
* Computes a Matrix4 instance from a Matrix3 representing the rotation
* and a Cartesian3 representing the translation.
*
* @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
* @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromRotationTranslation = function(rotation, translation, result) {
Check.typeOf.object('rotation', rotation);
translation = defaultValue(translation, Cartesian3.ZERO);
if (!defined(result)) {
return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
rotation[1], rotation[4], rotation[7], translation.y,
rotation[2], rotation[5], rotation[8], translation.z,
0.0, 0.0, 0.0, 1.0);
}
result[0] = rotation[0];
result[1] = rotation[1];
result[2] = rotation[2];
result[3] = 0.0;
result[4] = rotation[3];
result[5] = rotation[4];
result[6] = rotation[5];
result[7] = 0.0;
result[8] = rotation[6];
result[9] = rotation[7];
result[10] = rotation[8];
result[11] = 0.0;
result[12] = translation.x;
result[13] = translation.y;
result[14] = translation.z;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
* representation with the rotation represented as a quaternion.
*
* @param {Cartesian3} translation The translation transformation.
* @param {Quaternion} rotation The rotation transformation.
* @param {Cartesian3} scale The non-uniform scale transformation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
* new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
* Cesium.Quaternion.IDENTITY, // rotation
* new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
* result);
*/
Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
Check.typeOf.object('translation', translation);
Check.typeOf.object('rotation', rotation);
Check.typeOf.object('scale', scale);
if (!defined(result)) {
result = new Matrix4();
}
var scaleX = scale.x;
var scaleY = scale.y;
var scaleZ = scale.z;
var x2 = rotation.x * rotation.x;
var xy = rotation.x * rotation.y;
var xz = rotation.x * rotation.z;
var xw = rotation.x * rotation.w;
var y2 = rotation.y * rotation.y;
var yz = rotation.y * rotation.z;
var yw = rotation.y * rotation.w;
var z2 = rotation.z * rotation.z;
var zw = rotation.z * rotation.w;
var w2 = rotation.w * rotation.w;
var m00 = x2 - y2 - z2 + w2;
var m01 = 2.0 * (xy - zw);
var m02 = 2.0 * (xz + yw);
var m10 = 2.0 * (xy + zw);
var m11 = -x2 + y2 - z2 + w2;
var m12 = 2.0 * (yz - xw);
var m20 = 2.0 * (xz - yw);
var m21 = 2.0 * (yz + xw);
var m22 = -x2 - y2 + z2 + w2;
result[0] = m00 * scaleX;
result[1] = m10 * scaleX;
result[2] = m20 * scaleX;
result[3] = 0.0;
result[4] = m01 * scaleY;
result[5] = m11 * scaleY;
result[6] = m21 * scaleY;
result[7] = 0.0;
result[8] = m02 * scaleZ;
result[9] = m12 * scaleZ;
result[10] = m22 * scaleZ;
result[11] = 0.0;
result[12] = translation.x;
result[13] = translation.y;
result[14] = translation.z;
result[15] = 1.0;
return result;
};
/**
* Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
*
* @param {TranslationRotationScale} translationRotationScale The instance.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
Check.typeOf.object('translationRotationScale', translationRotationScale);
return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
};
/**
* Creates a Matrix4 instance from a Cartesian3 representing the translation.
*
* @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @see Matrix4.multiplyByTranslation
*/
Matrix4.fromTranslation = function(translation, result) {
Check.typeOf.object('translation', translation);
return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
};
/**
* Computes a Matrix4 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0, 0.0]
* // [0.0, 0.0, 9.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix4.fromScale = function(scale, result) {
Check.typeOf.object('scale', scale);
if (!defined(result)) {
return new Matrix4(
scale.x, 0.0, 0.0, 0.0,
0.0, scale.y, 0.0, 0.0,
0.0, 0.0, scale.z, 0.0,
0.0, 0.0, 0.0, 1.0);
}
result[0] = scale.x;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = scale.y;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = scale.z;
result[11] = 0.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = 0.0;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance representing a uniform scale.
*
* @param {Number} scale The uniform scale factor.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0, 0.0]
* // [0.0, 0.0, 2.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* var m = Cesium.Matrix4.fromUniformScale(2.0);
*/
Matrix4.fromUniformScale = function(scale, result) {
Check.typeOf.number('scale', scale);
if (!defined(result)) {
return new Matrix4(scale, 0.0, 0.0, 0.0,
0.0, scale, 0.0, 0.0,
0.0, 0.0, scale, 0.0,
0.0, 0.0, 0.0, 1.0);
}
result[0] = scale;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = scale;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = scale;
result[11] = 0.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = 0.0;
result[15] = 1.0;
return result;
};
var fromCameraF = new Cartesian3();
var fromCameraR = new Cartesian3();
var fromCameraU = new Cartesian3();
/**
* Computes a Matrix4 instance from a Camera.
*
* @param {Camera} camera The camera to use.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromCamera = function(camera, result) {
Check.typeOf.object('camera', camera);
var position = camera.position;
var direction = camera.direction;
var up = camera.up;
Check.typeOf.object('camera.position', position);
Check.typeOf.object('camera.direction', direction);
Check.typeOf.object('camera.up', up);
Cartesian3.normalize(direction, fromCameraF);
Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
var sX = fromCameraR.x;
var sY = fromCameraR.y;
var sZ = fromCameraR.z;
var fX = fromCameraF.x;
var fY = fromCameraF.y;
var fZ = fromCameraF.z;
var uX = fromCameraU.x;
var uY = fromCameraU.y;
var uZ = fromCameraU.z;
var positionX = position.x;
var positionY = position.y;
var positionZ = position.z;
var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
var t2 = fX * positionX + fY * positionY + fZ * positionZ;
// The code below this comment is an optimized
// version of the commented lines.
// Rather that create two matrices and then multiply,
// we just bake in the multiplcation as part of creation.
// var rotation = new Matrix4(
// sX, sY, sZ, 0.0,
// uX, uY, uZ, 0.0,
// -fX, -fY, -fZ, 0.0,
// 0.0, 0.0, 0.0, 1.0);
// var translation = new Matrix4(
// 1.0, 0.0, 0.0, -position.x,
// 0.0, 1.0, 0.0, -position.y,
// 0.0, 0.0, 1.0, -position.z,
// 0.0, 0.0, 0.0, 1.0);
// return rotation.multiply(translation);
if (!defined(result)) {
return new Matrix4(
sX, sY, sZ, t0,
uX, uY, uZ, t1,
-fX, -fY, -fZ, t2,
0.0, 0.0, 0.0, 1.0);
}
result[0] = sX;
result[1] = uX;
result[2] = -fX;
result[3] = 0.0;
result[4] = sY;
result[5] = uY;
result[6] = -fY;
result[7] = 0.0;
result[8] = sZ;
result[9] = uZ;
result[10] = -fZ;
result[11] = 0.0;
result[12] = t0;
result[13] = t1;
result[14] = t2;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance representing a perspective transformation matrix.
*
* @param {Number} fovY The field of view along the Y axis in radians.
* @param {Number} aspectRatio The aspect ratio.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} fovY must be in (0, PI].
* @exception {DeveloperError} aspectRatio must be greater than zero.
* @exception {DeveloperError} near must be greater than zero.
* @exception {DeveloperError} far must be greater than zero.
*/
Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
Check.typeOf.number.greaterThan('fovY', fovY, 0.0);
Check.typeOf.number.lessThan('fovY', fovY, Math.PI);
Check.typeOf.number.greaterThan('near', near, 0.0);
Check.typeOf.number.greaterThan('far', far, 0.0);
Check.typeOf.object('result', result);
var bottom = Math.tan(fovY * 0.5);
var column1Row1 = 1.0 / bottom;
var column0Row0 = column1Row1 / aspectRatio;
var column2Row2 = (far + near) / (near - far);
var column3Row2 = (2.0 * far * near) / (near - far);
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = column2Row2;
result[11] = -1.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = column3Row2;
result[15] = 0.0;
return result;
};
/**
* Computes a Matrix4 instance representing an orthographic transformation matrix.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
Check.typeOf.number('left', left);
Check.typeOf.number('right', right);
Check.typeOf.number('bottom', bottom);
Check.typeOf.number('top', top);
Check.typeOf.number('near', near);
Check.typeOf.number('far', far);
Check.typeOf.object('result', result);
var a = 1.0 / (right - left);
var b = 1.0 / (top - bottom);
var c = 1.0 / (far - near);
var tx = -(right + left) * a;
var ty = -(top + bottom) * b;
var tz = -(far + near) * c;
a *= 2.0;
b *= 2.0;
c *= -2.0;
result[0] = a;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = b;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = c;
result[11] = 0.0;
result[12] = tx;
result[13] = ty;
result[14] = tz;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance representing an off center perspective transformation.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
Check.typeOf.number('left', left);
Check.typeOf.number('right', right);
Check.typeOf.number('bottom', bottom);
Check.typeOf.number('top', top);
Check.typeOf.number('near', near);
Check.typeOf.number('far', far);
Check.typeOf.object('result', result);
var column0Row0 = 2.0 * near / (right - left);
var column1Row1 = 2.0 * near / (top - bottom);
var column2Row0 = (right + left) / (right - left);
var column2Row1 = (top + bottom) / (top - bottom);
var column2Row2 = -(far + near) / (far - near);
var column2Row3 = -1.0;
var column3Row2 = -2.0 * far * near / (far - near);
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = 0.0;
result[13] = 0.0;
result[14] = column3Row2;
result[15] = 0.0;
return result;
};
/**
* Computes a Matrix4 instance representing an infinite off center perspective transformation.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
Check.typeOf.number('left', left);
Check.typeOf.number('right', right);
Check.typeOf.number('bottom', bottom);
Check.typeOf.number('top', top);
Check.typeOf.number('near', near);
Check.typeOf.object('result', result);
var column0Row0 = 2.0 * near / (right - left);
var column1Row1 = 2.0 * near / (top - bottom);
var column2Row0 = (right + left) / (right - left);
var column2Row1 = (top + bottom) / (top - bottom);
var column2Row2 = -1.0;
var column2Row3 = -1.0;
var column3Row2 = -2.0 * near;
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = 0.0;
result[13] = 0.0;
result[14] = column3Row2;
result[15] = 0.0;
return result;
};
/**
* Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
*
* @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
* @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
* @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Create viewport transformation using an explicit viewport and depth range.
* var m = Cesium.Matrix4.computeViewportTransformation({
* x : 0.0,
* y : 0.0,
* width : 1024.0,
* height : 768.0
* }, 0.0, 1.0, new Cesium.Matrix4());
*/
Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
Check.typeOf.object('result', result);
viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
var x = defaultValue(viewport.x, 0.0);
var y = defaultValue(viewport.y, 0.0);
var width = defaultValue(viewport.width, 0.0);
var height = defaultValue(viewport.height, 0.0);
nearDepthRange = defaultValue(nearDepthRange, 0.0);
farDepthRange = defaultValue(farDepthRange, 1.0);
var halfWidth = width * 0.5;
var halfHeight = height * 0.5;
var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
var column0Row0 = halfWidth;
var column1Row1 = halfHeight;
var column2Row2 = halfDepth;
var column3Row0 = x + halfWidth;
var column3Row1 = y + halfHeight;
var column3Row2 = nearDepthRange + halfDepth;
var column3Row3 = 1.0;
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = column2Row2;
result[11] = 0.0;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = column3Row3;
return result;
};
/**
* Computes a Matrix4 instance that transforms from world space to view space.
*
* @param {Cartesian3} position The position of the camera.
* @param {Cartesian3} direction The forward direction.
* @param {Cartesian3} up The up direction.
* @param {Cartesian3} right The right direction.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.computeView = function(position, direction, up, right, result) {
Check.typeOf.object('position', position);
Check.typeOf.object('direction', direction);
Check.typeOf.object('up', up);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result[0] = right.x;
result[1] = up.x;
result[2] = -direction.x;
result[3] = 0.0;
result[4] = right.y;
result[5] = up.y;
result[6] = -direction.y;
result[7] = 0.0;
result[8] = right.z;
result[9] = up.z;
result[10] = -direction.z;
result[11] = 0.0;
result[12] = -Cartesian3.dot(right, position);
result[13] = -Cartesian3.dot(up, position);
result[14] = Cartesian3.dot(direction, position);
result[15] = 1.0;
return result;
};
/**
* Computes an Array from the provided Matrix4 instance.
* The array will be in column-major order.
*
* @param {Matrix4} matrix The matrix to use..
* @param {Number[]} [result] The Array onto which to store the result.
* @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
*
* @example
* //create an array from an instance of Matrix4
* // m = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
* var a = Cesium.Matrix4.toArray(m);
*
* // m remains the same
* //creates a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0]
*/
Matrix4.toArray = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
if (!defined(result)) {
return [matrix[0], matrix[1], matrix[2], matrix[3],
matrix[4], matrix[5], matrix[6], matrix[7],
matrix[8], matrix[9], matrix[10], matrix[11],
matrix[12], matrix[13], matrix[14], matrix[15]];
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
};
/**
* Computes the array index of the element at the provided row and column.
*
* @param {Number} row The zero-based index of the row.
* @param {Number} column The zero-based index of the column.
* @returns {Number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, 2, or 3.
* @exception {DeveloperError} column must be 0, 1, 2, or 3.
*
* @example
* var myMatrix = new Cesium.Matrix4();
* var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
* var column1Row0 = myMatrix[column1Row0Index];
* myMatrix[column1Row0Index] = 10.0;
*/
Matrix4.getElementIndex = function(column, row) {
Check.typeOf.number.greaterThanOrEquals('row', row, 0);
Check.typeOf.number.lessThanOrEquals('row', row, 3);
Check.typeOf.number.greaterThanOrEquals('column', column, 0);
Check.typeOf.number.lessThanOrEquals('column', column, 3);
return column * 4 + row;
};
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Creates an instance of Cartesian
* var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
*
* @example
* //Example 2: Sets values for Cartesian instance
* var a = new Cesium.Cartesian4();
* Cesium.Matrix4.getColumn(m, 2, a);
*
* // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
*/
Matrix4.getColumn = function(matrix, index, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 3);
Check.typeOf.object('result', result);
var startIndex = index * 4;
var x = matrix[startIndex];
var y = matrix[startIndex + 1];
var z = matrix[startIndex + 2];
var w = matrix[startIndex + 3];
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //creates a new Matrix4 instance with new column values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 11.0, 99.0, 13.0]
* // [14.0, 15.0, 98.0, 17.0]
* // [18.0, 19.0, 97.0, 21.0]
* // [22.0, 23.0, 96.0, 25.0]
*/
Matrix4.setColumn = function(matrix, index, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 3);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result = Matrix4.clone(matrix, result);
var startIndex = index * 4;
result[startIndex] = cartesian.x;
result[startIndex + 1] = cartesian.y;
result[startIndex + 2] = cartesian.z;
result[startIndex + 3] = cartesian.w;
return result;
};
/**
* Computes a new matrix that replaces the translation in the rightmost column of the provided
* matrix with the provided translation. This assumes the matrix is an affine transformation
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.setTranslation = function(matrix, translation, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('translation', translation);
Check.typeOf.object('result', result);
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = translation.x;
result[13] = translation.y;
result[14] = translation.z;
result[15] = matrix[15];
return result;
};
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Returns an instance of Cartesian
* var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
*
* @example
* //Example 2: Sets values for a Cartesian instance
* var a = new Cesium.Cartesian4();
* Cesium.Matrix4.getRow(m, 2, a);
*
* // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
*/
Matrix4.getRow = function(matrix, index, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 3);
Check.typeOf.object('result', result);
var x = matrix[index];
var y = matrix[index + 4];
var z = matrix[index + 8];
var w = matrix[index + 12];
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //create a new Matrix4 instance with new row values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [99.0, 98.0, 97.0, 96.0]
* // [22.0, 23.0, 24.0, 25.0]
*/
Matrix4.setRow = function(matrix, index, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number.greaterThanOrEquals('index', index, 0);
Check.typeOf.number.lessThanOrEquals('index', index, 3);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result = Matrix4.clone(matrix, result);
result[index] = cartesian.x;
result[index + 4] = cartesian.y;
result[index + 8] = cartesian.z;
result[index + 12] = cartesian.w;
return result;
};
var scratchColumn = new Cartesian3();
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter
*/
Matrix4.getScale = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
return result;
};
var scratchScale = new Cartesian3();
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors in the upper-left
* 3x3 matrix.
*
* @param {Matrix4} matrix The matrix.
* @returns {Number} The maximum scale.
*/
Matrix4.getMaximumScale = function(matrix) {
Matrix4.getScale(matrix, scratchScale);
return Cartesian3.maximumComponent(scratchScale);
};
/**
* Computes the product of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.multiply = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
var left0 = left[0];
var left1 = left[1];
var left2 = left[2];
var left3 = left[3];
var left4 = left[4];
var left5 = left[5];
var left6 = left[6];
var left7 = left[7];
var left8 = left[8];
var left9 = left[9];
var left10 = left[10];
var left11 = left[11];
var left12 = left[12];
var left13 = left[13];
var left14 = left[14];
var left15 = left[15];
var right0 = right[0];
var right1 = right[1];
var right2 = right[2];
var right3 = right[3];
var right4 = right[4];
var right5 = right[5];
var right6 = right[6];
var right7 = right[7];
var right8 = right[8];
var right9 = right[9];
var right10 = right[10];
var right11 = right[11];
var right12 = right[12];
var right13 = right[13];
var right14 = right[14];
var right15 = right[15];
var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column0Row3;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = column1Row3;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = column3Row3;
return result;
};
/**
* Computes the sum of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.add = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result[0] = left[0] + right[0];
result[1] = left[1] + right[1];
result[2] = left[2] + right[2];
result[3] = left[3] + right[3];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
result[9] = left[9] + right[9];
result[10] = left[10] + right[10];
result[11] = left[11] + right[11];
result[12] = left[12] + right[12];
result[13] = left[13] + right[13];
result[14] = left[14] + right[14];
result[15] = left[15] + right[15];
return result;
};
/**
* Computes the difference of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.subtract = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result[0] = left[0] - right[0];
result[1] = left[1] - right[1];
result[2] = left[2] - right[2];
result[3] = left[3] - right[3];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
result[9] = left[9] - right[9];
result[10] = left[10] - right[10];
result[11] = left[11] - right[11];
result[12] = left[12] - right[12];
result[13] = left[13] - right[13];
result[14] = left[14] - right[14];
result[15] = left[15] - right[15];
return result;
};
/**
* Computes the product of two matrices assuming the matrices are
* affine transformation matrices, where the upper left 3x3 elements
* are a rotation matrix, and the upper three elements in the fourth
* column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
* The matrix is not verified to be in the proper form.
* This method is faster than computing the product for general 4x4
* matrices using {@link Matrix4.multiply}.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* var m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0);
* var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
* var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
*/
Matrix4.multiplyTransformation = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
var left0 = left[0];
var left1 = left[1];
var left2 = left[2];
var left4 = left[4];
var left5 = left[5];
var left6 = left[6];
var left8 = left[8];
var left9 = left[9];
var left10 = left[10];
var left12 = left[12];
var left13 = left[13];
var left14 = left[14];
var right0 = right[0];
var right1 = right[1];
var right2 = right[2];
var right4 = right[4];
var right5 = right[5];
var right6 = right[6];
var right8 = right[8];
var right9 = right[9];
var right10 = right[10];
var right12 = right[12];
var right13 = right[13];
var right14 = right[14];
var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = 0.0;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = 0.0;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = 1.0;
return result;
};
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by a 3x3 rotation matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
* Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
*/
Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('rotation', rotation);
Check.typeOf.object('result', result);
var left0 = matrix[0];
var left1 = matrix[1];
var left2 = matrix[2];
var left4 = matrix[4];
var left5 = matrix[5];
var left6 = matrix[6];
var left8 = matrix[8];
var left9 = matrix[9];
var left10 = matrix[10];
var right0 = rotation[0];
var right1 = rotation[1];
var right2 = rotation[2];
var right4 = rotation[3];
var right5 = rotation[4];
var right6 = rotation[5];
var right8 = rotation[6];
var right9 = rotation[7];
var right10 = rotation[8];
var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = 0.0;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = 0.0;
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
};
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Cartesian3} translation The translation on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
* Cesium.Matrix4.multiplyByTranslation(m, position, m);
*/
Matrix4.multiplyByTranslation = function(matrix, translation, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('translation', translation);
Check.typeOf.object('result', result);
var x = translation.x;
var y = translation.y;
var z = translation.z;
var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = tx;
result[13] = ty;
result[14] = tz;
result[15] = matrix[15];
return result;
};
var uniformScaleScratch = new Cartesian3();
/**
* Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit uniform scale matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
* <code>m</code> must be an affine matrix.
* This function performs fewer allocations and arithmetic operations.
*
* @param {Matrix4} matrix The affine matrix on the left-hand side.
* @param {Number} scale The uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
* Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
*
* @see Matrix4.fromUniformScale
* @see Matrix4.multiplyByScale
*/
Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number('scale', scale);
Check.typeOf.object('result', result);
uniformScaleScratch.x = scale;
uniformScaleScratch.y = scale;
uniformScaleScratch.z = scale;
return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
};
/**
* Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit non-uniform scale matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
* <code>m</code> must be an affine matrix.
* This function performs fewer allocations and arithmetic operations.
*
* @param {Matrix4} matrix The affine matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
* Cesium.Matrix4.multiplyByScale(m, scale, m);
*
* @see Matrix4.fromScale
* @see Matrix4.multiplyByUniformScale
*/
Matrix4.multiplyByScale = function(matrix, scale, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('scale', scale);
Check.typeOf.object('result', result);
var scaleX = scale.x;
var scaleY = scale.y;
var scaleZ = scale.z;
// Faster than Cartesian3.equals
if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
return Matrix4.clone(matrix, result);
}
result[0] = scaleX * matrix[0];
result[1] = scaleX * matrix[1];
result[2] = scaleX * matrix[2];
result[3] = 0.0;
result[4] = scaleY * matrix[4];
result[5] = scaleY * matrix[5];
result[6] = scaleY * matrix[6];
result[7] = 0.0;
result[8] = scaleZ * matrix[8];
result[9] = scaleZ * matrix[9];
result[10] = scaleZ * matrix[10];
result[11] = 0.0;
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = 1.0;
return result;
};
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian4} cartesian The vector.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Matrix4.multiplyByVector = function(matrix, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var vW = cartesian.w;
var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a <code>w</code> component of zero.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
* // A shortcut for
* // Cartesian3 p = ...
* // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
*/
Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
*/
Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix4} matrix The matrix.
* @param {Number} scalar The number to multiply by.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //create a Matrix4 instance which is a scaled version of the supplied Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
*
* // m remains the same
* // a = [-20.0, -22.0, -24.0, -26.0]
* // [-28.0, -30.0, -32.0, -34.0]
* // [-36.0, -38.0, -40.0, -42.0]
* // [-44.0, -46.0, -48.0, -50.0]
*/
Matrix4.multiplyByScalar = function(matrix, scalar, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
result[9] = matrix[9] * scalar;
result[10] = matrix[10] * scalar;
result[11] = matrix[11] * scalar;
result[12] = matrix[12] * scalar;
result[13] = matrix[13] * scalar;
result[14] = matrix[14] * scalar;
result[15] = matrix[15] * scalar;
return result;
};
/**
* Computes a negated copy of the provided matrix.
*
* @param {Matrix4} matrix The matrix to negate.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //create a new Matrix4 instance which is a negation of a Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
*
* // m remains the same
* // a = [-10.0, -11.0, -12.0, -13.0]
* // [-14.0, -15.0, -16.0, -17.0]
* // [-18.0, -19.0, -20.0, -21.0]
* // [-22.0, -23.0, -24.0, -25.0]
*/
Matrix4.negate = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result[0] = -matrix[0];
result[1] = -matrix[1];
result[2] = -matrix[2];
result[3] = -matrix[3];
result[4] = -matrix[4];
result[5] = -matrix[5];
result[6] = -matrix[6];
result[7] = -matrix[7];
result[8] = -matrix[8];
result[9] = -matrix[9];
result[10] = -matrix[10];
result[11] = -matrix[11];
result[12] = -matrix[12];
result[13] = -matrix[13];
result[14] = -matrix[14];
result[15] = -matrix[15];
return result;
};
/**
* Computes the transpose of the provided matrix.
*
* @param {Matrix4} matrix The matrix to transpose.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //returns transpose of a Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*/
Matrix4.transpose = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
var matrix1 = matrix[1];
var matrix2 = matrix[2];
var matrix3 = matrix[3];
var matrix6 = matrix[6];
var matrix7 = matrix[7];
var matrix11 = matrix[11];
result[0] = matrix[0];
result[1] = matrix[4];
result[2] = matrix[8];
result[3] = matrix[12];
result[4] = matrix1;
result[5] = matrix[5];
result[6] = matrix[9];
result[7] = matrix[13];
result[8] = matrix2;
result[9] = matrix6;
result[10] = matrix[10];
result[11] = matrix[14];
result[12] = matrix3;
result[13] = matrix7;
result[14] = matrix11;
result[15] = matrix[15];
return result;
};
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix4} matrix The matrix with signed elements.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.abs = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
result[9] = Math.abs(matrix[9]);
result[10] = Math.abs(matrix[10]);
result[11] = Math.abs(matrix[11]);
result[12] = Math.abs(matrix[12]);
result[13] = Math.abs(matrix[13]);
result[14] = Math.abs(matrix[14]);
result[15] = Math.abs(matrix[15]);
return result;
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix4} [left] The first matrix.
* @param {Matrix4} [right] The second matrix.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*
* @example
* //compares two Matrix4 instances
*
* // a = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* // b = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* if(Cesium.Matrix4.equals(a,b)) {
* console.log("Both matrices are equal");
* } else {
* console.log("They are not equal");
* }
*
* //Prints "Both matrices are equal" on the console
*/
Matrix4.equals = function(left, right) {
// Given that most matrices will be transformation matrices, the elements
// are tested in order such that the test is likely to fail as early
// as possible. I _think_ this is just as friendly to the L1 cache
// as testing in index order. It is certainty faster in practice.
return (left === right) ||
(defined(left) &&
defined(right) &&
// Translation
left[12] === right[12] &&
left[13] === right[13] &&
left[14] === right[14] &&
// Rotation/scale
left[0] === right[0] &&
left[1] === right[1] &&
left[2] === right[2] &&
left[4] === right[4] &&
left[5] === right[5] &&
left[6] === right[6] &&
left[8] === right[8] &&
left[9] === right[9] &&
left[10] === right[10] &&
// Bottom row
left[3] === right[3] &&
left[7] === right[7] &&
left[11] === right[11] &&
left[15] === right[15]);
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix4} [left] The first matrix.
* @param {Matrix4} [right] The second matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*
* @example
* //compares two Matrix4 instances
*
* // a = [10.5, 14.5, 18.5, 22.5]
* // [11.5, 15.5, 19.5, 23.5]
* // [12.5, 16.5, 20.5, 24.5]
* // [13.5, 17.5, 21.5, 25.5]
*
* // b = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
* console.log("Difference between both the matrices is less than 0.1");
* } else {
* console.log("Difference between both the matrices is not less than 0.1");
* }
*
* //Prints "Difference between both the matrices is not less than 0.1" on the console
*/
Matrix4.equalsEpsilon = function(left, right, epsilon) {
Check.typeOf.number('epsilon', epsilon);
return (left === right) ||
(defined(left) &&
defined(right) &&
Math.abs(left[0] - right[0]) <= epsilon &&
Math.abs(left[1] - right[1]) <= epsilon &&
Math.abs(left[2] - right[2]) <= epsilon &&
Math.abs(left[3] - right[3]) <= epsilon &&
Math.abs(left[4] - right[4]) <= epsilon &&
Math.abs(left[5] - right[5]) <= epsilon &&
Math.abs(left[6] - right[6]) <= epsilon &&
Math.abs(left[7] - right[7]) <= epsilon &&
Math.abs(left[8] - right[8]) <= epsilon &&
Math.abs(left[9] - right[9]) <= epsilon &&
Math.abs(left[10] - right[10]) <= epsilon &&
Math.abs(left[11] - right[11]) <= epsilon &&
Math.abs(left[12] - right[12]) <= epsilon &&
Math.abs(left[13] - right[13]) <= epsilon &&
Math.abs(left[14] - right[14]) <= epsilon &&
Math.abs(left[15] - right[15]) <= epsilon);
};
/**
* Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix4.getTranslation = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result.x = matrix[12];
result.y = matrix[13];
result.z = matrix[14];
return result;
};
/**
* Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @example
* // returns a Matrix3 instance from a Matrix4 instance
*
* // m = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* var b = new Cesium.Matrix3();
* Cesium.Matrix4.getRotation(m,b);
*
* // b = [10.0, 14.0, 18.0]
* // [11.0, 15.0, 19.0]
* // [12.0, 16.0, 20.0]
*/
Matrix4.getRotation = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[4];
result[4] = matrix[5];
result[5] = matrix[6];
result[6] = matrix[8];
result[7] = matrix[9];
result[8] = matrix[10];
return result;
};
var scratchInverseRotation = new Matrix3();
var scratchMatrix3Zero = new Matrix3();
var scratchBottomRow = new Cartesian4();
var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
/**
* Computes the inverse of the provided matrix using Cramers Rule.
* If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
* If the matrix is an affine transformation matrix, it is more efficient
* to invert it with {@link Matrix4.inverseTransformation}.
*
* @param {Matrix4} matrix The matrix to invert.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {RuntimeError} matrix is not invertible because its determinate is zero.
*/
Matrix4.inverse = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
// Special case for a zero scale matrix that can occur, for example,
// when a model's node has a [0, 0, 0] scale.
if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
result[0] = 0.0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = 0.0;
result[11] = 0.0;
result[12] = -matrix[12];
result[13] = -matrix[13];
result[14] = -matrix[14];
result[15] = 1.0;
return result;
}
//
// Ported from:
// ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
//
var src0 = matrix[0];
var src1 = matrix[4];
var src2 = matrix[8];
var src3 = matrix[12];
var src4 = matrix[1];
var src5 = matrix[5];
var src6 = matrix[9];
var src7 = matrix[13];
var src8 = matrix[2];
var src9 = matrix[6];
var src10 = matrix[10];
var src11 = matrix[14];
var src12 = matrix[3];
var src13 = matrix[7];
var src14 = matrix[11];
var src15 = matrix[15];
// calculate pairs for first 8 elements (cofactors)
var tmp0 = src10 * src15;
var tmp1 = src11 * src14;
var tmp2 = src9 * src15;
var tmp3 = src11 * src13;
var tmp4 = src9 * src14;
var tmp5 = src10 * src13;
var tmp6 = src8 * src15;
var tmp7 = src11 * src12;
var tmp8 = src8 * src14;
var tmp9 = src10 * src12;
var tmp10 = src8 * src13;
var tmp11 = src9 * src12;
// calculate first 8 elements (cofactors)
var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
// calculate pairs for second 8 elements (cofactors)
tmp0 = src2 * src7;
tmp1 = src3 * src6;
tmp2 = src1 * src7;
tmp3 = src3 * src5;
tmp4 = src1 * src6;
tmp5 = src2 * src5;
tmp6 = src0 * src7;
tmp7 = src3 * src4;
tmp8 = src0 * src6;
tmp9 = src2 * src4;
tmp10 = src0 * src5;
tmp11 = src1 * src4;
// calculate second 8 elements (cofactors)
var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
// calculate determinant
var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
if (Math.abs(det) < CesiumMath.EPSILON20) {
throw new RuntimeError('matrix is not invertible because its determinate is zero.');
}
// calculate matrix inverse
det = 1.0 / det;
result[0] = dst0 * det;
result[1] = dst1 * det;
result[2] = dst2 * det;
result[3] = dst3 * det;
result[4] = dst4 * det;
result[5] = dst5 * det;
result[6] = dst6 * det;
result[7] = dst7 * det;
result[8] = dst8 * det;
result[9] = dst9 * det;
result[10] = dst10 * det;
result[11] = dst11 * det;
result[12] = dst12 * det;
result[13] = dst13 * det;
result[14] = dst14 * det;
result[15] = dst15 * det;
return result;
};
/**
* Computes the inverse of the provided matrix assuming it is
* an affine transformation matrix, where the upper left 3x3 elements
* are a rotation matrix, and the upper three elements in the fourth
* column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
* The matrix is not verified to be in the proper form.
* This method is faster than computing the inverse for a general 4x4
* matrix using {@link Matrix4.inverse}.
*
* @param {Matrix4} matrix The matrix to invert.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.inverseTransformation = function(matrix, result) {
Check.typeOf.object('matrix', matrix);
Check.typeOf.object('result', result);
//This function is an optimized version of the below 4 lines.
//var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
//var rTN = Matrix3.negate(rT);
//var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
//return Matrix4.fromRotationTranslation(rT, rTT, result);
var matrix0 = matrix[0];
var matrix1 = matrix[1];
var matrix2 = matrix[2];
var matrix4 = matrix[4];
var matrix5 = matrix[5];
var matrix6 = matrix[6];
var matrix8 = matrix[8];
var matrix9 = matrix[9];
var matrix10 = matrix[10];
var vX = matrix[12];
var vY = matrix[13];
var vZ = matrix[14];
var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
result[0] = matrix0;
result[1] = matrix4;
result[2] = matrix8;
result[3] = 0.0;
result[4] = matrix1;
result[5] = matrix5;
result[6] = matrix9;
result[7] = 0.0;
result[8] = matrix2;
result[9] = matrix6;
result[10] = matrix10;
result[11] = 0.0;
result[12] = x;
result[13] = y;
result[14] = z;
result[15] = 1.0;
return result;
};
/**
* An immutable Matrix4 instance initialized to the identity matrix.
*
* @type {Matrix4}
* @constant
*/
Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0));
/**
* An immutable Matrix4 instance initialized to the zero matrix.
*
* @type {Matrix4}
* @constant
*/
Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0));
/**
* The index into Matrix4 for column 0, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW0 = 0;
/**
* The index into Matrix4 for column 0, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW1 = 1;
/**
* The index into Matrix4 for column 0, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW2 = 2;
/**
* The index into Matrix4 for column 0, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW3 = 3;
/**
* The index into Matrix4 for column 1, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW0 = 4;
/**
* The index into Matrix4 for column 1, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW1 = 5;
/**
* The index into Matrix4 for column 1, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW2 = 6;
/**
* The index into Matrix4 for column 1, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW3 = 7;
/**
* The index into Matrix4 for column 2, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW0 = 8;
/**
* The index into Matrix4 for column 2, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW1 = 9;
/**
* The index into Matrix4 for column 2, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW2 = 10;
/**
* The index into Matrix4 for column 2, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW3 = 11;
/**
* The index into Matrix4 for column 3, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW0 = 12;
/**
* The index into Matrix4 for column 3, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW1 = 13;
/**
* The index into Matrix4 for column 3, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW2 = 14;
/**
* The index into Matrix4 for column 3, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW3 = 15;
defineProperties(Matrix4.prototype, {
/**
* Gets the number of items in the collection.
* @memberof Matrix4.prototype
*
* @type {Number}
*/
length : {
get : function() {
return Matrix4.packedLength;
}
}
});
/**
* Duplicates the provided Matrix4 instance.
*
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*/
Matrix4.prototype.clone = function(result) {
return Matrix4.clone(this, result);
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix4} [right] The right hand side matrix.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Matrix4.prototype.equals = function(right) {
return Matrix4.equals(this, right);
};
/**
* @private
*/
Matrix4.equalsArray = function(matrix, array, offset) {
return matrix[0] === array[offset] &&
matrix[1] === array[offset + 1] &&
matrix[2] === array[offset + 2] &&
matrix[3] === array[offset + 3] &&
matrix[4] === array[offset + 4] &&
matrix[5] === array[offset + 5] &&
matrix[6] === array[offset + 6] &&
matrix[7] === array[offset + 7] &&
matrix[8] === array[offset + 8] &&
matrix[9] === array[offset + 9] &&
matrix[10] === array[offset + 10] &&
matrix[11] === array[offset + 11] &&
matrix[12] === array[offset + 12] &&
matrix[13] === array[offset + 13] &&
matrix[14] === array[offset + 14] &&
matrix[15] === array[offset + 15];
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix4} [right] The right hand side matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
return Matrix4.equalsEpsilon(this, right, epsilon);
};
/**
* Computes a string representing this Matrix with each row being
* on a separate line and in the format '(column0, column1, column2, column3)'.
*
* @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
*/
Matrix4.prototype.toString = function() {
return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
'(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
'(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
'(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
};
return Matrix4;
});
/*global define*/
define('Core/Rectangle',[
'./Cartographic',
'./Check',
'./defaultValue',
'./defined',
'./defineProperties',
'./Ellipsoid',
'./freezeObject',
'./Math'
], function(
Cartographic,
Check,
defaultValue,
defined,
defineProperties,
Ellipsoid,
freezeObject,
CesiumMath) {
'use strict';
/**
* A two dimensional region specified as longitude and latitude coordinates.
*
* @alias Rectangle
* @constructor
*
* @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
* @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
* @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
* @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
*
* @see Packable
*/
function Rectangle(west, south, east, north) {
/**
* The westernmost longitude in radians in the range [-Pi, Pi].
*
* @type {Number}
* @default 0.0
*/
this.west = defaultValue(west, 0.0);
/**
* The southernmost latitude in radians in the range [-Pi/2, Pi/2].
*
* @type {Number}
* @default 0.0
*/
this.south = defaultValue(south, 0.0);
/**
* The easternmost longitude in radians in the range [-Pi, Pi].
*
* @type {Number}
* @default 0.0
*/
this.east = defaultValue(east, 0.0);
/**
* The northernmost latitude in radians in the range [-Pi/2, Pi/2].
*
* @type {Number}
* @default 0.0
*/
this.north = defaultValue(north, 0.0);
}
defineProperties(Rectangle.prototype, {
/**
* Gets the width of the rectangle in radians.
* @memberof Rectangle.prototype
* @type {Number}
*/
width : {
get : function() {
return Rectangle.computeWidth(this);
}
},
/**
* Gets the height of the rectangle in radians.
* @memberof Rectangle.prototype
* @type {Number}
*/
height : {
get : function() {
return Rectangle.computeHeight(this);
}
}
});
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Rectangle.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {Rectangle} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Rectangle.pack = function(value, array, startingIndex) {
Check.typeOf.object('value', value);
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.west;
array[startingIndex++] = value.south;
array[startingIndex++] = value.east;
array[startingIndex] = value.north;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Rectangle} [result] The object into which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
*/
Rectangle.unpack = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Rectangle();
}
result.west = array[startingIndex++];
result.south = array[startingIndex++];
result.east = array[startingIndex++];
result.north = array[startingIndex];
return result;
};
/**
* Computes the width of a rectangle in radians.
* @param {Rectangle} rectangle The rectangle to compute the width of.
* @returns {Number} The width.
*/
Rectangle.computeWidth = function(rectangle) {
Check.typeOf.object('rectangle', rectangle);
var east = rectangle.east;
var west = rectangle.west;
if (east < west) {
east += CesiumMath.TWO_PI;
}
return east - west;
};
/**
* Computes the height of a rectangle in radians.
* @param {Rectangle} rectangle The rectangle to compute the height of.
* @returns {Number} The height.
*/
Rectangle.computeHeight = function(rectangle) {
Check.typeOf.object('rectangle', rectangle);
return rectangle.north - rectangle.south;
};
/**
* Creates a rectangle given the boundary longitude and latitude in degrees.
*
* @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
* @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
* @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
* @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*
* @example
* var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
*/
Rectangle.fromDegrees = function(west, south, east, north, result) {
west = CesiumMath.toRadians(defaultValue(west, 0.0));
south = CesiumMath.toRadians(defaultValue(south, 0.0));
east = CesiumMath.toRadians(defaultValue(east, 0.0));
north = CesiumMath.toRadians(defaultValue(north, 0.0));
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Creates an rectangle given the boundary longitude and latitude in radians.
*
* @param {Number} [west=0.0] The westernmost longitude in radians in the range [-Math.PI, Math.PI].
* @param {Number} [south=0.0] The southernmost latitude in radians in the range [-Math.PI/2, Math.PI/2].
* @param {Number} [east=0.0] The easternmost longitude in radians in the range [-Math.PI, Math.PI].
* @param {Number} [north=0.0] The northernmost latitude in radians in the range [-Math.PI/2, Math.PI/2].
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*
* @example
* var rectangle = Cesium.Rectangle.fromRadians(0.0, Math.PI/4, Math.PI/8, 3*Math.PI/4);
*/
Rectangle.fromRadians = function(west, south, east, north, result) {
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = defaultValue(west, 0.0);
result.south = defaultValue(south, 0.0);
result.east = defaultValue(east, 0.0);
result.north = defaultValue(north, 0.0);
return result;
};
/**
* Creates the smallest possible Rectangle that encloses all positions in the provided array.
*
* @param {Cartographic[]} cartographics The list of Cartographic instances.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
Rectangle.fromCartographicArray = function(cartographics, result) {
Check.defined('cartographics', cartographics);
var west = Number.MAX_VALUE;
var east = -Number.MAX_VALUE;
var westOverIDL = Number.MAX_VALUE;
var eastOverIDL = -Number.MAX_VALUE;
var south = Number.MAX_VALUE;
var north = -Number.MAX_VALUE;
for ( var i = 0, len = cartographics.length; i < len; i++) {
var position = cartographics[i];
west = Math.min(west, position.longitude);
east = Math.max(east, position.longitude);
south = Math.min(south, position.latitude);
north = Math.max(north, position.latitude);
var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
westOverIDL = Math.min(westOverIDL, lonAdjusted);
eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
}
if(east - west > eastOverIDL - westOverIDL) {
west = westOverIDL;
east = eastOverIDL;
if (east > CesiumMath.PI) {
east = east - CesiumMath.TWO_PI;
}
if (west > CesiumMath.PI) {
west = west - CesiumMath.TWO_PI;
}
}
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Creates the smallest possible Rectangle that encloses all positions in the provided array.
*
* @param {Cartesian[]} cartesians The list of Cartesian instances.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
Check.defined('cartesians', cartesians);
var west = Number.MAX_VALUE;
var east = -Number.MAX_VALUE;
var westOverIDL = Number.MAX_VALUE;
var eastOverIDL = -Number.MAX_VALUE;
var south = Number.MAX_VALUE;
var north = -Number.MAX_VALUE;
for ( var i = 0, len = cartesians.length; i < len; i++) {
var position = ellipsoid.cartesianToCartographic(cartesians[i]);
west = Math.min(west, position.longitude);
east = Math.max(east, position.longitude);
south = Math.min(south, position.latitude);
north = Math.max(north, position.latitude);
var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
westOverIDL = Math.min(westOverIDL, lonAdjusted);
eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
}
if(east - west > eastOverIDL - westOverIDL) {
west = westOverIDL;
east = eastOverIDL;
if (east > CesiumMath.PI) {
east = east - CesiumMath.TWO_PI;
}
if (west > CesiumMath.PI) {
west = west - CesiumMath.TWO_PI;
}
}
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Duplicates a Rectangle.
*
* @param {Rectangle} rectangle The rectangle to clone.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
*/
Rectangle.clone = function(rectangle, result) {
if (!defined(rectangle)) {
return undefined;
}
if (!defined(result)) {
return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
}
result.west = rectangle.west;
result.south = rectangle.south;
result.east = rectangle.east;
result.north = rectangle.north;
return result;
};
/**
* Duplicates this Rectangle.
*
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
Rectangle.prototype.clone = function(result) {
return Rectangle.clone(this, result);
};
/**
* Compares the provided Rectangle with this Rectangle componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Rectangle} [other] The Rectangle to compare.
* @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
*/
Rectangle.prototype.equals = function(other) {
return Rectangle.equals(this, other);
};
/**
* Compares the provided rectangles and returns <code>true</code> if they are equal,
* <code>false</code> otherwise.
*
* @param {Rectangle} [left] The first Rectangle.
* @param {Rectangle} [right] The second Rectangle.
* @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
*/
Rectangle.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.west === right.west) &&
(left.south === right.south) &&
(left.east === right.east) &&
(left.north === right.north));
};
/**
* Compares the provided Rectangle with this Rectangle componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Rectangle} [other] The Rectangle to compare.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
*/
Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
Check.typeOf.number('epsilon', epsilon);
return defined(other) &&
(Math.abs(this.west - other.west) <= epsilon) &&
(Math.abs(this.south - other.south) <= epsilon) &&
(Math.abs(this.east - other.east) <= epsilon) &&
(Math.abs(this.north - other.north) <= epsilon);
};
/**
* Checks a Rectangle's properties and throws if they are not in valid ranges.
*
* @param {Rectangle} rectangle The rectangle to validate
*
* @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
* @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
* @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
* @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
*/
Rectangle.validate = function(rectangle) {
Check.typeOf.object('rectangle', rectangle);
var north = rectangle.north;
Check.typeOf.number.greaterThanOrEquals('north', north, -CesiumMath.PI_OVER_TWO);
Check.typeOf.number.lessThanOrEquals('north', north, CesiumMath.PI_OVER_TWO);
var south = rectangle.south;
Check.typeOf.number.greaterThanOrEquals('south', south, -CesiumMath.PI_OVER_TWO);
Check.typeOf.number.lessThanOrEquals('south', south, CesiumMath.PI_OVER_TWO);
var west = rectangle.west;
Check.typeOf.number.greaterThanOrEquals('west', west, -Math.PI);
Check.typeOf.number.lessThanOrEquals('west', west, Math.PI);
var east = rectangle.east;
Check.typeOf.number.greaterThanOrEquals('east', east, -Math.PI);
Check.typeOf.number.lessThanOrEquals('east', east, Math.PI);
};
/**
* Computes the southwest corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.southwest = function(rectangle, result) {
Check.typeOf.object('rectangle', rectangle);
if (!defined(result)) {
return new Cartographic(rectangle.west, rectangle.south);
}
result.longitude = rectangle.west;
result.latitude = rectangle.south;
result.height = 0.0;
return result;
};
/**
* Computes the northwest corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.northwest = function(rectangle, result) {
Check.typeOf.object('rectangle', rectangle);
if (!defined(result)) {
return new Cartographic(rectangle.west, rectangle.north);
}
result.longitude = rectangle.west;
result.latitude = rectangle.north;
result.height = 0.0;
return result;
};
/**
* Computes the northeast corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.northeast = function(rectangle, result) {
Check.typeOf.object('rectangle', rectangle);
if (!defined(result)) {
return new Cartographic(rectangle.east, rectangle.north);
}
result.longitude = rectangle.east;
result.latitude = rectangle.north;
result.height = 0.0;
return result;
};
/**
* Computes the southeast corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.southeast = function(rectangle, result) {
Check.typeOf.object('rectangle', rectangle);
if (!defined(result)) {
return new Cartographic(rectangle.east, rectangle.south);
}
result.longitude = rectangle.east;
result.latitude = rectangle.south;
result.height = 0.0;
return result;
};
/**
* Computes the center of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the center
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.center = function(rectangle, result) {
Check.typeOf.object('rectangle', rectangle);
var east = rectangle.east;
var west = rectangle.west;
if (east < west) {
east += CesiumMath.TWO_PI;
}
var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
var latitude = (rectangle.south + rectangle.north) * 0.5;
if (!defined(result)) {
return new Cartographic(longitude, latitude);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = 0.0;
return result;
};
/**
* Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
* latitude and longitude in radians and produces a correct intersection, taking into account the fact that
* the same angle can be represented with multiple values as well as the wrapping of longitude at the
* anti-meridian. For a simple intersection that ignores these factors and can be used with projected
* coordinates, see {@link Rectangle.simpleIntersection}.
*
* @param {Rectangle} rectangle On rectangle to find an intersection
* @param {Rectangle} otherRectangle Another rectangle to find an intersection
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
*/
Rectangle.intersection = function(rectangle, otherRectangle, result) {
Check.typeOf.object('rectangle', rectangle);
Check.typeOf.object('otherRectangle', otherRectangle);
var rectangleEast = rectangle.east;
var rectangleWest = rectangle.west;
var otherRectangleEast = otherRectangle.east;
var otherRectangleWest = otherRectangle.west;
if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
rectangleEast += CesiumMath.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
otherRectangleEast += CesiumMath.TWO_PI;
}
if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
otherRectangleWest += CesiumMath.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
rectangleWest += CesiumMath.TWO_PI;
}
var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
return undefined;
}
var south = Math.max(rectangle.south, otherRectangle.south);
var north = Math.min(rectangle.north, otherRectangle.north);
if (south >= north) {
return undefined;
}
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
* does not attempt to put the angular coordinates into a consistent range or to account for crossing the
* anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
* and longitude (i.e. projected coordinates).
*
* @param {Rectangle} rectangle On rectangle to find an intersection
* @param {Rectangle} otherRectangle Another rectangle to find an intersection
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
*/
Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
Check.typeOf.object('rectangle', rectangle);
Check.typeOf.object('otherRectangle', otherRectangle);
var west = Math.max(rectangle.west, otherRectangle.west);
var south = Math.max(rectangle.south, otherRectangle.south);
var east = Math.min(rectangle.east, otherRectangle.east);
var north = Math.min(rectangle.north, otherRectangle.north);
if (south >= north || west >= east) {
return undefined;
}
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Computes a rectangle that is the union of two rectangles.
*
* @param {Rectangle} rectangle A rectangle to enclose in rectangle.
* @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
Rectangle.union = function(rectangle, otherRectangle, result) {
Check.typeOf.object('rectangle', rectangle);
Check.typeOf.object('otherRectangle', otherRectangle);
if (!defined(result)) {
result = new Rectangle();
}
var rectangleEast = rectangle.east;
var rectangleWest = rectangle.west;
var otherRectangleEast = otherRectangle.east;
var otherRectangleWest = otherRectangle.west;
if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
rectangleEast += CesiumMath.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
otherRectangleEast += CesiumMath.TWO_PI;
}
if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
otherRectangleWest += CesiumMath.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
rectangleWest += CesiumMath.TWO_PI;
}
var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
result.west = west;
result.south = Math.min(rectangle.south, otherRectangle.south);
result.east = east;
result.north = Math.max(rectangle.north, otherRectangle.north);
return result;
};
/**
* Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
*
* @param {Rectangle} rectangle A rectangle to expand.
* @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
*/
Rectangle.expand = function(rectangle, cartographic, result) {
Check.typeOf.object('rectangle', rectangle);
Check.typeOf.object('cartographic', cartographic);
if (!defined(result)) {
result = new Rectangle();
}
result.west = Math.min(rectangle.west, cartographic.longitude);
result.south = Math.min(rectangle.south, cartographic.latitude);
result.east = Math.max(rectangle.east, cartographic.longitude);
result.north = Math.max(rectangle.north, cartographic.latitude);
return result;
};
/**
* Returns true if the cartographic is on or inside the rectangle, false otherwise.
*
* @param {Rectangle} rectangle The rectangle
* @param {Cartographic} cartographic The cartographic to test.
* @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
*/
Rectangle.contains = function(rectangle, cartographic) {
Check.typeOf.object('rectangle', rectangle);
Check.typeOf.object('cartographic', cartographic);
var longitude = cartographic.longitude;
var latitude = cartographic.latitude;
var west = rectangle.west;
var east = rectangle.east;
if (east < west) {
east += CesiumMath.TWO_PI;
if (longitude < 0.0) {
longitude += CesiumMath.TWO_PI;
}
}
return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
(longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
latitude >= rectangle.south &&
latitude <= rectangle.north;
};
var subsampleLlaScratch = new Cartographic();
/**
* Samples a rectangle so that it includes a list of Cartesian points suitable for passing to
* {@link BoundingSphere#fromPoints}. Sampling is necessary to account
* for rectangles that cover the poles or cross the equator.
*
* @param {Rectangle} rectangle The rectangle to subsample.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
* @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
* @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
* @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
*/
Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
Check.typeOf.object('rectangle', rectangle);
ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
surfaceHeight = defaultValue(surfaceHeight, 0.0);
if (!defined(result)) {
result = [];
}
var length = 0;
var north = rectangle.north;
var south = rectangle.south;
var east = rectangle.east;
var west = rectangle.west;
var lla = subsampleLlaScratch;
lla.height = surfaceHeight;
lla.longitude = west;
lla.latitude = north;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.longitude = east;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.latitude = south;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.longitude = west;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
if (north < 0.0) {
lla.latitude = north;
} else if (south > 0.0) {
lla.latitude = south;
} else {
lla.latitude = 0.0;
}
for ( var i = 1; i < 8; ++i) {
lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
if (Rectangle.contains(rectangle, lla)) {
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
}
}
if (lla.latitude === 0.0) {
lla.longitude = west;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.longitude = east;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
}
result.length = length;
return result;
};
/**
* The largest possible rectangle.
*
* @type {Rectangle}
* @constant
*/
Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
return Rectangle;
});
/*global define*/
define('Core/BoundingSphere',[
'./Cartesian3',
'./Cartographic',
'./Check',
'./defaultValue',
'./defined',
'./Ellipsoid',
'./GeographicProjection',
'./Intersect',
'./Interval',
'./Matrix3',
'./Matrix4',
'./Rectangle'
], function(
Cartesian3,
Cartographic,
Check,
defaultValue,
defined,
Ellipsoid,
GeographicProjection,
Intersect,
Interval,
Matrix3,
Matrix4,
Rectangle) {
'use strict';
/**
* A bounding sphere with a center and a radius.
* @alias BoundingSphere
* @constructor
*
* @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
* @param {Number} [radius=0.0] The radius of the bounding sphere.
*
* @see AxisAlignedBoundingBox
* @see BoundingRectangle
* @see Packable
*/
function BoundingSphere(center, radius) {
/**
* The center point of the sphere.
* @type {Cartesian3}
* @default {@link Cartesian3.ZERO}
*/
this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
/**
* The radius of the sphere.
* @type {Number}
* @default 0.0
*/
this.radius = defaultValue(radius, 0.0);
}
var fromPointsXMin = new Cartesian3();
var fromPointsYMin = new Cartesian3();
var fromPointsZMin = new Cartesian3();
var fromPointsXMax = new Cartesian3();
var fromPointsYMax = new Cartesian3();
var fromPointsZMax = new Cartesian3();
var fromPointsCurrentPos = new Cartesian3();
var fromPointsScratch = new Cartesian3();
var fromPointsRitterCenter = new Cartesian3();
var fromPointsMinBoxPt = new Cartesian3();
var fromPointsMaxBoxPt = new Cartesian3();
var fromPointsNaiveCenterScratch = new Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
* The bounding sphere is computed by running two algorithms, a naive algorithm and
* Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
*
* @param {Cartesian3[]} positions An array of points that the bounding sphere will enclose. Each point must have <code>x</code>, <code>y</code>, and <code>z</code> properties.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
BoundingSphere.fromPoints = function(positions, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(positions) || positions.length === 0) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
var numPositions = positions.length;
for (var i = 1; i < numPositions; i++) {
Cartesian3.clone(positions[i], currentPos);
var x = currentPos.x;
var y = currentPos.y;
var z = currentPos.z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
// Set the diameter endpoints to the largest span.
var diameter1 = xMin;
var diameter2 = xMax;
var maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
var ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
var ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
var minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
var maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
var naiveRadius = 0;
for (i = 0; i < numPositions; i++) {
Cartesian3.clone(positions[i], currentPos);
// Find the furthest point from the naive center to calculate the naive radius.
var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
if (oldCenterToPointSquared > radiusSquared) {
var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
var oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
var defaultProjection = new GeographicProjection();
var fromRectangle2DLowerLeft = new Cartesian3();
var fromRectangle2DUpperRight = new Cartesian3();
var fromRectangle2DSouthwest = new Cartographic();
var fromRectangle2DNortheast = new Cartographic();
/**
* Computes a bounding sphere from an rectangle projected in 2D.
*
* @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
* @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
};
/**
* Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
* object's minimum and maximum heights over the rectangle.
*
* @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
* @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
* @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(rectangle)) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
projection = defaultValue(projection, defaultProjection);
Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
fromRectangle2DSouthwest.height = minimumHeight;
Rectangle.northeast(rectangle, fromRectangle2DNortheast);
fromRectangle2DNortheast.height = maximumHeight;
var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
var width = upperRight.x - lowerLeft.x;
var height = upperRight.y - lowerLeft.y;
var elevation = upperRight.z - lowerLeft.z;
result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
var center = result.center;
center.x = lowerLeft.x + width * 0.5;
center.y = lowerLeft.y + height * 0.5;
center.z = lowerLeft.z + elevation * 0.5;
return result;
};
var fromRectangle3DScratch = [];
/**
* Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
* on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
*
* @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
* @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
surfaceHeight = defaultValue(surfaceHeight, 0.0);
var positions;
if (defined(rectangle)) {
positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
}
return BoundingSphere.fromPoints(positions, result);
};
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
* stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
* algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
* ensure a tight fit.
*
* @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
* origin of the coordinate system. This is useful when the positions are to be used for
* relative-to-center (RTC) rendering.
* @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
* be higher. Regardless of the value of this parameter, the X coordinate of the first position
* is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
* 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
* the stride is 5, however, two array elements are skipped and the next position begins at array
* index 5.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @example
* // Compute the bounding sphere from 3 positions, each specified relative to a center.
* // In addition to the X, Y, and Z coordinates, the points array contains two additional
* // elements per point which are ignored for the purpose of computing the bounding sphere.
* var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* var points = [1.0, 2.0, 3.0, 0.1, 0.2,
* 4.0, 5.0, 6.0, 0.1, 0.2,
* 7.0, 8.0, 9.0, 0.1, 0.2];
* var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
BoundingSphere.fromVertices = function(positions, center, stride, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(positions) || positions.length === 0) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
center = defaultValue(center, Cartesian3.ZERO);
stride = defaultValue(stride, 3);
Check.typeOf.number.greaterThanOrEquals('stride', stride, 3);
var currentPos = fromPointsCurrentPos;
currentPos.x = positions[0] + center.x;
currentPos.y = positions[1] + center.y;
currentPos.z = positions[2] + center.z;
var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
var numElements = positions.length;
for (var i = 0; i < numElements; i += stride) {
var x = positions[i] + center.x;
var y = positions[i + 1] + center.y;
var z = positions[i + 2] + center.z;
currentPos.x = x;
currentPos.y = y;
currentPos.z = z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
// Set the diameter endpoints to the largest span.
var diameter1 = xMin;
var diameter2 = xMax;
var maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
var ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
var ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
var minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
var maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
var naiveRadius = 0;
for (i = 0; i < numElements; i += stride) {
currentPos.x = positions[i] + center.x;
currentPos.y = positions[i + 1] + center.y;
currentPos.z = positions[i + 2] + center.z;
// Find the furthest point from the naive center to calculate the naive radius.
var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
if (oldCenterToPointSquared > radiusSquared) {
var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
var oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
/**
* Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
* stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
* algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
* ensure a tight fit.
*
* @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
var currentPos = fromPointsCurrentPos;
currentPos.x = positionsHigh[0] + positionsLow[0];
currentPos.y = positionsHigh[1] + positionsLow[1];
currentPos.z = positionsHigh[2] + positionsLow[2];
var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
var numElements = positionsHigh.length;
for (var i = 0; i < numElements; i += 3) {
var x = positionsHigh[i] + positionsLow[i];
var y = positionsHigh[i + 1] + positionsLow[i + 1];
var z = positionsHigh[i + 2] + positionsLow[i + 2];
currentPos.x = x;
currentPos.y = y;
currentPos.z = z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
// Set the diameter endpoints to the largest span.
var diameter1 = xMin;
var diameter2 = xMax;
var maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
var ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
var ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
var minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
var maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
var naiveRadius = 0;
for (i = 0; i < numElements; i += 3) {
currentPos.x = positionsHigh[i] + positionsLow[i];
currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
// Find the furthest point from the naive center to calculate the naive radius.
var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
if (oldCenterToPointSquared > radiusSquared) {
var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
var oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
/**
* Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
* tighly and fully encompases the box.
*
* @param {Cartesian3} [corner] The minimum height over the rectangle.
* @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* // Create a bounding sphere around the unit cube
* var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
*/
BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
Check.typeOf.object('corner', corner);
Check.typeOf.object('oppositeCorner', oppositeCorner);
if (!defined(result)) {
result = new BoundingSphere();
}
var center = result.center;
Cartesian3.add(corner, oppositeCorner, center);
Cartesian3.multiplyByScalar(center, 0.5, center);
result.radius = Cartesian3.distance(center, oppositeCorner);
return result;
};
/**
* Creates a bounding sphere encompassing an ellipsoid.
*
* @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
*/
BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
Check.typeOf.object('ellipsoid', ellipsoid);
if (!defined(result)) {
result = new BoundingSphere();
}
Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = ellipsoid.maximumRadius;
return result;
};
var fromBoundingSpheresScratch = new Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
*
* @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
var length = boundingSpheres.length;
if (length === 1) {
return BoundingSphere.clone(boundingSpheres[0], result);
}
if (length === 2) {
return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
}
var positions = [];
for (var i = 0; i < length; i++) {
positions.push(boundingSpheres[i].center);
}
result = BoundingSphere.fromPoints(positions, result);
var center = result.center;
var radius = result.radius;
for (i = 0; i < length; i++) {
var tmp = boundingSpheres[i];
radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
}
result.radius = radius;
return result;
};
var fromOrientedBoundingBoxScratchU = new Cartesian3();
var fromOrientedBoundingBoxScratchV = new Cartesian3();
var fromOrientedBoundingBoxScratchW = new Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
*
* @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
var halfAxes = orientedBoundingBox.halfAxes;
var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
var uHalf = Cartesian3.magnitude(u);
var vHalf = Cartesian3.magnitude(v);
var wHalf = Cartesian3.magnitude(w);
result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
result.radius = Math.max(uHalf, vHalf, wHalf);
return result;
};
/**
* Duplicates a BoundingSphere instance.
*
* @param {BoundingSphere} sphere The bounding sphere to duplicate.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
*/
BoundingSphere.clone = function(sphere, result) {
if (!defined(sphere)) {
return undefined;
}
if (!defined(result)) {
return new BoundingSphere(sphere.center, sphere.radius);
}
result.center = Cartesian3.clone(sphere.center, result.center);
result.radius = sphere.radius;
return result;
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
BoundingSphere.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {BoundingSphere} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
BoundingSphere.pack = function(value, array, startingIndex) {
Check.typeOf.object('value', value);
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
var center = value.center;
array[startingIndex++] = center.x;
array[startingIndex++] = center.y;
array[startingIndex++] = center.z;
array[startingIndex] = value.radius;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {BoundingSphere} [result] The object into which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*/
BoundingSphere.unpack = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new BoundingSphere();
}
var center = result.center;
center.x = array[startingIndex++];
center.y = array[startingIndex++];
center.z = array[startingIndex++];
result.radius = array[startingIndex];
return result;
};
var unionScratch = new Cartesian3();
var unionScratchCenter = new Cartesian3();
/**
* Computes a bounding sphere that contains both the left and right bounding spheres.
*
* @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.union = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
if (!defined(result)) {
result = new BoundingSphere();
}
var leftCenter = left.center;
var leftRadius = left.radius;
var rightCenter = right.center;
var rightRadius = right.radius;
var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
var centerSeparation = Cartesian3.magnitude(toRightCenter);
if (leftRadius >= (centerSeparation + rightRadius)) {
// Left sphere wins.
left.clone(result);
return result;
}
if (rightRadius >= (centerSeparation + leftRadius)) {
// Right sphere wins.
right.clone(result);
return result;
}
// There are two tangent points, one on far side of each sphere.
var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
// Compute the center point halfway between the two tangent points.
var center = Cartesian3.multiplyByScalar(toRightCenter,
(-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
Cartesian3.add(center, leftCenter, center);
Cartesian3.clone(center, result.center);
result.radius = halfDistanceBetweenTangentPoints;
return result;
};
var expandScratch = new Cartesian3();
/**
* Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
*
* @param {BoundingSphere} sphere A sphere to expand.
* @param {Cartesian3} point A point to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.expand = function(sphere, point, result) {
Check.typeOf.object('sphere', sphere);
Check.typeOf.object('point', point);
result = BoundingSphere.clone(sphere, result);
var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
if (radius > result.radius) {
result.radius = radius;
}
return result;
};
/**
* Determines which side of a plane a sphere is located.
*
* @param {BoundingSphere} sphere The bounding sphere to test.
* @param {Plane} plane The plane to test against.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
BoundingSphere.intersectPlane = function(sphere, plane) {
Check.typeOf.object('sphere', sphere);
Check.typeOf.object('plane', plane);
var center = sphere.center;
var radius = sphere.radius;
var normal = plane.normal;
var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
if (distanceToPlane < -radius) {
// The center point is negative side of the plane normal
return Intersect.OUTSIDE;
} else if (distanceToPlane < radius) {
// The center point is positive side of the plane, but radius extends beyond it; partial overlap
return Intersect.INTERSECTING;
}
return Intersect.INSIDE;
};
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.transform = function(sphere, transform, result) {
Check.typeOf.object('sphere', sphere);
Check.typeOf.object('transform', transform);
if (!defined(result)) {
result = new BoundingSphere();
}
result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
return result;
};
var distanceSquaredToScratch = new Cartesian3();
/**
* Computes the estimated distance squared from the closest point on a bounding sphere to a point.
*
* @param {BoundingSphere} sphere The sphere.
* @param {Cartesian3} cartesian The point
* @returns {Number} The estimated distance squared from the bounding sphere to the point.
*
* @example
* // Sort bounding spheres from back to front
* spheres.sort(function(a, b) {
* return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
* });
*/
BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
Check.typeOf.object('sphere', sphere);
Check.typeOf.object('cartesian', cartesian);
var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
};
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
* The transformation matrix is not verified to have a uniform scale of 1.
* This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
* var boundingSphere = new Cesium.BoundingSphere();
* var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
*/
BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
Check.typeOf.object('sphere', sphere);
Check.typeOf.object('transform', transform);
if (!defined(result)) {
result = new BoundingSphere();
}
result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
result.radius = sphere.radius;
return result;
};
var scratchCartesian3 = new Cartesian3();
/**
* The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
* plus/minus the radius of the bounding sphere.
* <br>
* If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
* closest and farthest planes from position that intersect the bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
* @param {Cartesian3} position The position to calculate the distance from.
* @param {Cartesian3} direction The direction from position.
* @param {Interval} [result] A Interval to store the nearest and farthest distances.
* @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
*/
BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
Check.typeOf.object('sphere', sphere);
Check.typeOf.object('position', position);
Check.typeOf.object('direction', direction);
if (!defined(result)) {
result = new Interval();
}
var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
var mag = Cartesian3.dot(direction, toCenter);
result.start = mag - sphere.radius;
result.stop = mag + sphere.radius;
return result;
};
var projectTo2DNormalScratch = new Cartesian3();
var projectTo2DEastScratch = new Cartesian3();
var projectTo2DNorthScratch = new Cartesian3();
var projectTo2DWestScratch = new Cartesian3();
var projectTo2DSouthScratch = new Cartesian3();
var projectTo2DCartographicScratch = new Cartographic();
var projectTo2DPositionsScratch = new Array(8);
for (var n = 0; n < 8; ++n) {
projectTo2DPositionsScratch[n] = new Cartesian3();
}
var projectTo2DProjection = new GeographicProjection();
/**
* Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
*
* @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
* @param {Object} [projection=GeographicProjection] The projection to 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.projectTo2D = function(sphere, projection, result) {
Check.typeOf.object('sphere', sphere);
projection = defaultValue(projection, projectTo2DProjection);
var ellipsoid = projection.ellipsoid;
var center = sphere.center;
var radius = sphere.radius;
var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
Cartesian3.normalize(east, east);
var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
Cartesian3.normalize(north, north);
Cartesian3.multiplyByScalar(normal, radius, normal);
Cartesian3.multiplyByScalar(north, radius, north);
Cartesian3.multiplyByScalar(east, radius, east);
var south = Cartesian3.negate(north, projectTo2DSouthScratch);
var west = Cartesian3.negate(east, projectTo2DWestScratch);
var positions = projectTo2DPositionsScratch;
// top NE corner
var corner = positions[0];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, east, corner);
// top NW corner
corner = positions[1];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, west, corner);
// top SW corner
corner = positions[2];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, west, corner);
// top SE corner
corner = positions[3];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, east, corner);
Cartesian3.negate(normal, normal);
// bottom NE corner
corner = positions[4];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, east, corner);
// bottom NW corner
corner = positions[5];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, west, corner);
// bottom SW corner
corner = positions[6];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, west, corner);
// bottom SE corner
corner = positions[7];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, east, corner);
var length = positions.length;
for (var i = 0; i < length; ++i) {
var position = positions[i];
Cartesian3.add(center, position, position);
var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
projection.project(cartographic, position);
}
result = BoundingSphere.fromPoints(positions, result);
// swizzle center components
center = result.center;
var x = center.x;
var y = center.y;
var z = center.z;
center.x = z;
center.y = x;
center.z = y;
return result;
};
/**
* Determines whether or not a sphere is hidden from view by the occluder.
*
* @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
* @param {Occluder} occluder The occluder.
* @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
*/
BoundingSphere.isOccluded = function(sphere, occluder) {
Check.typeOf.object('sphere', sphere);
Check.typeOf.object('occluder', occluder);
return !occluder.isBoundingSphereVisible(sphere);
};
/**
* Compares the provided BoundingSphere componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {BoundingSphere} [left] The first BoundingSphere.
* @param {BoundingSphere} [right] The second BoundingSphere.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
BoundingSphere.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
Cartesian3.equals(left.center, right.center) &&
left.radius === right.radius);
};
/**
* Determines which side of a plane the sphere is located.
*
* @param {Plane} plane The plane to test against.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
BoundingSphere.prototype.intersectPlane = function(plane) {
return BoundingSphere.intersectPlane(this, plane);
};
/**
* Computes the estimated distance squared from the closest point on a bounding sphere to a point.
*
* @param {Cartesian3} cartesian The point
* @returns {Number} The estimated distance squared from the bounding sphere to the point.
*
* @example
* // Sort bounding spheres from back to front
* spheres.sort(function(a, b) {
* return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
* });
*/
BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
return BoundingSphere.distanceSquaredTo(this, cartesian);
};
/**
* The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
* plus/minus the radius of the bounding sphere.
* <br>
* If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
* closest and farthest planes from position that intersect the bounding sphere.
*
* @param {Cartesian3} position The position to calculate the distance from.
* @param {Cartesian3} direction The direction from position.
* @param {Interval} [result] A Interval to store the nearest and farthest distances.
* @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
*/
BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
return BoundingSphere.computePlaneDistances(this, position, direction, result);
};
/**
* Determines whether or not a sphere is hidden from view by the occluder.
*
* @param {Occluder} occluder The occluder.
* @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
*/
BoundingSphere.prototype.isOccluded = function(occluder) {
return BoundingSphere.isOccluded(this, occluder);
};
/**
* Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {BoundingSphere} [right] The right hand side BoundingSphere.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
BoundingSphere.prototype.equals = function(right) {
return BoundingSphere.equals(this, right);
};
/**
* Duplicates this BoundingSphere instance.
*
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.prototype.clone = function(result) {
return BoundingSphere.clone(this, result);
};
return BoundingSphere;
});
/*global define*/
define('Core/Cartesian2',[
'./Check',
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
Check,
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
'use strict';
/**
* A 2D Cartesian point.
* @alias Cartesian2
* @constructor
*
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
*
* @see Cartesian3
* @see Cartesian4
* @see Packable
*/
function Cartesian2(x, y) {
/**
* The X component.
* @type {Number}
* @default 0.0
*/
this.x = defaultValue(x, 0.0);
/**
* The Y component.
* @type {Number}
* @default 0.0
*/
this.y = defaultValue(y, 0.0);
}
/**
* Creates a Cartesian2 instance from x and y coordinates.
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.fromElements = function(x, y, result) {
if (!defined(result)) {
return new Cartesian2(x, y);
}
result.x = x;
result.y = y;
return result;
};
/**
* Duplicates a Cartesian2 instance.
*
* @param {Cartesian2} cartesian The Cartesian to duplicate.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
Cartesian2.clone = function(cartesian, result) {
if (!defined(cartesian)) {
return undefined;
}
if (!defined(result)) {
return new Cartesian2(cartesian.x, cartesian.y);
}
result.x = cartesian.x;
result.y = cartesian.y;
return result;
};
/**
* Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
* x and y properties of the Cartesian3 and drops z.
* @function
*
* @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.fromCartesian3 = Cartesian2.clone;
/**
* Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
* x and y properties of the Cartesian4 and drops z and w.
* @function
*
* @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.fromCartesian4 = Cartesian2.clone;
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Cartesian2.packedLength = 2;
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian2} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Cartesian2.pack = function(value, array, startingIndex) {
Check.typeOf.object('value', value);
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex] = value.y;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian2} [result] The object into which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.unpack = function(array, startingIndex, result) {
Check.defined('array', array);
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Cartesian2();
}
result.x = array[startingIndex++];
result.y = array[startingIndex];
return result;
};
/**
* Flattens an array of Cartesian2s into and array of components.
*
* @param {Cartesian2[]} array The array of cartesians to pack.
* @param {Number[]} result The array onto which to store the result.
* @returns {Number[]} The packed array.
*/
Cartesian2.packArray = function(array, result) {
Check.defined('array', array);
var length = array.length;
if (!defined(result)) {
result = new Array(length * 2);
} else {
result.length = length * 2;
}
for (var i = 0; i < length; ++i) {
Cartesian2.pack(array[i], result, i * 2);
}
return result;
};
/**
* Unpacks an array of cartesian components into and array of Cartesian2s.
*
* @param {Number[]} array The array of components to unpack.
* @param {Cartesian2[]} result The array onto which to store the result.
* @returns {Cartesian2[]} The unpacked array.
*/
Cartesian2.unpackArray = function(array, result) {
Check.defined('array', array);
var length = array.length;
if (!defined(result)) {
result = new Array(length / 2);
} else {
result.length = length / 2;
}
for (var i = 0; i < length; i += 2) {
var index = i / 2;
result[index] = Cartesian2.unpack(array, i, result[index]);
}
return result;
};
/**
* Creates a Cartesian2 from two consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*
* @example
* // Create a Cartesian2 with (1.0, 2.0)
* var v = [1.0, 2.0];
* var p = Cesium.Cartesian2.fromArray(v);
*
* // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 2.0];
* var p2 = Cesium.Cartesian2.fromArray(v2, 2);
*/
Cartesian2.fromArray = Cartesian2.unpack;
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian2} cartesian The cartesian to use.
* @returns {Number} The value of the maximum component.
*/
Cartesian2.maximumComponent = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return Math.max(cartesian.x, cartesian.y);
};
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian2} cartesian The cartesian to use.
* @returns {Number} The value of the minimum component.
*/
Cartesian2.minimumComponent = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return Math.min(cartesian.x, cartesian.y);
};
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian2} first A cartesian to compare.
* @param {Cartesian2} second A cartesian to compare.
* @param {Cartesian2} result The object into which to store the result.
* @returns {Cartesian2} A cartesian with the minimum components.
*/
Cartesian2.minimumByComponent = function(first, second, result) {
Check.typeOf.object('first', first);
Check.typeOf.object('second', second);
Check.typeOf.object('result', result);
result.x = Math.min(first.x, second.x);
result.y = Math.min(first.y, second.y);
return result;
};
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian2} first A cartesian to compare.
* @param {Cartesian2} second A cartesian to compare.
* @param {Cartesian2} result The object into which to store the result.
* @returns {Cartesian2} A cartesian with the maximum components.
*/
Cartesian2.maximumByComponent = function(first, second, result) {
Check.typeOf.object('first', first);
Check.typeOf.object('second', second);
Check.typeOf.object('result', result);
result.x = Math.max(first.x, second.x);
result.y = Math.max(first.y, second.y);
return result;
};
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {Number} The squared magnitude.
*/
Cartesian2.magnitudeSquared = function(cartesian) {
Check.typeOf.object('cartesian', cartesian);
return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
};
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {Number} The magnitude.
*/
Cartesian2.magnitude = function(cartesian) {
return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
};
var distanceScratch = new Cartesian2();
/**
* Computes the distance between two points.
*
* @param {Cartesian2} left The first point to compute the distance from.
* @param {Cartesian2} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 1.0
* var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
*/
Cartesian2.distance = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian2.subtract(left, right, distanceScratch);
return Cartesian2.magnitude(distanceScratch);
};
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
*
* @param {Cartesian2} left The first point to compute the distance from.
* @param {Cartesian2} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
*/
Cartesian2.distanceSquared = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian2.subtract(left, right, distanceScratch);
return Cartesian2.magnitudeSquared(distanceScratch);
};
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian to be normalized.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.normalize = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var magnitude = Cartesian2.magnitude(cartesian);
result.x = cartesian.x / magnitude;
result.y = cartesian.y / magnitude;
if (isNaN(result.x) || isNaN(result.y)) {
throw new DeveloperError('normalized result is not a number');
}
return result;
};
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @returns {Number} The dot product.
*/
Cartesian2.dot = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
return left.x * right.x + left.y * right.y;
};
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.multiplyComponents = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x * right.x;
result.y = left.y * right.y;
return result;
};
/**
* Computes the componentwise quotient of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.divideComponents = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x / right.x;
result.y = left.y / right.y;
return result;
};
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.add = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x + right.x;
result.y = left.y + right.y;
return result;
};
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.subtract = function(left, right, result) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Check.typeOf.object('result', result);
result.x = left.x - right.x;
result.y = left.y - right.y;
return result;
};
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian2} cartesian The Cartesian to be scaled.
* @param {Number} scalar The scalar to multiply with.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result.x = cartesian.x * scalar;
result.y = cartesian.y * scalar;
return result;
};
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian2} cartesian The Cartesian to be divided.
* @param {Number} scalar The scalar to divide by.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.divideByScalar = function(cartesian, scalar, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.number('scalar', scalar);
Check.typeOf.object('result', result);
result.x = cartesian.x / scalar;
result.y = cartesian.y / scalar;
return result;
};
/**
* Negates the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian to be negated.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.negate = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result.x = -cartesian.x;
result.y = -cartesian.y;
return result;
};
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.abs = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
result.x = Math.abs(cartesian.x);
result.y = Math.abs(cartesian.y);
return result;
};
var lerpScratch = new Cartesian2();
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian2} start The value corresponding to t at 0.0.
* @param {Cartesian2} end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.lerp = function(start, end, t, result) {
Check.typeOf.object('start', start);
Check.typeOf.object('end', end);
Check.typeOf.number('t', t);
Check.typeOf.object('result', result);
Cartesian2.multiplyByScalar(end, t, lerpScratch);
result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
return Cartesian2.add(lerpScratch, result, result);
};
var angleBetweenScratch = new Cartesian2();
var angleBetweenScratch2 = new Cartesian2();
/**
* Returns the angle, in radians, between the provided Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @returns {Number} The angle between the Cartesians.
*/
Cartesian2.angleBetween = function(left, right) {
Check.typeOf.object('left', left);
Check.typeOf.object('right', right);
Cartesian2.normalize(left, angleBetweenScratch);
Cartesian2.normalize(right, angleBetweenScratch2);
return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
};
var mostOrthogonalAxisScratch = new Cartesian2();
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The most orthogonal axis.
*/
Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
Check.typeOf.object('cartesian', cartesian);
Check.typeOf.object('result', result);
var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
Cartesian2.abs(f, f);
if (f.x <= f.y) {
result = Cartesian2.clone(Cartesian2.UNIT_X, result);
} else {
result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
}
return result;
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian2} [left] The first Cartesian.
* @param {Cartesian2} [right] The second Cartesian.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartesian2.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.x === right.x) &&
(left.y === right.y));
};
/**
* @private
*/
Cartesian2.equalsArray = function(cartesian, array, offset) {
return cartesian.x === array[offset] &&
cartesian.y === array[offset + 1];
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian2} [left] The first Cartesian.
* @param {Cartesian2} [right] The second Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return (left === right) ||
(defined(left) &&
defined(right) &&
CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
};
/**
* An immutable Cartesian2 instance initialized to (0.0, 0.0).
*
* @type {Cartesian2}
* @constant
*/
Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
/**
* An immutable Cartesian2 instance initialized to (1.0, 0.0).
*
* @type {Cartesian2}
* @constant
*/
Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
/**
* An immutable Cartesian2 instance initialized to (0.0, 1.0).
*
* @type {Cartesian2}
* @constant
*/
Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
/**
* Duplicates this Cartesian2 instance.
*
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.prototype.clone = function(result) {
return Cartesian2.clone(this, result);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian2} [right] The right hand side Cartesian.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Cartesian2.prototype.equals = function(right) {
return Cartesian2.equals(this, right);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian2} [right] The right hand side Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
};
/**
* Creates a string representing this Cartesian in the format '(x, y)'.
*
* @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
*/
Cartesian2.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ')';
};
return Cartesian2;
});
/*global define*/
define('Core/Fullscreen',[
'./defined',
'./defineProperties'
], function(
defined,
defineProperties) {
'use strict';
var _supportsFullscreen;
var _names = {
requestFullscreen : undefined,
exitFullscreen : undefined,
fullscreenEnabled : undefined,
fullscreenElement : undefined,
fullscreenchange : undefined,
fullscreenerror : undefined
};
/**
* Browser-independent functions for working with the standard fullscreen API.
*
* @exports Fullscreen
*
* @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
*/
var Fullscreen = {};
defineProperties(Fullscreen, {
/**
* The element that is currently fullscreen, if any. To simply check if the
* browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {Object}
* @readonly
*/
element : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return document[_names.fullscreenElement];
}
},
/**
* The name of the event on the document that is fired when fullscreen is
* entered or exited. This event name is intended for use with addEventListener.
* In your event handler, to determine if the browser is in fullscreen mode or not,
* use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {String}
* @readonly
*/
changeEventName : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return _names.fullscreenchange;
}
},
/**
* The name of the event that is fired when a fullscreen error
* occurs. This event name is intended for use with addEventListener.
* @memberof Fullscreen
* @type {String}
* @readonly
*/
errorEventName : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return _names.fullscreenerror;
}
},
/**
* Determine whether the browser will allow an element to be made fullscreen, or not.
* For example, by default, iframes cannot go fullscreen unless the containing page
* adds an "allowfullscreen" attribute (or prefixed equivalent).
* @memberof Fullscreen
* @type {Boolean}
* @readonly
*/
enabled : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return document[_names.fullscreenEnabled];
}
},
/**
* Determines if the browser is currently in fullscreen mode.
* @memberof Fullscreen
* @type {Boolean}
* @readonly
*/
fullscreen : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return Fullscreen.element !== null;
}
}
});
/**
* Detects whether the browser supports the standard fullscreen API.
*
* @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
* <code>false</code> otherwise.
*/
Fullscreen.supportsFullscreen = function() {
if (defined(_supportsFullscreen)) {
return _supportsFullscreen;
}
_supportsFullscreen = false;
var body = document.body;
if (typeof body.requestFullscreen === 'function') {
// go with the unprefixed, standard set of names
_names.requestFullscreen = 'requestFullscreen';
_names.exitFullscreen = 'exitFullscreen';
_names.fullscreenEnabled = 'fullscreenEnabled';
_names.fullscreenElement = 'fullscreenElement';
_names.fullscreenchange = 'fullscreenchange';
_names.fullscreenerror = 'fullscreenerror';
_supportsFullscreen = true;
return _supportsFullscreen;
}
//check for the correct combination of prefix plus the various names that browsers use
var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
var name;
for (var i = 0, len = prefixes.length; i < len; ++i) {
var prefix = prefixes[i];
// casing of Fullscreen differs across browsers
name = prefix + 'RequestFullscreen';
if (typeof body[name] === 'function') {
_names.requestFullscreen = name;
_supportsFullscreen = true;
} else {
name = prefix + 'RequestFullScreen';
if (typeof body[name] === 'function') {
_names.requestFullscreen = name;
_supportsFullscreen = true;
}
}
// disagreement about whether it's "exit" as per spec, or "cancel"
name = prefix + 'ExitFullscreen';
if (typeof document[name] === 'function') {
_names.exitFullscreen = name;
} else {
name = prefix + 'CancelFullScreen';
if (typeof document[name] === 'function') {
_names.exitFullscreen = name;
}
}
// casing of Fullscreen differs across browsers
name = prefix + 'FullscreenEnabled';
if (document[name] !== undefined) {
_names.fullscreenEnabled = name;
} else {
name = prefix + 'FullScreenEnabled';
if (document[name] !== undefined) {
_names.fullscreenEnabled = name;
}
}
// casing of Fullscreen differs across browsers
name = prefix + 'FullscreenElement';
if (document[name] !== undefined) {
_names.fullscreenElement = name;
} else {
name = prefix + 'FullScreenElement';
if (document[name] !== undefined) {
_names.fullscreenElement = name;
}
}
// thankfully, event names are all lowercase per spec
name = prefix + 'fullscreenchange';
// event names do not have 'on' in the front, but the property on the document does
if (document['on' + name] !== undefined) {
//except on IE
if (prefix === 'ms') {
name = 'MSFullscreenChange';
}
_names.fullscreenchange = name;
}
name = prefix + 'fullscreenerror';
if (document['on' + name] !== undefined) {
//except on IE
if (prefix === 'ms') {
name = 'MSFullscreenError';
}
_names.fullscreenerror = name;
}
}
return _supportsFullscreen;
};
/**
* Asynchronously requests the browser to enter fullscreen mode on the given element.
* If fullscreen mode is not supported by the browser, does nothing.
*
* @param {Object} element The HTML element which will be placed into fullscreen mode.
* @param {HMDVRDevice} [vrDevice] The VR device.
*
* @example
* // Put the entire page into fullscreen.
* Cesium.Fullscreen.requestFullscreen(document.body)
*
* // Place only the Cesium canvas into fullscreen.
* Cesium.Fullscreen.requestFullscreen(scene.canvas)
*/
Fullscreen.requestFullscreen = function(element, vrDevice) {
if (!Fullscreen.supportsFullscreen()) {
return;
}
element[_names.requestFullscreen]({ vrDisplay: vrDevice });
};
/**
* Asynchronously exits fullscreen mode. If the browser is not currently
* in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
*/
Fullscreen.exitFullscreen = function() {
if (!Fullscreen.supportsFullscreen()) {
return;
}
document[_names.exitFullscreen]();
};
return Fullscreen;
});
/*global define*/
define('Core/FeatureDetection',[
'./defaultValue',
'./defined',
'./Fullscreen'
], function(
defaultValue,
defined,
Fullscreen) {
'use strict';
var theNavigator;
if (typeof navigator !== 'undefined') {
theNavigator = navigator;
} else {
theNavigator = {};
}
function extractVersion(versionString) {
var parts = versionString.split('.');
for (var i = 0, len = parts.length; i < len; ++i) {
parts[i] = parseInt(parts[i], 10);
}
return parts;
}
var isChromeResult;
var chromeVersionResult;
function isChrome() {
if (!defined(isChromeResult)) {
isChromeResult = false;
// Edge contains Chrome in the user agent too
if (!isEdge()) {
var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
if (fields !== null) {
isChromeResult = true;
chromeVersionResult = extractVersion(fields[1]);
}
}
}
return isChromeResult;
}
function chromeVersion() {
return isChrome() && chromeVersionResult;
}
var isSafariResult;
var safariVersionResult;
function isSafari() {
if (!defined(isSafariResult)) {
isSafariResult = false;
// Chrome and Edge contain Safari in the user agent too
if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
if (fields !== null) {
isSafariResult = true;
safariVersionResult = extractVersion(fields[1]);
}
}
}
return isSafariResult;
}
function safariVersion() {
return isSafari() && safariVersionResult;
}
var isWebkitResult;
var webkitVersionResult;
function isWebkit() {
if (!defined(isWebkitResult)) {
isWebkitResult = false;
var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
if (fields !== null) {
isWebkitResult = true;
webkitVersionResult = extractVersion(fields[1]);
webkitVersionResult.isNightly = !!fields[2];
}
}
return isWebkitResult;
}
function webkitVersion() {
return isWebkit() && webkitVersionResult;
}
var isInternetExplorerResult;
var internetExplorerVersionResult;
function isInternetExplorer() {
if (!defined(isInternetExplorerResult)) {
isInternetExplorerResult = false;
var fields;
if (theNavigator.appName === 'Microsoft Internet Explorer') {
fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
} else if (theNavigator.appName === 'Netscape') {
fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
}
}
return isInternetExplorerResult;
}
function internetExplorerVersion() {
return isInternetExplorer() && internetExplorerVersionResult;
}
var isEdgeResult;
var edgeVersionResult;
function isEdge() {
if (!defined(isEdgeResult)) {
isEdgeResult = false;
var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
if (fields !== null) {
isEdgeResult = true;
edgeVersionResult = extractVersion(fields[1]);
}
}
return isEdgeResult;
}
function edgeVersion() {
return isEdge() && edgeVersionResult;
}
var isFirefoxResult;
var firefoxVersionResult;
function isFirefox() {
if (!defined(isFirefoxResult)) {
isFirefoxResult = false;
var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isFirefoxResult = true;
firefoxVersionResult = extractVersion(fields[1]);
}
}
return isFirefoxResult;
}
var isWindowsResult;
function isWindows() {
if (!defined(isWindowsResult)) {
isWindowsResult = /Windows/i.test(theNavigator.appVersion);
}
return isWindowsResult;
}
function firefoxVersion() {
return isFirefox() && firefoxVersionResult;
}
var hasPointerEvents;
function supportsPointerEvents() {
if (!defined(hasPointerEvents)) {
//While navigator.pointerEnabled is deprecated in the W3C specification
//we still need to use it if it exists in order to support browsers
//that rely on it, such as the Windows WebBrowser control which defines
//PointerEvent but sets navigator.pointerEnabled to false.
hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
}
return hasPointerEvents;
}
var imageRenderingValueResult;
var supportsImageRenderingPixelatedResult;
function supportsImageRenderingPixelated() {
if (!defined(supportsImageRenderingPixelatedResult)) {
var canvas = document.createElement('canvas');
canvas.setAttribute('style',
'image-rendering: -moz-crisp-edges;' +
'image-rendering: pixelated;');
//canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
var tmp = canvas.style.imageRendering;
supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
if (supportsImageRenderingPixelatedResult) {
imageRenderingValueResult = tmp;
}
}
return supportsImageRenderingPixelatedResult;
}
function imageRenderingValue() {
return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
}
/**
* A set of functions to detect whether the current browser supports
* various features.
*
* @exports FeatureDetection
*/
var FeatureDetection = {
isChrome : isChrome,
chromeVersion : chromeVersion,
isSafari : isSafari,
safariVersion : safariVersion,
isWebkit : isWebkit,
webkitVersion : webkitVersion,
isInternetExplorer : isInternetExplorer,
internetExplorerVersion : internetExplorerVersion,
isEdge : isEdge,
edgeVersion : edgeVersion,
isFirefox : isFirefox,
firefoxVersion : firefoxVersion,
isWindows : isWindows,
hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
supportsPointerEvents : supportsPointerEvents,
supportsImageRenderingPixelated: supportsImageRenderingPixelated,
imageRenderingValue: imageRenderingValue
};
/**
* Detects whether the current browser supports the full screen standard.
*
* @returns {Boolean} true if the browser supports the full screen standard, false if not.
*
* @see Fullscreen
* @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
*/
FeatureDetection.supportsFullscreen = function() {
return Fullscreen.supportsFullscreen();
};
/**
* Detects whether the current browser supports typed arrays.
*
* @returns {Boolean} true if the browser supports typed arrays, false if not.
*
* @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
*/
FeatureDetection.supportsTypedArrays = function() {
return typeof ArrayBuffer !== 'undefined';
};
/**
* Detects whether the current browser supports Web Workers.
*
* @returns {Boolean} true if the browsers supports Web Workers, false if not.
*
* @see {@link http://www.w3.org/TR/workers/}
*/
FeatureDetection.supportsWebWorkers = function() {
return typeof Worker !== 'undefined';
};
return FeatureDetection;
});
/*global define*/
define('Core/WebGLConstants',[
'./freezeObject'
], function(
freezeObject) {
'use strict';
/**
* Enum containing WebGL Constant values by name.
* for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
* (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
*
* These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
* and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
* specifications.
*
* @exports WebGLConstants
*/
var WebGLConstants = {
DEPTH_BUFFER_BIT : 0x00000100,
STENCIL_BUFFER_BIT : 0x00000400,
COLOR_BUFFER_BIT : 0x00004000,
POINTS : 0x0000,
LINES : 0x0001,
LINE_LOOP : 0x0002,
LINE_STRIP : 0x0003,
TRIANGLES : 0x0004,
TRIANGLE_STRIP : 0x0005,
TRIANGLE_FAN : 0x0006,
ZERO : 0,
ONE : 1,
SRC_COLOR : 0x0300,
ONE_MINUS_SRC_COLOR : 0x0301,
SRC_ALPHA : 0x0302,
ONE_MINUS_SRC_ALPHA : 0x0303,
DST_ALPHA : 0x0304,
ONE_MINUS_DST_ALPHA : 0x0305,
DST_COLOR : 0x0306,
ONE_MINUS_DST_COLOR : 0x0307,
SRC_ALPHA_SATURATE : 0x0308,
FUNC_ADD : 0x8006,
BLEND_EQUATION : 0x8009,
BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
BLEND_EQUATION_ALPHA : 0x883D,
FUNC_SUBTRACT : 0x800A,
FUNC_REVERSE_SUBTRACT : 0x800B,
BLEND_DST_RGB : 0x80C8,
BLEND_SRC_RGB : 0x80C9,
BLEND_DST_ALPHA : 0x80CA,
BLEND_SRC_ALPHA : 0x80CB,
CONSTANT_COLOR : 0x8001,
ONE_MINUS_CONSTANT_COLOR : 0x8002,
CONSTANT_ALPHA : 0x8003,
ONE_MINUS_CONSTANT_ALPHA : 0x8004,
BLEND_COLOR : 0x8005,
ARRAY_BUFFER : 0x8892,
ELEMENT_ARRAY_BUFFER : 0x8893,
ARRAY_BUFFER_BINDING : 0x8894,
ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
STREAM_DRAW : 0x88E0,
STATIC_DRAW : 0x88E4,
DYNAMIC_DRAW : 0x88E8,
BUFFER_SIZE : 0x8764,
BUFFER_USAGE : 0x8765,
CURRENT_VERTEX_ATTRIB : 0x8626,
FRONT : 0x0404,
BACK : 0x0405,
FRONT_AND_BACK : 0x0408,
CULL_FACE : 0x0B44,
BLEND : 0x0BE2,
DITHER : 0x0BD0,
STENCIL_TEST : 0x0B90,
DEPTH_TEST : 0x0B71,
SCISSOR_TEST : 0x0C11,
POLYGON_OFFSET_FILL : 0x8037,
SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
SAMPLE_COVERAGE : 0x80A0,
NO_ERROR : 0,
INVALID_ENUM : 0x0500,
INVALID_VALUE : 0x0501,
INVALID_OPERATION : 0x0502,
OUT_OF_MEMORY : 0x0505,
CW : 0x0900,
CCW : 0x0901,
LINE_WIDTH : 0x0B21,
ALIASED_POINT_SIZE_RANGE : 0x846D,
ALIASED_LINE_WIDTH_RANGE : 0x846E,
CULL_FACE_MODE : 0x0B45,
FRONT_FACE : 0x0B46,
DEPTH_RANGE : 0x0B70,
DEPTH_WRITEMASK : 0x0B72,
DEPTH_CLEAR_VALUE : 0x0B73,
DEPTH_FUNC : 0x0B74,
STENCIL_CLEAR_VALUE : 0x0B91,
STENCIL_FUNC : 0x0B92,
STENCIL_FAIL : 0x0B94,
STENCIL_PASS_DEPTH_FAIL : 0x0B95,
STENCIL_PASS_DEPTH_PASS : 0x0B96,
STENCIL_REF : 0x0B97,
STENCIL_VALUE_MASK : 0x0B93,
STENCIL_WRITEMASK : 0x0B98,
STENCIL_BACK_FUNC : 0x8800,
STENCIL_BACK_FAIL : 0x8801,
STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
STENCIL_BACK_REF : 0x8CA3,
STENCIL_BACK_VALUE_MASK : 0x8CA4,
STENCIL_BACK_WRITEMASK : 0x8CA5,
VIEWPORT : 0x0BA2,
SCISSOR_BOX : 0x0C10,
COLOR_CLEAR_VALUE : 0x0C22,
COLOR_WRITEMASK : 0x0C23,
UNPACK_ALIGNMENT : 0x0CF5,
PACK_ALIGNMENT : 0x0D05,
MAX_TEXTURE_SIZE : 0x0D33,
MAX_VIEWPORT_DIMS : 0x0D3A,
SUBPIXEL_BITS : 0x0D50,
RED_BITS : 0x0D52,
GREEN_BITS : 0x0D53,
BLUE_BITS : 0x0D54,
ALPHA_BITS : 0x0D55,
DEPTH_BITS : 0x0D56,
STENCIL_BITS : 0x0D57,
POLYGON_OFFSET_UNITS : 0x2A00,
POLYGON_OFFSET_FACTOR : 0x8038,
TEXTURE_BINDING_2D : 0x8069,
SAMPLE_BUFFERS : 0x80A8,
SAMPLES : 0x80A9,
SAMPLE_COVERAGE_VALUE : 0x80AA,
SAMPLE_COVERAGE_INVERT : 0x80AB,
COMPRESSED_TEXTURE_FORMATS : 0x86A3,
DONT_CARE : 0x1100,
FASTEST : 0x1101,
NICEST : 0x1102,
GENERATE_MIPMAP_HINT : 0x8192,
BYTE : 0x1400,
UNSIGNED_BYTE : 0x1401,
SHORT : 0x1402,
UNSIGNED_SHORT : 0x1403,
INT : 0x1404,
UNSIGNED_INT : 0x1405,
FLOAT : 0x1406,
DEPTH_COMPONENT : 0x1902,
ALPHA : 0x1906,
RGB : 0x1907,
RGBA : 0x1908,
LUMINANCE : 0x1909,
LUMINANCE_ALPHA : 0x190A,
UNSIGNED_SHORT_4_4_4_4 : 0x8033,
UNSIGNED_SHORT_5_5_5_1 : 0x8034,
UNSIGNED_SHORT_5_6_5 : 0x8363,
FRAGMENT_SHADER : 0x8B30,
VERTEX_SHADER : 0x8B31,
MAX_VERTEX_ATTRIBS : 0x8869,
MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
MAX_VARYING_VECTORS : 0x8DFC,
MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
MAX_TEXTURE_IMAGE_UNITS : 0x8872,
MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
SHADER_TYPE : 0x8B4F,
DELETE_STATUS : 0x8B80,
LINK_STATUS : 0x8B82,
VALIDATE_STATUS : 0x8B83,
ATTACHED_SHADERS : 0x8B85,
ACTIVE_UNIFORMS : 0x8B86,
ACTIVE_ATTRIBUTES : 0x8B89,
SHADING_LANGUAGE_VERSION : 0x8B8C,
CURRENT_PROGRAM : 0x8B8D,
NEVER : 0x0200,
LESS : 0x0201,
EQUAL : 0x0202,
LEQUAL : 0x0203,
GREATER : 0x0204,
NOTEQUAL : 0x0205,
GEQUAL : 0x0206,
ALWAYS : 0x0207,
KEEP : 0x1E00,
REPLACE : 0x1E01,
INCR : 0x1E02,
DECR : 0x1E03,
INVERT : 0x150A,
INCR_WRAP : 0x8507,
DECR_WRAP : 0x8508,
VENDOR : 0x1F00,
RENDERER : 0x1F01,
VERSION : 0x1F02,
NEAREST : 0x2600,
LINEAR : 0x2601,
NEAREST_MIPMAP_NEAREST : 0x2700,
LINEAR_MIPMAP_NEAREST : 0x2701,
NEAREST_MIPMAP_LINEAR : 0x2702,
LINEAR_MIPMAP_LINEAR : 0x2703,
TEXTURE_MAG_FILTER : 0x2800,
TEXTURE_MIN_FILTER : 0x2801,
TEXTURE_WRAP_S : 0x2802,
TEXTURE_WRAP_T : 0x2803,
TEXTURE_2D : 0x0DE1,
TEXTURE : 0x1702,
TEXTURE_CUBE_MAP : 0x8513,
TEXTURE_BINDING_CUBE_MAP : 0x8514,
TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
TEXTURE0 : 0x84C0,
TEXTURE1 : 0x84C1,
TEXTURE2 : 0x84C2,
TEXTURE3 : 0x84C3,
TEXTURE4 : 0x84C4,
TEXTURE5 : 0x84C5,
TEXTURE6 : 0x84C6,
TEXTURE7 : 0x84C7,
TEXTURE8 : 0x84C8,
TEXTURE9 : 0x84C9,
TEXTURE10 : 0x84CA,
TEXTURE11 : 0x84CB,
TEXTURE12 : 0x84CC,
TEXTURE13 : 0x84CD,
TEXTURE14 : 0x84CE,
TEXTURE15 : 0x84CF,
TEXTURE16 : 0x84D0,
TEXTURE17 : 0x84D1,
TEXTURE18 : 0x84D2,
TEXTURE19 : 0x84D3,
TEXTURE20 : 0x84D4,
TEXTURE21 : 0x84D5,
TEXTURE22 : 0x84D6,
TEXTURE23 : 0x84D7,
TEXTURE24 : 0x84D8,
TEXTURE25 : 0x84D9,
TEXTURE26 : 0x84DA,
TEXTURE27 : 0x84DB,
TEXTURE28 : 0x84DC,
TEXTURE29 : 0x84DD,
TEXTURE30 : 0x84DE,
TEXTURE31 : 0x84DF,
ACTIVE_TEXTURE : 0x84E0,
REPEAT : 0x2901,
CLAMP_TO_EDGE : 0x812F,
MIRRORED_REPEAT : 0x8370,
FLOAT_VEC2 : 0x8B50,
FLOAT_VEC3 : 0x8B51,
FLOAT_VEC4 : 0x8B52,
INT_VEC2 : 0x8B53,
INT_VEC3 : 0x8B54,
INT_VEC4 : 0x8B55,
BOOL : 0x8B56,
BOOL_VEC2 : 0x8B57,
BOOL_VEC3 : 0x8B58,
BOOL_VEC4 : 0x8B59,
FLOAT_MAT2 : 0x8B5A,
FLOAT_MAT3 : 0x8B5B,
FLOAT_MAT4 : 0x8B5C,
SAMPLER_2D : 0x8B5E,
SAMPLER_CUBE : 0x8B60,
VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
COMPILE_STATUS : 0x8B81,
LOW_FLOAT : 0x8DF0,
MEDIUM_FLOAT : 0x8DF1,
HIGH_FLOAT : 0x8DF2,
LOW_INT : 0x8DF3,
MEDIUM_INT : 0x8DF4,
HIGH_INT : 0x8DF5,
FRAMEBUFFER : 0x8D40,
RENDERBUFFER : 0x8D41,
RGBA4 : 0x8056,
RGB5_A1 : 0x8057,
RGB565 : 0x8D62,
DEPTH_COMPONENT16 : 0x81A5,
STENCIL_INDEX : 0x1901,
STENCIL_INDEX8 : 0x8D48,
DEPTH_STENCIL : 0x84F9,
RENDERBUFFER_WIDTH : 0x8D42,
RENDERBUFFER_HEIGHT : 0x8D43,
RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
RENDERBUFFER_RED_SIZE : 0x8D50,
RENDERBUFFER_GREEN_SIZE : 0x8D51,
RENDERBUFFER_BLUE_SIZE : 0x8D52,
RENDERBUFFER_ALPHA_SIZE : 0x8D53,
RENDERBUFFER_DEPTH_SIZE : 0x8D54,
RENDERBUFFER_STENCIL_SIZE : 0x8D55,
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
COLOR_ATTACHMENT0 : 0x8CE0,
DEPTH_ATTACHMENT : 0x8D00,
STENCIL_ATTACHMENT : 0x8D20,
DEPTH_STENCIL_ATTACHMENT : 0x821A,
NONE : 0,
FRAMEBUFFER_COMPLETE : 0x8CD5,
FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
FRAMEBUFFER_BINDING : 0x8CA6,
RENDERBUFFER_BINDING : 0x8CA7,
MAX_RENDERBUFFER_SIZE : 0x84E8,
INVALID_FRAMEBUFFER_OPERATION : 0x0506,
UNPACK_FLIP_Y_WEBGL : 0x9240,
UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
CONTEXT_LOST_WEBGL : 0x9242,
UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
BROWSER_DEFAULT_WEBGL : 0x9244,
// WEBGL_compressed_texture_s3tc
COMPRESSED_RGB_S3TC_DXT1_EXT : 0x83F0,
COMPRESSED_RGBA_S3TC_DXT1_EXT : 0x83F1,
COMPRESSED_RGBA_S3TC_DXT3_EXT : 0x83F2,
COMPRESSED_RGBA_S3TC_DXT5_EXT : 0x83F3,
// WEBGL_compressed_texture_pvrtc
COMPRESSED_RGB_PVRTC_4BPPV1_IMG : 0x8C00,
COMPRESSED_RGB_PVRTC_2BPPV1_IMG : 0x8C01,
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : 0x8C02,
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : 0x8C03,
// WEBGL_compressed_texture_etc1
COMPRESSED_RGB_ETC1_WEBGL : 0x8D64,
// Desktop OpenGL
DOUBLE : 0x140A,
// WebGL 2
READ_BUFFER : 0x0C02,
UNPACK_ROW_LENGTH : 0x0CF2,
UNPACK_SKIP_ROWS : 0x0CF3,
UNPACK_SKIP_PIXELS : 0x0CF4,
PACK_ROW_LENGTH : 0x0D02,
PACK_SKIP_ROWS : 0x0D03,
PACK_SKIP_PIXELS : 0x0D04,
COLOR : 0x1800,
DEPTH : 0x1801,
STENCIL : 0x1802,
RED : 0x1903,
RGB8 : 0x8051,
RGBA8 : 0x8058,
RGB10_A2 : 0x8059,
TEXTURE_BINDING_3D : 0x806A,
UNPACK_SKIP_IMAGES : 0x806D,
UNPACK_IMAGE_HEIGHT : 0x806E,
TEXTURE_3D : 0x806F,
TEXTURE_WRAP_R : 0x8072,
MAX_3D_TEXTURE_SIZE : 0x8073,
UNSIGNED_INT_2_10_10_10_REV : 0x8368,
MAX_ELEMENTS_VERTICES : 0x80E8,
MAX_ELEMENTS_INDICES : 0x80E9,
TEXTURE_MIN_LOD : 0x813A,
TEXTURE_MAX_LOD : 0x813B,
TEXTURE_BASE_LEVEL : 0x813C,
TEXTURE_MAX_LEVEL : 0x813D,
MIN : 0x8007,
MAX : 0x8008,
DEPTH_COMPONENT24 : 0x81A6,
MAX_TEXTURE_LOD_BIAS : 0x84FD,
TEXTURE_COMPARE_MODE : 0x884C,
TEXTURE_COMPARE_FUNC : 0x884D,
CURRENT_QUERY : 0x8865,
QUERY_RESULT : 0x8866,
QUERY_RESULT_AVAILABLE : 0x8867,
STREAM_READ : 0x88E1,
STREAM_COPY : 0x88E2,
STATIC_READ : 0x88E5,
STATIC_COPY : 0x88E6,
DYNAMIC_READ : 0x88E9,
DYNAMIC_COPY : 0x88EA,
MAX_DRAW_BUFFERS : 0x8824,
DRAW_BUFFER0 : 0x8825,
DRAW_BUFFER1 : 0x8826,
DRAW_BUFFER2 : 0x8827,
DRAW_BUFFER3 : 0x8828,
DRAW_BUFFER4 : 0x8829,
DRAW_BUFFER5 : 0x882A,
DRAW_BUFFER6 : 0x882B,
DRAW_BUFFER7 : 0x882C,
DRAW_BUFFER8 : 0x882D,
DRAW_BUFFER9 : 0x882E,
DRAW_BUFFER10 : 0x882F,
DRAW_BUFFER11 : 0x8830,
DRAW_BUFFER12 : 0x8831,
DRAW_BUFFER13 : 0x8832,
DRAW_BUFFER14 : 0x8833,
DRAW_BUFFER15 : 0x8834,
MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
SAMPLER_3D : 0x8B5F,
SAMPLER_2D_SHADOW : 0x8B62,
FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
PIXEL_PACK_BUFFER : 0x88EB,
PIXEL_UNPACK_BUFFER : 0x88EC,
PIXEL_PACK_BUFFER_BINDING : 0x88ED,
PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
FLOAT_MAT2x3 : 0x8B65,
FLOAT_MAT2x4 : 0x8B66,
FLOAT_MAT3x2 : 0x8B67,
FLOAT_MAT3x4 : 0x8B68,
FLOAT_MAT4x2 : 0x8B69,
FLOAT_MAT4x3 : 0x8B6A,
SRGB : 0x8C40,
SRGB8 : 0x8C41,
SRGB8_ALPHA8 : 0x8C43,
COMPARE_REF_TO_TEXTURE : 0x884E,
RGBA32F : 0x8814,
RGB32F : 0x8815,
RGBA16F : 0x881A,
RGB16F : 0x881B,
VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
MAX_VARYING_COMPONENTS : 0x8B4B,
TEXTURE_2D_ARRAY : 0x8C1A,
TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
R11F_G11F_B10F : 0x8C3A,
UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
RGB9_E5 : 0x8C3D,
UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
RASTERIZER_DISCARD : 0x8C89,
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
INTERLEAVED_ATTRIBS : 0x8C8C,
SEPARATE_ATTRIBS : 0x8C8D,
TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
RGBA32UI : 0x8D70,
RGB32UI : 0x8D71,
RGBA16UI : 0x8D76,
RGB16UI : 0x8D77,
RGBA8UI : 0x8D7C,
RGB8UI : 0x8D7D,
RGBA32I : 0x8D82,
RGB32I : 0x8D83,
RGBA16I : 0x8D88,
RGB16I : 0x8D89,
RGBA8I : 0x8D8E,
RGB8I : 0x8D8F,
RED_INTEGER : 0x8D94,
RGB_INTEGER : 0x8D98,
RGBA_INTEGER : 0x8D99,
SAMPLER_2D_ARRAY : 0x8DC1,
SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
SAMPLER_CUBE_SHADOW : 0x8DC5,
UNSIGNED_INT_VEC2 : 0x8DC6,
UNSIGNED_INT_VEC3 : 0x8DC7,
UNSIGNED_INT_VEC4 : 0x8DC8,
INT_SAMPLER_2D : 0x8DCA,
INT_SAMPLER_3D : 0x8DCB,
INT_SAMPLER_CUBE : 0x8DCC,
INT_SAMPLER_2D_ARRAY : 0x8DCF,
UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
DEPTH_COMPONENT32F : 0x8CAC,
DEPTH32F_STENCIL8 : 0x8CAD,
FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
FRAMEBUFFER_DEFAULT : 0x8218,
UNSIGNED_INT_24_8 : 0x84FA,
DEPTH24_STENCIL8 : 0x88F0,
UNSIGNED_NORMALIZED : 0x8C17,
DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
READ_FRAMEBUFFER : 0x8CA8,
DRAW_FRAMEBUFFER : 0x8CA9,
READ_FRAMEBUFFER_BINDING : 0x8CAA,
RENDERBUFFER_SAMPLES : 0x8CAB,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
MAX_COLOR_ATTACHMENTS : 0x8CDF,
COLOR_ATTACHMENT1 : 0x8CE1,
COLOR_ATTACHMENT2 : 0x8CE2,
COLOR_ATTACHMENT3 : 0x8CE3,
COLOR_ATTACHMENT4 : 0x8CE4,
COLOR_ATTACHMENT5 : 0x8CE5,
COLOR_ATTACHMENT6 : 0x8CE6,
COLOR_ATTACHMENT7 : 0x8CE7,
COLOR_ATTACHMENT8 : 0x8CE8,
COLOR_ATTACHMENT9 : 0x8CE9,
COLOR_ATTACHMENT10 : 0x8CEA,
COLOR_ATTACHMENT11 : 0x8CEB,
COLOR_ATTACHMENT12 : 0x8CEC,
COLOR_ATTACHMENT13 : 0x8CED,
COLOR_ATTACHMENT14 : 0x8CEE,
COLOR_ATTACHMENT15 : 0x8CEF,
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
MAX_SAMPLES : 0x8D57,
HALF_FLOAT : 0x140B,
RG : 0x8227,
RG_INTEGER : 0x8228,
R8 : 0x8229,
RG8 : 0x822B,
R16F : 0x822D,
R32F : 0x822E,
RG16F : 0x822F,
RG32F : 0x8230,
R8I : 0x8231,
R8UI : 0x8232,
R16I : 0x8233,
R16UI : 0x8234,
R32I : 0x8235,
R32UI : 0x8236,
RG8I : 0x8237,
RG8UI : 0x8238,
RG16I : 0x8239,
RG16UI : 0x823A,
RG32I : 0x823B,
RG32UI : 0x823C,
VERTEX_ARRAY_BINDING : 0x85B5,
R8_SNORM : 0x8F94,
RG8_SNORM : 0x8F95,
RGB8_SNORM : 0x8F96,
RGBA8_SNORM : 0x8F97,
SIGNED_NORMALIZED : 0x8F9C,
COPY_READ_BUFFER : 0x8F36,
COPY_WRITE_BUFFER : 0x8F37,
COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
UNIFORM_BUFFER : 0x8A11,
UNIFORM_BUFFER_BINDING : 0x8A28,
UNIFORM_BUFFER_START : 0x8A29,
UNIFORM_BUFFER_SIZE : 0x8A2A,
MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
ACTIVE_UNIFORM_BLOCKS : 0x8A36,
UNIFORM_TYPE : 0x8A37,
UNIFORM_SIZE : 0x8A38,
UNIFORM_BLOCK_INDEX : 0x8A3A,
UNIFORM_OFFSET : 0x8A3B,
UNIFORM_ARRAY_STRIDE : 0x8A3C,
UNIFORM_MATRIX_STRIDE : 0x8A3D,
UNIFORM_IS_ROW_MAJOR : 0x8A3E,
UNIFORM_BLOCK_BINDING : 0x8A3F,
UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
INVALID_INDEX : 0xFFFFFFFF,
MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
MAX_SERVER_WAIT_TIMEOUT : 0x9111,
OBJECT_TYPE : 0x9112,
SYNC_CONDITION : 0x9113,
SYNC_STATUS : 0x9114,
SYNC_FLAGS : 0x9115,
SYNC_FENCE : 0x9116,
SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
UNSIGNALED : 0x9118,
SIGNALED : 0x9119,
ALREADY_SIGNALED : 0x911A,
TIMEOUT_EXPIRED : 0x911B,
CONDITION_SATISFIED : 0x911C,
WAIT_FAILED : 0x911D,
SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
ANY_SAMPLES_PASSED : 0x8C2F,
ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
SAMPLER_BINDING : 0x8919,
RGB10_A2UI : 0x906F,
INT_2_10_10_10_REV : 0x8D9F,
TRANSFORM_FEEDBACK : 0x8E22,
TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
TRANSFORM_FEEDBACK_BINDING : 0x8E25,
COMPRESSED_R11_EAC : 0x9270,
COMPRESSED_SIGNED_R11_EAC : 0x9271,
COMPRESSED_RG11_EAC : 0x9272,
COMPRESSED_SIGNED_RG11_EAC : 0x9273,
COMPRESSED_RGB8_ETC2 : 0x9274,
COMPRESSED_SRGB8_ETC2 : 0x9275,
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
TEXTURE_IMMUTABLE_FORMAT : 0x912F,
MAX_ELEMENT_INDEX : 0x8D6B,
TEXTURE_IMMUTABLE_LEVELS : 0x82DF,
// Extensions
MAX_TEXTURE_MAX_ANISOTROPY_EXT : 0x84FF
};
return freezeObject(WebGLConstants);
});
/*global define*/
define('Core/ComponentDatatype',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./FeatureDetection',
'./freezeObject',
'./WebGLConstants'
], function(
defaultValue,
defined,
DeveloperError,
FeatureDetection,
freezeObject,
WebGLConstants) {
'use strict';
// Bail out if the browser doesn't support typed arrays, to prevent the setup function
// from failing, since we won't be able to create a WebGL context anyway.
if (!FeatureDetection.supportsTypedArrays()) {
return {};
}
/**
* WebGL component datatypes. Components are intrinsics,
* which form attributes, which form vertices.
*
* @exports ComponentDatatype
*/
var ComponentDatatype = {
/**
* 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
* of an element in <code>Int8Array</code>.
*
* @type {Number}
* @constant
*/
BYTE : WebGLConstants.BYTE,
/**
* 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
* of an element in <code>Uint8Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
/**
* 16-bit signed short corresponding to <code>SHORT</code> and the type
* of an element in <code>Int16Array</code>.
*
* @type {Number}
* @constant
*/
SHORT : WebGLConstants.SHORT,
/**
* 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
* of an element in <code>Uint16Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
/**
* 32-bit signed int corresponding to <code>INT</code> and the type
* of an element in <code>Int32Array</code>.
*
* @memberOf ComponentDatatype
*
* @type {Number}
* @constant
*/
INT : WebGLConstants.INT,
/**
* 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
* of an element in <code>Uint32Array</code>.
*
* @memberOf ComponentDatatype
*
* @type {Number}
* @constant
*/
UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
/**
* 32-bit floating-point corresponding to <code>FLOAT</code> and the type
* of an element in <code>Float32Array</code>.
*
* @type {Number}
* @constant
*/
FLOAT : WebGLConstants.FLOAT,
/**
* 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
* this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
* and the type of an element in <code>Float64Array</code>.
*
* @memberOf ComponentDatatype
*
* @type {Number}
* @constant
* @default 0x140A
*/
DOUBLE : WebGLConstants.DOUBLE
};
/**
* Returns the size, in bytes, of the corresponding datatype.
*
* @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
* @returns {Number} The size in bytes.
*
* @exception {DeveloperError} componentDatatype is not a valid value.
*
* @example
* // Returns Int8Array.BYTES_PER_ELEMENT
* var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
*/
ComponentDatatype.getSizeInBytes = function(componentDatatype){
if (!defined(componentDatatype)) {
throw new DeveloperError('value is required.');
}
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return Int8Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_BYTE:
return Uint8Array.BYTES_PER_ELEMENT;
case ComponentDatatype.SHORT:
return Int16Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_SHORT:
return Uint16Array.BYTES_PER_ELEMENT;
case ComponentDatatype.INT:
return Int32Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_INT:
return Uint32Array.BYTES_PER_ELEMENT;
case ComponentDatatype.FLOAT:
return Float32Array.BYTES_PER_ELEMENT;
case ComponentDatatype.DOUBLE:
return Float64Array.BYTES_PER_ELEMENT;
default:
throw new DeveloperError('componentDatatype is not a valid value.');
}
};
/**
* Gets the {@link ComponentDatatype} for the provided TypedArray instance.
*
* @param {TypedArray} array The typed array.
* @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
*/
ComponentDatatype.fromTypedArray = function(array) {
if (array instanceof Int8Array) {
return ComponentDatatype.BYTE;
}
if (array instanceof Uint8Array) {
return ComponentDatatype.UNSIGNED_BYTE;
}
if (array instanceof Int16Array) {
return ComponentDatatype.SHORT;
}
if (array instanceof Uint16Array) {
return ComponentDatatype.UNSIGNED_SHORT;
}
if (array instanceof Int32Array) {
return ComponentDatatype.INT;
}
if (array instanceof Uint32Array) {
return ComponentDatatype.UNSIGNED_INT;
}
if (array instanceof Float32Array) {
return ComponentDatatype.FLOAT;
}
if (array instanceof Float64Array) {
return ComponentDatatype.DOUBLE;
}
};
/**
* Validates that the provided component datatype is a valid {@link ComponentDatatype}
*
* @param {ComponentDatatype} componentDatatype The component datatype to validate.
* @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
*
* @example
* if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
* throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
* }
*/
ComponentDatatype.validate = function(componentDatatype) {
return defined(componentDatatype) &&
(componentDatatype === ComponentDatatype.BYTE ||
componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
componentDatatype === ComponentDatatype.SHORT ||
componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
componentDatatype === ComponentDatatype.INT ||
componentDatatype === ComponentDatatype.UNSIGNED_INT ||
componentDatatype === ComponentDatatype.FLOAT ||
componentDatatype === ComponentDatatype.DOUBLE);
};
/**
* Creates a typed array corresponding to component data type.
*
* @param {ComponentDatatype} componentDatatype The component data type.
* @param {Number|Array} valuesOrLength The length of the array to create or an array.
* @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
*
* @exception {DeveloperError} componentDatatype is not a valid value.
*
* @example
* // creates a Float32Array with length of 100
* var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
*/
ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
if (!defined(componentDatatype)) {
throw new DeveloperError('componentDatatype is required.');
}
if (!defined(valuesOrLength)) {
throw new DeveloperError('valuesOrLength is required.');
}
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return new Int8Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_BYTE:
return new Uint8Array(valuesOrLength);
case ComponentDatatype.SHORT:
return new Int16Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_SHORT:
return new Uint16Array(valuesOrLength);
case ComponentDatatype.INT:
return new Int32Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_INT:
return new Uint32Array(valuesOrLength);
case ComponentDatatype.FLOAT:
return new Float32Array(valuesOrLength);
case ComponentDatatype.DOUBLE:
return new Float64Array(valuesOrLength);
default:
throw new DeveloperError('componentDatatype is not a valid value.');
}
};
/**
* Creates a typed view of an array of bytes.
*
* @param {ComponentDatatype} componentDatatype The type of the view to create.
* @param {ArrayBuffer} buffer The buffer storage to use for the view.
* @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
* @param {Number} [length] The number of elements in the view.
* @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
*
* @exception {DeveloperError} componentDatatype is not a valid value.
*/
ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
if (!defined(componentDatatype)) {
throw new DeveloperError('componentDatatype is required.');
}
if (!defined(buffer)) {
throw new DeveloperError('buffer is required.');
}
byteOffset = defaultValue(byteOffset, 0);
length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return new Int8Array(buffer, byteOffset, length);
case ComponentDatatype.UNSIGNED_BYTE:
return new Uint8Array(buffer, byteOffset, length);
case ComponentDatatype.SHORT:
return new Int16Array(buffer, byteOffset, length);
case ComponentDatatype.UNSIGNED_SHORT:
return new Uint16Array(buffer, byteOffset, length);
case ComponentDatatype.INT:
return new Int32Array(buffer, byteOffset, length);
case ComponentDatatype.UNSIGNED_INT:
return new Uint32Array(buffer, byteOffset, length);
case ComponentDatatype.FLOAT:
return new Float32Array(buffer, byteOffset, length);
case ComponentDatatype.DOUBLE:
return new Float64Array(buffer, byteOffset, length);
default:
throw new DeveloperError('componentDatatype is not a valid value.');
}
};
/**
* Get the ComponentDatatype from its name.
*
* @param {String} name The name of the ComponentDatatype.
* @returns {ComponentDatatype} The ComponentDatatype.
*
* @exception {DeveloperError} name is not a valid value.
*/
ComponentDatatype.fromName = function(name) {
switch (name) {
case 'BYTE':
return ComponentDatatype.BYTE;
case 'UNSIGNED_BYTE':
return ComponentDatatype.UNSIGNED_BYTE;
case 'SHORT':
return ComponentDatatype.SHORT;
case 'UNSIGNED_SHORT':
return ComponentDatatype.UNSIGNED_SHORT;
case 'INT':
return ComponentDatatype.INT;
case 'UNSIGNED_INT':
return ComponentDatatype.UNSIGNED_INT;
case 'FLOAT':
return ComponentDatatype.FLOAT;
case 'DOUBLE':
return ComponentDatatype.DOUBLE;
default:
throw new DeveloperError('name is not a valid value.');
}
};
return freezeObject(ComponentDatatype);
});
/*global define*/
define('Core/GeometryType',[
'./freezeObject'
], function(
freezeObject) {
'use strict';
/**
* @private
*/
var GeometryType = {
NONE : 0,
TRIANGLES : 1,
LINES : 2,
POLYLINES : 3
};
return freezeObject(GeometryType);
});
/*global define*/
define('Core/PrimitiveType',[
'./freezeObject',
'./WebGLConstants'
], function(
freezeObject,
WebGLConstants) {
'use strict';
/**
* The type of a geometric primitive, i.e., points, lines, and triangles.
*
* @exports PrimitiveType
*/
var PrimitiveType = {
/**
* Points primitive where each vertex (or index) is a separate point.
*
* @type {Number}
* @constant
*/
POINTS : WebGLConstants.POINTS,
/**
* Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
*
* @type {Number}
* @constant
*/
LINES : WebGLConstants.LINES,
/**
* Line loop primitive where each vertex (or index) after the first connects a line to
* the previous vertex, and the last vertex implicitly connects to the first.
*
* @type {Number}
* @constant
*/
LINE_LOOP : WebGLConstants.LINE_LOOP,
/**
* Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
*
* @type {Number}
* @constant
*/
LINE_STRIP : WebGLConstants.LINE_STRIP,
/**
* Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
*
* @type {Number}
* @constant
*/
TRIANGLES : WebGLConstants.TRIANGLES,
/**
* Triangle strip primitive where each vertex (or index) after the first two connect to
* the previous two vertices forming a triangle. For example, this can be used to model a wall.
*
* @type {Number}
* @constant
*/
TRIANGLE_STRIP : WebGLConstants.TRIANGLE_STRIP,
/**
* Triangle fan primitive where each vertex (or index) after the first two connect to
* the previous vertex and the first vertex forming a triangle. For example, this can be used
* to model a cone or circle.
*
* @type {Number}
* @constant
*/
TRIANGLE_FAN : WebGLConstants.TRIANGLE_FAN,
/**
* @private
*/
validate : function(primitiveType) {
return primitiveType === PrimitiveType.POINTS ||
primitiveType === PrimitiveType.LINES ||
primitiveType === PrimitiveType.LINE_LOOP ||
primitiveType === PrimitiveType.LINE_STRIP ||
primitiveType === PrimitiveType.TRIANGLES ||
primitiveType === PrimitiveType.TRIANGLE_STRIP ||
primitiveType === PrimitiveType.TRIANGLE_FAN;
}
};
return freezeObject(PrimitiveType);
});
/*global define*/
define('Core/Geometry',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./GeometryType',
'./PrimitiveType'
], function(
defaultValue,
defined,
DeveloperError,
GeometryType,
PrimitiveType) {
'use strict';
/**
* A geometry representation with attributes forming vertices and optional index data
* defining primitives. Geometries and an {@link Appearance}, which describes the shading,
* can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
* be created from many heterogeneous - in many cases - geometries for performance.
* <p>
* Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
* </p>
*
* @alias Geometry
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
* @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
* @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
* @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
*
* @see PolygonGeometry
* @see RectangleGeometry
* @see EllipseGeometry
* @see CircleGeometry
* @see WallGeometry
* @see SimplePolylineGeometry
* @see BoxGeometry
* @see EllipsoidGeometry
*
* @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
*
* @example
* // Create geometry with a position attribute and indexed lines.
* var positions = new Float64Array([
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ]);
*
* var geometry = new Cesium.Geometry({
* attributes : {
* position : new Cesium.GeometryAttribute({
* componentDatatype : Cesium.ComponentDatatype.DOUBLE,
* componentsPerAttribute : 3,
* values : positions
* })
* },
* indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
* primitiveType : Cesium.PrimitiveType.LINES,
* boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
* });
*/
function Geometry(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
if (!defined(options.attributes)) {
throw new DeveloperError('options.attributes is required.');
}
/**
* Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
* {@link GeometryAttribute} containing the attribute's data.
* <p>
* Attributes are always stored non-interleaved in a Geometry.
* </p>
* <p>
* There are reserved attribute names with well-known semantics. The following attributes
* are created by a Geometry (depending on the provided {@link VertexFormat}.
* <ul>
* <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
* <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
* <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
* <li><code>bitangent</code> - Bitangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#bitangent}.</li>
* <li><code>tangent</code> - Tangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#tangent}.</li>
* </ul>
* </p>
* <p>
* The following attribute names are generally not created by a Geometry, but are added
* to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
* the geometry for rendering.
* <ul>
* <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>position3DLow</code> - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>position2DLow</code> - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
* </ul>
* </p>
*
* @type GeometryAttributes
*
* @default undefined
*
*
* @example
* geometry.attributes.position = new Cesium.GeometryAttribute({
* componentDatatype : Cesium.ComponentDatatype.FLOAT,
* componentsPerAttribute : 3,
* values : new Float32Array(0)
* });
*
* @see GeometryAttribute
* @see VertexFormat
*/
this.attributes = options.attributes;
/**
* Optional index data that - along with {@link Geometry#primitiveType} -
* determines the primitives in the geometry.
*
* @type Array
*
* @default undefined
*/
this.indices = options.indices;
/**
* The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
* but can varying based on the specific geometry.
*
* @type PrimitiveType
*
* @default undefined
*/
this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);
/**
* An optional bounding sphere that fully encloses the geometry. This is
* commonly used for culling.
*
* @type BoundingSphere
*
* @default undefined
*/
this.boundingSphere = options.boundingSphere;
/**
* @private
*/
this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
/**
* @private
*/
this.boundingSphereCV = options.boundingSphereCV;
}
/**
* Computes the number of vertices in a geometry. The runtime is linear with
* respect to the number of attributes in a vertex, not the number of vertices.
*
* @param {Geometry} geometry The geometry.
* @returns {Number} The number of vertices in the geometry.
*
* @example
* var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
*/
Geometry.computeNumberOfVertices = function(geometry) {
if (!defined(geometry)) {
throw new DeveloperError('geometry is required.');
}
var numberOfVertices = -1;
for ( var property in geometry.attributes) {
if (geometry.attributes.hasOwnProperty(property) &&
defined(geometry.attributes[property]) &&
defined(geometry.attributes[property].values)) {
var attribute = geometry.attributes[property];
var num = attribute.values.length / attribute.componentsPerAttribute;
if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
throw new DeveloperError('All attribute lists must have the same number of attributes.');
}
numberOfVertices = num;
}
}
return numberOfVertices;
};
return Geometry;
});
/*global define*/
define('Core/GeometryAttribute',[
'./defaultValue',
'./defined',
'./DeveloperError'
], function(
defaultValue,
defined,
DeveloperError) {
'use strict';
/**
* Values and type information for geometry attributes. A {@link Geometry}
* generally contains one or more attributes. All attributes together form
* the geometry's vertices.
*
* @alias GeometryAttribute
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
* @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
* @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering.
* @param {TypedArray} [options.values] The values for the attributes stored in a typed array.
*
* @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
*
*
* @example
* var geometry = new Cesium.Geometry({
* attributes : {
* position : new Cesium.GeometryAttribute({
* componentDatatype : Cesium.ComponentDatatype.FLOAT,
* componentsPerAttribute : 3,
* values : new Float32Array([
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ])
* })
* },
* primitiveType : Cesium.PrimitiveType.LINE_LOOP
* });
*
* @see Geometry
*/
function GeometryAttribute(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
if (!defined(options.componentDatatype)) {
throw new DeveloperError('options.componentDatatype is required.');
}
if (!defined(options.componentsPerAttribute)) {
throw new DeveloperError('options.componentsPerAttribute is required.');
}
if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
throw new DeveloperError('options.componentsPerAttribute must be between 1 and 4.');
}
if (!defined(options.values)) {
throw new DeveloperError('options.values is required.');
}
/**
* The datatype of each component in the attribute, e.g., individual elements in
* {@link GeometryAttribute#values}.
*
* @type ComponentDatatype
*
* @default undefined
*/
this.componentDatatype = options.componentDatatype;
/**
* A number between 1 and 4 that defines the number of components in an attributes.
* For example, a position attribute with x, y, and z components would have 3 as
* shown in the code example.
*
* @type Number
*
* @default undefined
*
* @example
* attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
* attribute.componentsPerAttribute = 3;
* attribute.values = new Float32Array([
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ]);
*/
this.componentsPerAttribute = options.componentsPerAttribute;
/**
* When <code>true</code> and <code>componentDatatype</code> is an integer format,
* indicate that the components should be mapped to the range [0, 1] (unsigned)
* or [-1, 1] (signed) when they are accessed as floating-point for rendering.
* <p>
* This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
* </p>
*
* @type Boolean
*
* @default false
*
* @example
* attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
* attribute.componentsPerAttribute = 4;
* attribute.normalize = true;
* attribute.values = new Uint8Array([
* Cesium.Color.floatToByte(color.red),
* Cesium.Color.floatToByte(color.green),
* Cesium.Color.floatToByte(color.blue),
* Cesium.Color.floatToByte(color.alpha)
* ]);
*/
this.normalize = defaultValue(options.normalize, false);
/**
* The values for the attributes stored in a typed array. In the code example,
* every three elements in <code>values</code> defines one attributes since
* <code>componentsPerAttribute</code> is 3.
*
* @type TypedArray
*
* @default undefined
*
* @example
* attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
* attribute.componentsPerAttribute = 3;
* attribute.values = new Float32Array([
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ]);
*/
this.values = options.values;
}
return GeometryAttribute;
});
/*global define*/
define('Core/GeometryAttributes',[
'./defaultValue'
], function(
defaultValue) {
'use strict';
/**
* Attributes, which make up a geometry's vertices. Each property in this object corresponds to a
* {@link GeometryAttribute} containing the attribute's data.
* <p>
* Attributes are always stored non-interleaved in a Geometry.
* </p>
*
* @alias GeometryAttributes
* @constructor
*/
function GeometryAttributes(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
/**
* The 3D position attribute.
* <p>
* 64-bit floating-point (for precision). 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.position = options.position;
/**
* The normal attribute (normalized), which is commonly used for lighting.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.normal = options.normal;
/**
* The 2D texture coordinate attribute.
* <p>
* 32-bit floating-point. 2 components per attribute
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.st = options.st;
/**
* The bitangent attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.bitangent = options.bitangent;
/**
* The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.tangent = options.tangent;
/**
* The color attribute.
* <p>
* 8-bit unsigned integer. 4 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.color = options.color;
}
return GeometryAttributes;
});
/*global define*/
define('Core/IndexDatatype',[
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math',
'./WebGLConstants'
], function(
defined,
DeveloperError,
freezeObject,
CesiumMath,
WebGLConstants) {
'use strict';
/**
* Constants for WebGL index datatypes. These corresponds to the
* <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
*
* @exports IndexDatatype
*/
var IndexDatatype = {
/**
* 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
* of an element in <code>Uint8Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
/**
* 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
* of an element in <code>Uint16Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
/**
* 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
* of an element in <code>Uint32Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_INT : WebGLConstants.UNSIGNED_INT
};
/**
* Returns the size, in bytes, of the corresponding datatype.
*
* @param {IndexDatatype} indexDatatype The index datatype to get the size of.
* @returns {Number} The size in bytes.
*
* @example
* // Returns 2
* var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
*/
IndexDatatype.getSizeInBytes = function(indexDatatype) {
switch(indexDatatype) {
case IndexDatatype.UNSIGNED_BYTE:
return Uint8Array.BYTES_PER_ELEMENT;
case IndexDatatype.UNSIGNED_SHORT:
return Uint16Array.BYTES_PER_ELEMENT;
case IndexDatatype.UNSIGNED_INT:
return Uint32Array.BYTES_PER_ELEMENT;
}
throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
};
/**
* Validates that the provided index datatype is a valid {@link IndexDatatype}.
*
* @param {IndexDatatype} indexDatatype The index datatype to validate.
* @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
*
* @example
* if (!Cesium.IndexDatatype.validate(indexDatatype)) {
* throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
* }
*/
IndexDatatype.validate = function(indexDatatype) {
return defined(indexDatatype) &&
(indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
indexDatatype === IndexDatatype.UNSIGNED_INT);
};
/**
* Creates a typed array that will store indices, using either <code><Uint16Array</code>
* or <code>Uint32Array</code> depending on the number of vertices.
*
* @param {Number} numberOfVertices Number of vertices that the indices will reference.
* @param {*} indicesLengthOrArray Passed through to the typed array constructor.
* @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
*
* @example
* this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
*/
IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
if (!defined(numberOfVertices)) {
throw new DeveloperError('numberOfVertices is required.');
}
if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
return new Uint32Array(indicesLengthOrArray);
}
return new Uint16Array(indicesLengthOrArray);
};
/**
* Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
* or <code>Uint32Array</code> depending on the number of vertices.
*
* @param {Number} numberOfVertices Number of vertices that the indices will reference.
* @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
* @param {Number} byteOffset Passed through to the typed array constructor.
* @param {Number} length Passed through to the typed array constructor.
* @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
*
*/
IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
if (!defined(numberOfVertices)) {
throw new DeveloperError('numberOfVertices is required.');
}
if (!defined(sourceArray)) {
throw new DeveloperError('sourceArray is required.');
}
if (!defined(byteOffset)) {
throw new DeveloperError('byteOffset is required.');
}
if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
return new Uint32Array(sourceArray, byteOffset, length);
}
return new Uint16Array(sourceArray, byteOffset, length);
};
return freezeObject(IndexDatatype);
});
/*global define*/
define('Core/VertexFormat',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject'
], function(
defaultValue,
defined,
DeveloperError,
freezeObject) {
'use strict';
/**
* A vertex format defines what attributes make up a vertex. A VertexFormat can be provided
* to a {@link Geometry} to request that certain properties be computed, e.g., just position,
* position and normal, etc.
*
* @param {Object} [options] An object with boolean properties corresponding to VertexFormat properties as shown in the code example.
*
* @alias VertexFormat
* @constructor
*
* @example
* // Create a vertex format with position and 2D texture coordinate attributes.
* var format = new Cesium.VertexFormat({
* position : true,
* st : true
* });
*
* @see Geometry#attributes
* @see Packable
*/
function VertexFormat(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
/**
* When <code>true</code>, the vertex has a 3D position attribute.
* <p>
* 64-bit floating-point (for precision). 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.position = defaultValue(options.position, false);
/**
* When <code>true</code>, the vertex has a normal attribute (normalized), which is commonly used for lighting.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.normal = defaultValue(options.normal, false);
/**
* When <code>true</code>, the vertex has a 2D texture coordinate attribute.
* <p>
* 32-bit floating-point. 2 components per attribute
* </p>
*
* @type Boolean
*
* @default false
*/
this.st = defaultValue(options.st, false);
/**
* When <code>true</code>, the vertex has a bitangent attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.bitangent = defaultValue(options.bitangent, false);
/**
* When <code>true</code>, the vertex has a tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.tangent = defaultValue(options.tangent, false);
/**
* When <code>true</code>, the vertex has an RGB color attribute.
* <p>
* 8-bit unsigned byte. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.color = defaultValue(options.color, false);
}
/**
* An immutable vertex format with only a position attribute.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
*/
VertexFormat.POSITION_ONLY = freezeObject(new VertexFormat({
position : true
}));
/**
* An immutable vertex format with position and normal attributes.
* This is compatible with per-instance color appearances like {@link PerInstanceColorAppearance}.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
*/
VertexFormat.POSITION_AND_NORMAL = freezeObject(new VertexFormat({
position : true,
normal : true
}));
/**
* An immutable vertex format with position, normal, and st attributes.
* This is compatible with {@link MaterialAppearance} when {@link MaterialAppearance#materialSupport}
* is <code>TEXTURED/code>.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
* @see VertexFormat#st
*/
VertexFormat.POSITION_NORMAL_AND_ST = freezeObject(new VertexFormat({
position : true,
normal : true,
st : true
}));
/**
* An immutable vertex format with position and st attributes.
* This is compatible with {@link EllipsoidSurfaceAppearance}.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#st
*/
VertexFormat.POSITION_AND_ST = freezeObject(new VertexFormat({
position : true,
st : true
}));
/**
* An immutable vertex format with position and color attributes.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#color
*/
VertexFormat.POSITION_AND_COLOR = freezeObject(new VertexFormat({
position : true,
color : true
}));
/**
* An immutable vertex format with well-known attributes: position, normal, st, tangent, and bitangent.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
* @see VertexFormat#st
* @see VertexFormat#tangent
* @see VertexFormat#bitangent
*/
VertexFormat.ALL = freezeObject(new VertexFormat({
position : true,
normal : true,
st : true,
tangent : true,
bitangent : true
}));
/**
* An immutable vertex format with position, normal, and st attributes.
* This is compatible with most appearances and materials; however
* normal and st attributes are not always required. When this is
* known in advance, another <code>VertexFormat</code> should be used.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
*/
VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
VertexFormat.packedLength = 6;
/**
* Stores the provided instance into the provided array.
*
* @param {VertexFormat} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
VertexFormat.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.position ? 1.0 : 0.0;
array[startingIndex++] = value.normal ? 1.0 : 0.0;
array[startingIndex++] = value.st ? 1.0 : 0.0;
array[startingIndex++] = value.tangent ? 1.0 : 0.0;
array[startingIndex++] = value.bitangent ? 1.0 : 0.0;
array[startingIndex++] = value.color ? 1.0 : 0.0;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {VertexFormat} [result] The object into which to store the result.
* @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided.
*/
VertexFormat.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new VertexFormat();
}
result.position = array[startingIndex++] === 1.0;
result.normal = array[startingIndex++] === 1.0;
result.st = array[startingIndex++] === 1.0;
result.tangent = array[startingIndex++] === 1.0;
result.bitangent = array[startingIndex++] === 1.0;
result.color = array[startingIndex++] === 1.0;
return result;
};
/**
* Duplicates a VertexFormat instance.
*
* @param {VertexFormat} vertexFormat The vertex format to duplicate.
* @param {VertexFormat} [result] The object onto which to store the result.
* @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. (Returns undefined if vertexFormat is undefined)
*/
VertexFormat.clone = function(vertexFormat, result) {
if (!defined(vertexFormat)) {
return undefined;
}
if (!defined(result)) {
result = new VertexFormat();
}
result.position = vertexFormat.position;
result.normal = vertexFormat.normal;
result.st = vertexFormat.st;
result.tangent = vertexFormat.tangent;
result.bitangent = vertexFormat.bitangent;
result.color = vertexFormat.color;
return result;
};
return VertexFormat;
});
/*global define*/
define('Core/EllipsoidGeometry',[
'./BoundingSphere',
'./Cartesian2',
'./Cartesian3',
'./ComponentDatatype',
'./defaultValue',
'./defined',
'./DeveloperError',
'./Ellipsoid',
'./Geometry',
'./GeometryAttribute',
'./GeometryAttributes',
'./IndexDatatype',
'./Math',
'./PrimitiveType',
'./VertexFormat'
], function(
BoundingSphere,
Cartesian2,
Cartesian3,
ComponentDatatype,
defaultValue,
defined,
DeveloperError,
Ellipsoid,
Geometry,
GeometryAttribute,
GeometryAttributes,
IndexDatatype,
CesiumMath,
PrimitiveType,
VertexFormat) {
'use strict';
var scratchPosition = new Cartesian3();
var scratchNormal = new Cartesian3();
var scratchTangent = new Cartesian3();
var scratchBitangent = new Cartesian3();
var scratchNormalST = new Cartesian3();
var defaultRadii = new Cartesian3(1.0, 1.0, 1.0);
var cos = Math.cos;
var sin = Math.sin;
/**
* A description of an ellipsoid centered at the origin.
*
* @alias EllipsoidGeometry
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Cartesian3} [options.radii=Cartesian3(1.0, 1.0, 1.0)] The radii of the ellipsoid in the x, y, and z directions.
* @param {Number} [options.stackPartitions=64] The number of times to partition the ellipsoid into stacks.
* @param {Number} [options.slicePartitions=64] The number of times to partition the ellipsoid into radial slices.
* @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
*
* @exception {DeveloperError} options.slicePartitions cannot be less than three.
* @exception {DeveloperError} options.stackPartitions cannot be less than three.
*
* @see EllipsoidGeometry#createGeometry
*
* @example
* var ellipsoid = new Cesium.EllipsoidGeometry({
* vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
* radii : new Cesium.Cartesian3(1000000.0, 500000.0, 500000.0)
* });
* var geometry = Cesium.EllipsoidGeometry.createGeometry(ellipsoid);
*/
function EllipsoidGeometry(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
var radii = defaultValue(options.radii, defaultRadii);
var stackPartitions = defaultValue(options.stackPartitions, 64);
var slicePartitions = defaultValue(options.slicePartitions, 64);
var vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
if (slicePartitions < 3) {
throw new DeveloperError ('options.slicePartitions cannot be less than three.');
}
if (stackPartitions < 3) {
throw new DeveloperError('options.stackPartitions cannot be less than three.');
}
this._radii = Cartesian3.clone(radii);
this._stackPartitions = stackPartitions;
this._slicePartitions = slicePartitions;
this._vertexFormat = VertexFormat.clone(vertexFormat);
this._workerName = 'createEllipsoidGeometry';
}
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
EllipsoidGeometry.packedLength = Cartesian3.packedLength + VertexFormat.packedLength + 2;
/**
* Stores the provided instance into the provided array.
*
* @param {EllipsoidGeometry} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
EllipsoidGeometry.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
Cartesian3.pack(value._radii, array, startingIndex);
startingIndex += Cartesian3.packedLength;
VertexFormat.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat.packedLength;
array[startingIndex++] = value._stackPartitions;
array[startingIndex] = value._slicePartitions;
return array;
};
var scratchRadii = new Cartesian3();
var scratchVertexFormat = new VertexFormat();
var scratchOptions = {
radii : scratchRadii,
vertexFormat : scratchVertexFormat,
stackPartitions : undefined,
slicePartitions : undefined
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {EllipsoidGeometry} [result] The object into which to store the result.
* @returns {EllipsoidGeometry} The modified result parameter or a new EllipsoidGeometry instance if one was not provided.
*/
EllipsoidGeometry.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
var radii = Cartesian3.unpack(array, startingIndex, scratchRadii);
startingIndex += Cartesian3.packedLength;
var vertexFormat = VertexFormat.unpack(array, startingIndex, scratchVertexFormat);
startingIndex += VertexFormat.packedLength;
var stackPartitions = array[startingIndex++];
var slicePartitions = array[startingIndex];
if (!defined(result)) {
scratchOptions.stackPartitions = stackPartitions;
scratchOptions.slicePartitions = slicePartitions;
return new EllipsoidGeometry(scratchOptions);
}
result._radii = Cartesian3.clone(radii, result._radii);
result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
result._stackPartitions = stackPartitions;
result._slicePartitions = slicePartitions;
return result;
};
/**
* Computes the geometric representation of an ellipsoid, including its vertices, indices, and a bounding sphere.
*
* @param {EllipsoidGeometry} ellipsoidGeometry A description of the ellipsoid.
* @returns {Geometry|undefined} The computed vertices and indices.
*/
EllipsoidGeometry.createGeometry = function(ellipsoidGeometry) {
var radii = ellipsoidGeometry._radii;
if ((radii.x <= 0) || (radii.y <= 0) || (radii.z <= 0)) {
return;
}
var ellipsoid = Ellipsoid.fromCartesian3(radii);
var vertexFormat = ellipsoidGeometry._vertexFormat;
// The extra slice and stack are for duplicating points at the x axis and poles.
// We need the texture coordinates to interpolate from (2 * pi - delta) to 2 * pi instead of
// (2 * pi - delta) to 0.
var slicePartitions = ellipsoidGeometry._slicePartitions + 1;
var stackPartitions = ellipsoidGeometry._stackPartitions + 1;
var vertexCount = stackPartitions * slicePartitions;
var positions = new Float64Array(vertexCount * 3);
var numIndices = 6 * (slicePartitions - 1) * (stackPartitions - 2);
var indices = IndexDatatype.createTypedArray(vertexCount, numIndices);
var normals = (vertexFormat.normal) ? new Float32Array(vertexCount * 3) : undefined;
var tangents = (vertexFormat.tangent) ? new Float32Array(vertexCount * 3) : undefined;
var bitangents = (vertexFormat.bitangent) ? new Float32Array(vertexCount * 3) : undefined;
var st = (vertexFormat.st) ? new Float32Array(vertexCount * 2) : undefined;
var cosTheta = new Array(slicePartitions);
var sinTheta = new Array(slicePartitions);
var i;
var j;
var index = 0;
for (i = 0; i < slicePartitions; i++) {
var theta = CesiumMath.TWO_PI * i / (slicePartitions - 1);
cosTheta[i] = cos(theta);
sinTheta[i] = sin(theta);
// duplicate first point for correct
// texture coordinates at the north pole.
positions[index++] = 0.0;
positions[index++] = 0.0;
positions[index++] = radii.z;
}
for (i = 1; i < stackPartitions - 1; i++) {
var phi = Math.PI * i / (stackPartitions - 1);
var sinPhi = sin(phi);
var xSinPhi = radii.x * sinPhi;
var ySinPhi = radii.y * sinPhi;
var zCosPhi = radii.z * cos(phi);
for (j = 0; j < slicePartitions; j++) {
positions[index++] = cosTheta[j] * xSinPhi;
positions[index++] = sinTheta[j] * ySinPhi;
positions[index++] = zCosPhi;
}
}
for (i = 0; i < slicePartitions; i++) {
// duplicate first point for correct
// texture coordinates at the south pole.
positions[index++] = 0.0;
positions[index++] = 0.0;
positions[index++] = -radii.z;
}
var attributes = new GeometryAttributes();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute({
componentDatatype : ComponentDatatype.DOUBLE,
componentsPerAttribute : 3,
values : positions
});
}
var stIndex = 0;
var normalIndex = 0;
var tangentIndex = 0;
var bitangentIndex = 0;
if (vertexFormat.st || vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
for( i = 0; i < vertexCount; i++) {
var position = Cartesian3.fromArray(positions, i * 3, scratchPosition);
var normal = ellipsoid.geodeticSurfaceNormal(position, scratchNormal);
if (vertexFormat.st) {
var normalST = Cartesian2.negate(normal, scratchNormalST);
// if the point is at or close to the pole, find a point along the same longitude
// close to the xy-plane for the s coordinate.
if (Cartesian2.magnitude(normalST) < CesiumMath.EPSILON6) {
index = (i + slicePartitions * Math.floor(stackPartitions * 0.5)) * 3;
if (index > positions.length) {
index = (i - slicePartitions * Math.floor(stackPartitions * 0.5)) * 3;
}
Cartesian3.fromArray(positions, index, normalST);
ellipsoid.geodeticSurfaceNormal(normalST, normalST);
Cartesian2.negate(normalST, normalST);
}
st[stIndex++] = (Math.atan2(normalST.y, normalST.x) / CesiumMath.TWO_PI) + 0.5;
st[stIndex++] = (Math.asin(normal.z) / Math.PI) + 0.5;
}
if (vertexFormat.normal) {
normals[normalIndex++] = normal.x;
normals[normalIndex++] = normal.y;
normals[normalIndex++] = normal.z;
}
if (vertexFormat.tangent || vertexFormat.bitangent) {
var tangent = scratchTangent;
if (i < slicePartitions || i > vertexCount - slicePartitions - 1) {
Cartesian3.cross(Cartesian3.UNIT_X, normal, tangent);
Cartesian3.normalize(tangent, tangent);
} else {
Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent);
Cartesian3.normalize(tangent, tangent);
}
if (vertexFormat.tangent) {
tangents[tangentIndex++] = tangent.x;
tangents[tangentIndex++] = tangent.y;
tangents[tangentIndex++] = tangent.z;
}
if (vertexFormat.bitangent) {
var bitangent = Cartesian3.cross(normal, tangent, scratchBitangent);
Cartesian3.normalize(bitangent, bitangent);
bitangents[bitangentIndex++] = bitangent.x;
bitangents[bitangentIndex++] = bitangent.y;
bitangents[bitangentIndex++] = bitangent.z;
}
}
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 2,
values : st
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 3,
values : normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 3,
values : tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 3,
values : bitangents
});
}
}
index = 0;
for (j = 0; j < slicePartitions - 1; j++) {
indices[index++] = slicePartitions + j;
indices[index++] = slicePartitions + j + 1;
indices[index++] = j + 1;
}
var topOffset;
var bottomOffset;
for (i = 1; i < stackPartitions - 2; i++) {
topOffset = i * slicePartitions;
bottomOffset = (i + 1) * slicePartitions;
for (j = 0; j < slicePartitions - 1; j++) {
indices[index++] = bottomOffset + j;
indices[index++] = bottomOffset + j + 1;
indices[index++] = topOffset + j + 1;
indices[index++] = bottomOffset + j;
indices[index++] = topOffset + j + 1;
indices[index++] = topOffset + j;
}
}
i = stackPartitions - 2;
topOffset = i * slicePartitions;
bottomOffset = (i + 1) * slicePartitions;
for (j = 0; j < slicePartitions - 1; j++) {
indices[index++] = bottomOffset + j;
indices[index++] = topOffset + j + 1;
indices[index++] = topOffset + j;
}
return new Geometry({
attributes : attributes,
indices : indices,
primitiveType : PrimitiveType.TRIANGLES,
boundingSphere : BoundingSphere.fromEllipsoid(ellipsoid)
});
};
return EllipsoidGeometry;
});
/*global define*/
define('Workers/createEllipsoidGeometry',[
'../Core/defined',
'../Core/EllipsoidGeometry'
], function(
defined,
EllipsoidGeometry) {
'use strict';
return function(ellipsoidGeometry, offset) {
if (defined(offset)) {
ellipsoidGeometry = EllipsoidGeometry.unpack(ellipsoidGeometry, offset);
}
return EllipsoidGeometry.createGeometry(ellipsoidGeometry);
};
});
}()); |
import { ParameterContainer } from "../core/parameter-container";
class Configuration {
constructor() {
this.parameterContainer = new ParameterContainer();
}
}
|
"use strict";
const sinon = require("sinon");
const _ = require("underscore");
const EventEmitter = require("events").EventEmitter;
const util = require("util");
const should = require("should");
const WatchDog = require("..").WatchDog;
function MyObject() {}
util.inherits(MyObject, EventEmitter);
MyObject.prototype.watchdogReset = function() {
this.emit("watchdogReset");
};
//xx var describe = require("node-opcua-leak-detector").describeWithLeakDetector;
// http://sinonjs.org/docs/#clock
describe("watch dog", function() {
this.timeout(10000);
let watchDog = null;
beforeEach(function() {
this.clock = sinon.useFakeTimers();
watchDog = new WatchDog();
});
afterEach(function() {
watchDog.shutdown();
this.clock.restore();
});
it("should maintain a subscriber count", function() {
watchDog.subscriberCount.should.eql(0);
const obj1 = new MyObject();
watchDog.addSubscriber(obj1, 1000);
watchDog.subscriberCount.should.eql(1);
watchDog.removeSubscriber(obj1);
watchDog.subscriberCount.should.eql(0);
});
it("should not have a timer running if no subscriber", function() {
watchDog.subscriberCount.should.eql(0);
should(watchDog._timer).equal(null);
});
it("should have the internal timer running after the first subscriber has registered", function() {
should(watchDog._timer).equal(null);
const obj1 = new MyObject();
watchDog.addSubscriber(obj1, 1000);
should.exist(watchDog._timer);
watchDog.removeSubscriber(obj1);
});
it("should stop the internal timer running after the last subscriber has unregistered", function() {
should(watchDog._timer).equal(null);
const obj1 = new MyObject();
watchDog.addSubscriber(obj1, 1000);
watchDog.removeSubscriber(obj1);
watchDog.addSubscriber(obj1, 1000);
watchDog.removeSubscriber(obj1);
should.not.exist(watchDog._timer)
});
it("should fail if the object subscribing to the WatchDog doesn't provide a 'watchdogReset' method", function(done) {
should(function() {
watchDog.addSubscriber({}, 100);
}).throwError();
done();
});
it("should install a 'keepAlive' method on the subscribing object during addSubscriber and remove it during removeSubscriber", function(done) {
const obj = new MyObject();
should(_.isFunction(obj.keepAlive)).eql(false);
watchDog.addSubscriber(obj, 100);
should(_.isFunction(obj.keepAlive)).eql(true);
watchDog.removeSubscriber(obj);
should(_.isFunction(obj.keepAlive)).eql(false);
done();
});
it("should call the watchdogReset method of a subscriber when timeout has expired", function(done) {
const obj = new MyObject();
watchDog.addSubscriber(obj, 100);
setTimeout(function() {
obj.keepAlive();
}, 200);
obj.on("watchdogReset", done);
this.clock.tick(2000);
});
it("should visit subscribers on a regular basis", function(done) {
const obj1 = new MyObject();
const obj2 = new MyObject();
watchDog.addSubscriber(obj1, 1000);
watchDog.addSubscriber(obj2, 1000);
const timer1 = setInterval(function() {
obj1.keepAlive();
}, 200);
const timer2 = setInterval(function() {
obj2.keepAlive();
}, 200);
// Since our objects are sending a keepAlive signal on a very regular basic,
// we should make sure object do not received a watchdogReset call by the WatchDog
obj1.on("watchdogReset", function() {
done(new Error("Received unexpected watchdogReset on object1"));
});
obj2.on("watchdogReset", function() {
done(new Error("Received unexpected watchdogReset on object2"));
});
setTimeout(function() {
obj1._watchDogData.visitCount.should.greaterThan(8);
obj2._watchDogData.visitCount.should.greaterThan(8);
watchDog.removeSubscriber(obj1);
watchDog.removeSubscriber(obj2);
clearInterval(timer1);
clearInterval(timer2);
}, 10000);
setTimeout(done, 15000);
this.clock.tick(20000);
});
it("should emit an event when it finds that some subscriber has reached the timeout period without sending a keepAlive signal", function(done) {
const obj1 = new MyObject();
watchDog.addSubscriber(obj1, 1000);
watchDog.on("timeout", function(subscribers) {
subscribers.length.should.eql(1);
done();
});
this.clock.tick(20000);
});
});
|
// --------------------
// Root namespace controller
// logout action
// --------------------
// libraries
var authentication = require('../../../../lib/authentication');
// exports
// action definition
exports = module.exports = {
// action params
title: 'Logout',
view: false,
actLocal: true,
// functions
get: function() {
// logout user
return authentication.logout(this.user, this.res, this.overlook).bind(this)
.then(function() {
// redirect to homepage
this.log('Logout');
return this.redirect('/', 'You are logged out');
});
}
};
|
import React from 'react';
import Head from 'next/head';
import { ThemeProvider, createGlobalStyle } from 'styled-components';
import Header from '@components/layout/header';
import { READER_PATH, APP_VERSION, CDN } from 'lib/config';
import { useGlobalState } from 'lib/state';
import { theme as rfTheme } from '@readerfront/ui';
const { primaryColor, bodyColor, bodyBackgroundColor, scrollBackground } =
rfTheme;
const GlobalStyle = createGlobalStyle`
body {
background-color: ${bodyBackgroundColor} !important;
color: ${bodyColor} !important;
}
a {
color: ${primaryColor} !important;
}
::-webkit-scrollbar {
width: 7px;
height: 5px;
}
::-webkit-scrollbar-thumb {
background: ${scrollBackground};
border-radius: 5px;
cursor: pointer;
&:hover {
background: ${primaryColor};
}
}
.container {
margin-top: 30px;
}
.show-loading-animation {
animation: react-placeholder-pulse 1.5s infinite;
}
@keyframes react-placeholder-pulse {
0% {
opacity: 0.6;
}
50% {
opacity: 1;
}
100% {
opacity: 0.6;
}
}
`;
function App({ children, theme }) {
const [themeSelected] = useGlobalState('theme');
const [language] = useGlobalState('language');
return (
<>
<Head>
<meta name="generator" content={`ReaderFront v${APP_VERSION}`} />
<link
rel="alternate"
type="application/rss+xml"
title="RSS Chapter Feed"
href={`${READER_PATH}/feed/rss/${language}`}
/>
<link
rel="alternate"
type="application/atom+xml"
title="Atom Chapter Feed"
href={`${READER_PATH}/feed/atom/${language}`}
/>
{CDN === 'photon' && <link rel="preconnect" href="//i0.wp.com" />}
{CDN === 'photon' && <link rel="preconnect" href="//i1.wp.com" />}
{CDN === 'photon' && <link rel="preconnect" href="//i2.wp.com" />}
</Head>
<ThemeProvider theme={{ mode: themeSelected || theme }}>
<GlobalStyle />
<div className="App">
<Header theme={themeSelected || theme} />
{children}
</div>
</ThemeProvider>
</>
);
}
export default App;
|
import React from 'react';
import {EventEmitter} from 'fbemitter';
let AdStore = {
showModal(component){
},
hideModal(target){
target.setState('')
}
}
export default AdStore;
|
'use strict';
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request === 'getSnippet') {
sendResponse(getSnippet());
}
}
);
function getSnippet () {
return {
title: document.title,
url: document.location.href,
description: getMetaDescription()
};
};
function getMetaDescription () {
var metas = document.getElementsByTagName('meta');
for (var i in metas) {
if (typeof (metas[i].name) !== 'undefined' &&
metas[i].name.toLowerCase() === 'description') {
return metas[i].content;
}
}
return '';
}
|
'use strict';
export default class DataObject {
constructor() {
}
}
|
'use strict';
/**
* @ngdoc filter
* @name SubSnoopApp.filter:truncate
* @function
* @description
* # truncate
* Filter in the SubSnoopApp.
*/
angular.module('SubSnoopApp')
.filter('truncate', function () {
/*
Truncate text posts to a certain number of words
*/
return function (input, num, letters) {
if (!letters) {
var split = input.split(' ');
var truncated_input = split.slice(0, num);
if (split.length > num) {
truncated_input.push('...');
}
return truncated_input.join(' ').toString();
} else {
truncated_input = input.slice(0, num);
if (input.length > num) {
truncated_input += '...';
}
return truncated_input;
}
};
});
|
/* */
"format global";
"use strict";
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
module.exports = ReplaceSupers;
var messages = _interopRequireWildcard(require("../../messages"));
var t = _interopRequireWildcard(require("../../types"));
function isIllegalBareSuper(node, parent) {
if (!isSuper(node, parent)) return false;
if (t.isMemberExpression(parent, { computed: false })) return false;
if (t.isCallExpression(parent, { callee: node })) return false;
return true;
}
function isSuper(node, parent) {
return t.isIdentifier(node, { name: "super" }) && t.isReferenced(node, parent);
}
var visitor = {
enter: function enter(node, parent, scope, state) {
var topLevel = state.topLevel;
var self = state.self;
if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
// we need to call traverseLevel again so we're context aware
self.traverseLevel(node, false);
return this.skip();
}
if (t.isProperty(node, { method: true }) || t.isMethodDefinition(node)) {
// break on object methods
return this.skip();
}
var getThisReference = topLevel ?
// top level so `this` is the instance
t.thisExpression :
// not in the top level so we need to create a reference
self.getThisReference.bind(self);
var callback = self.specHandle;
if (self.isLoose) callback = self.looseHandle;
return callback.call(self, getThisReference, node, parent);
}
};
var ReplaceSupers = (function () {
/**
* Description
*/
function ReplaceSupers(opts) {
var inClass = arguments[1] === undefined ? false : arguments[1];
_classCallCheck(this, ReplaceSupers);
this.topLevelThisReference = opts.topLevelThisReference;
this.methodNode = opts.methodNode;
this.superRef = opts.superRef;
this.isStatic = opts.isStatic;
this.hasSuper = false;
this.inClass = inClass;
this.isLoose = opts.isLoose;
this.scope = opts.scope;
this.file = opts.file;
this.opts = opts;
}
ReplaceSupers.prototype.getObjectRef = function getObjectRef() {
return this.opts.objectRef || this.opts.getObjectRef();
};
/**
* Sets a super class value of the named property.
*
* @example
*
* _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
*
*/
ReplaceSupers.prototype.setSuperProperty = function setSuperProperty(property, value, isComputed, thisExpression) {
return t.callExpression(this.file.addHelper("set"), [t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.isStatic ? this.getObjectRef() : t.memberExpression(this.getObjectRef(), t.identifier("prototype"))]), isComputed ? property : t.literal(property.name), value, thisExpression]);
};
/**
* Gets a node representing the super class value of the named property.
*
* @example
*
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
*/
ReplaceSupers.prototype.getSuperProperty = function getSuperProperty(property, isComputed, thisExpression) {
return t.callExpression(this.file.addHelper("get"), [t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.isStatic ? this.getObjectRef() : t.memberExpression(this.getObjectRef(), t.identifier("prototype"))]), isComputed ? property : t.literal(property.name), thisExpression]);
};
/**
* Description
*/
ReplaceSupers.prototype.replace = function replace() {
this.traverseLevel(this.methodNode.value, true);
};
/**
* Description
*/
ReplaceSupers.prototype.traverseLevel = function traverseLevel(node, topLevel) {
var state = { self: this, topLevel: topLevel };
this.scope.traverse(node, visitor, state);
};
/**
* Description
*/
ReplaceSupers.prototype.getThisReference = function getThisReference() {
if (this.topLevelThisReference) {
return this.topLevelThisReference;
} else {
var ref = this.topLevelThisReference = this.scope.generateUidIdentifier("this");
this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [t.variableDeclarator(this.topLevelThisReference, t.thisExpression())]));
return ref;
}
};
/**
* Description
*/
ReplaceSupers.prototype.getLooseSuperProperty = function getLooseSuperProperty(id, parent) {
var methodNode = this.methodNode;
var methodName = methodNode.key;
var superRef = this.superRef || t.identifier("Function");
if (parent.property === id) {
return;
} else if (t.isCallExpression(parent, { callee: id })) {
// super(); -> objectRef.prototype.MethodName.call(this);
parent.arguments.unshift(t.thisExpression());
if (methodName.name === "constructor") {
// constructor() { super(); }
return t.memberExpression(superRef, t.identifier("call"));
} else {
id = superRef;
// foo() { super(); }
if (!methodNode["static"]) {
id = t.memberExpression(id, t.identifier("prototype"));
}
id = t.memberExpression(id, methodName, methodNode.computed);
return t.memberExpression(id, t.identifier("call"));
}
} else if (t.isMemberExpression(parent) && !methodNode["static"]) {
// super.test -> objectRef.prototype.test
return t.memberExpression(superRef, t.identifier("prototype"));
} else {
return superRef;
}
};
/**
* Description
*/
ReplaceSupers.prototype.looseHandle = function looseHandle(getThisReference, node, parent) {
if (t.isIdentifier(node, { name: "super" })) {
this.hasSuper = true;
return this.getLooseSuperProperty(node, parent);
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> objectRef.prototype.MethodName.call(this);
this.hasSuper = true;
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(getThisReference());
}
};
/**
* Description
*/
ReplaceSupers.prototype.specHandle = function specHandle(getThisReference, node, parent) {
var methodNode = this.methodNode;
var property;
var computed;
var args;
var thisReference;
if (isIllegalBareSuper(node, parent)) {
throw this.file.errorWithNode(node, messages.get("classesIllegalBareSuper"));
}
if (t.isCallExpression(node)) {
var callee = node.callee;
if (isSuper(callee, node)) {
// super(); -> _get(Object.getPrototypeOf(objectRef), "MethodName", this).call(this);
property = methodNode.key;
computed = methodNode.computed;
args = node.arguments;
// bare `super` call is illegal inside non-constructors
// - https://esdiscuss.org/topic/super-call-in-methods
// - https://twitter.com/wycats/status/544553184396836864
if (methodNode.key.name !== "constructor" || !this.inClass) {
var methodName = methodNode.key.name || "METHOD_NAME";
throw this.file.errorWithNode(node, messages.get("classesIllegalSuperCall", methodName));
}
} else if (t.isMemberExpression(callee) && isSuper(callee.object, callee)) {
// super.test(); -> _get(Object.getPrototypeOf(objectRef.prototype), "test", this).call(this);
property = callee.property;
computed = callee.computed;
args = node.arguments;
}
} else if (t.isMemberExpression(node) && isSuper(node.object, node)) {
// super.name; -> _get(Object.getPrototypeOf(objectRef.prototype), "name", this);
property = node.property;
computed = node.computed;
} else if (t.isAssignmentExpression(node) && isSuper(node.left.object, node.left) && methodNode.kind === "set") {
// super.name = "val"; -> _set(Object.getPrototypeOf(objectRef.prototype), "name", this);
this.hasSuper = true;
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
}
if (!property) return;
this.hasSuper = true;
thisReference = getThisReference();
var superProperty = this.getSuperProperty(property, computed, thisReference);
if (args) {
if (args.length === 1 && t.isSpreadElement(args[0])) {
// super(...arguments);
return t.callExpression(t.memberExpression(superProperty, t.identifier("apply")), [thisReference, args[0].argument]);
} else {
return t.callExpression(t.memberExpression(superProperty, t.identifier("call")), [thisReference].concat(_toConsumableArray(args)));
}
} else {
return superProperty;
}
};
return ReplaceSupers;
})();
module.exports = ReplaceSupers; |
'use strict';
const log = require('../../log');
const Packet = require('../../../lib/packet');
exports.command = 'packet <hexData>';
exports.description = 'Decode a miIO UDP packet';
exports.builder = {
token: {
required: true,
description: 'Token to use for decoding'
}
};
exports.handler = function(argv) {
const packet = new Packet();
packet.token = Buffer.from(argv.token, 'hex');
const raw = Buffer.from(argv.hexData, 'hex');
packet.raw = raw;
const data = packet.data;
if(! data) {
log.error('Could not extract data from packet, check your token and packet data');
} else {
log.plain('Hex: ', data.toString('hex'));
log.plain('String: ', data.toString());
}
};
|
/* eslint no-console: 1 */
console.warn('You are using the default filter for the institutions service. For more information about event filters see https://docs.feathersjs.com/api/events.html#event-filtering'); // eslint-disable-line no-console
module.exports = function (data, connection, hook) { // eslint-disable-line no-unused-vars
return data;
};
|
/**
* @fileOverview The file overview and the following infos will be display in the "File Index" of jsDoc
* @author A. Livet
* @version 1.0.1
*/
/**
* Sample that show how to properly document your code for jsdoc
*/
/**
* @constant This is a constant declaration which will be displayed in the _global_ section of the jsdoc
*/
var ACCELERATION = 9.80665;
Core.Object.extend('Sample.MyObject',
/**
* The lends tag is used to tell jsdoc that we define an object from a
* JSON like structure. The # at the end of the name specify that we
* are working on the prototype section of the object. Note that we
* can't add anything except the class name in the lends tag line.
* @lends Sample.MyObject#
*/
{
/**
* Event declaration, we must specify the event name cause there
* is no function related to them. Fires on disconnection
* @name Sample.MyObject#disconnect
* @event
*/
/**
* Fires on a connection to something.
* @name Sample.MyObject#connect
* @event
* @param {boolean} autodisconnect
*/
/**
* By default, class fields are not included in the
* documentation. If you want to expose a field, you need to
* surround your comment with jsdoc doclet. We can define the
* default field value with the tag default
* @default 12
*/
myVar: 12,
//This field won't be included in the documentation cause we do
//not document it with jsdoc doclet.
myVar2: undefined,
/**
* This one is a documented field but explicitly ignored.
* @ignore
*/
myVar4: 42,
//This one will be documented with the property tag
documentedInConsctructor: 24,
/**
* @constructs This tag precises that this function is the constructor
* @class Here we can put the description of the class (we can't put it above the extend call cause we won't have the constructor description otherwise, maybe a jsdoc bug).
* Create a new class called MyObject in the namespace Sample.
* @extends Core.Object
* @property {number} documentedInConsctructor This is a field documented with the <b>property</b> tag in the constructor,
* it's not very elegant but may be usefull in some cases.
* @param {object} config If you want "config" to be display as a function paramter (inside the parenthesis) you must specify the param name config.
* @param {number} config.myVar This is the description of myVar which is a number
*/
constructor: function(config) {
// check if myVar is present in config.
// in this case, init with its value
if('myVar' in config) {
// use "this" to access all method and field
// of the current instance of the class
this.myVar = config.myVar;
}
//Events are documented at the begining of the class
this.addEvents('connect', 'disconnect');
},
/**
* @description The Description tag is implicite on the first comment line, but you can use it
* Like all tag, a description can be multi line as long as there is no arobase symbol in it.
* Multi line description
* We can use the <b>link</b> tag which like the <b>see</b> tag but can be used in others tags like this {@link MyNewNameSpace}
* Note the you can't use the <b>link</b> tag in the see tag.
* @param {string} myArg1 descrption of myArg1 which is a String
* @param {MyNewNameSpace} myArg2 descrption of myArg2 which is an Object documented in the framework (a link will be automatically generated)
* @param {number} [myArg3=1.618] Optional parameter with a default value
* @throws {OutOfMemeory} If the function can throw an exception you can add it to the description via the <b>throws</b> tag.
* @see <a href="http://daniel.erasme.lan:8080/era/samples/button/">The see tag can be use to refere to an hyper text link</a>.
* @see MyNewNameSpace or to add a reference to another description
* @see Sample.MyObject#deprecatedMethod here it is a reference to an instance member of a class
* @see Sample.MyObject.myStaticMethod And here it is a reference to an static member of a class
* @example
* //The example tag will generate a code snippet, properlly display
* var obj = new Sample.MyObject({myVar : 42});
* obj.aMethod("foo", new Ui.Button());
*/
aMethod: function(myArg1, myArg2, myArg3) {
},
/**
* @deprecated This is how we mark deprecated method
*/
deprecatedMethod: function() {
},
/**
* This method has been added in version 2.0 so we can use the <b>since</b> tag to specify this.
* @since version 2.0
*/
newMethod: function() {
},
/**
* Some times jsdoc complains about function inside function that are not documented
* The best way to avois them is to use no-code meta tag (I don't why but the ignore tag doesn't work in that case)
*/
jsdocWarningMethod: function(){
/**#nocode+ Avoid Jsdoc warnings...*/
var newEvent = {};
newEvent.preventDefault = function() {};
/**#nocode-*/
},
/**
* We can also use the <b>inner</b> tag to tell jsdoc that a function is intern (and also private) and don't need to be documented.
*/
jsdocOtherWarningMethod: function(obj){
var newEvent = {};
/**@inner*/
newEvent.preventDefault = function() {};
},
/**
* This is a defacto private method cause it's prefixed by an underscore.
*/
_nativeJsDocPrivateMethod: function(){
},
/** @private This method won't be include in the doc unless we use the option -p at the jsdoc generation.*/
singlePrivateMethod: function(){
},
/**#@+ This is a meta tag it will be apply on all the code above until the meta tag closure
* @private All the above function will be mark as private
*/
otherPrivateMethod: function(){
},
andAnotherOnePrivateMethod: function(){
},
/**#@- meta tag closure*/
/**
* An Example of function treated like a field in the doc. Rare case
* @field
* @type string
*/
fullName: function() {
return this.myVar + this.myVar2;
}
},
/**
* Function override are also part of the object prototype
* @lends Sample.MyObject#
*/
{
/**
* @see Core.Object#toString Use the <b>see</b> tag to link to another description.
* Don't use the <b>borrows</b> tag to copy description from another class cause it's buggy and experimental
*/
toString: function() {
// when you override a method, you can always called
// the overrided method with the following syntax:
var res = Sample.MyObject.base.toString.call(this);
return("Sample.MyObject ("+res+")");
}
},
/**
* And it's how we document the static part (without #)
* @lends Sample.MyObject
*/
{
/**
* declare a static field. To access its value
* @example Sample.MyObject.myStaticField
*/
myStaticField: 32,
/**
* the static constructor is called only once when the class is
* declared. In this constructor, "this" correspond to Sample.MyObject
*/
constructor: function() {
},
/**
* declare a static method.
* @example Sample.MyObject.myStaticMethod();
*/
myStaticMethod: function() {
}
});
/**
* Here I describe the constructor
* @class This is a classical class+constructor description
*/
Classic = function () {
};
/**
* Classical method of a non Core.Object class
*/
Classic.prototype.method = function() {
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:b30d3c45e462d6eb97105a2e111bb521dbd53fd852c78bc59a0f3c03de914b3f
size 13352
|
import { className } from '../consts.js';
import Element from './elements.js';
const EMPTY_STRING = '';
class Spinner extends Element {
constructor() {
super();
this._create();
}
_create() {
this.self = this.createDiv();
this._setClass(this.self, [className.SPINNER]);
var i;
for (i = 0 ; i < 3 ; i++) {
this.self.appendChild(this.createDiv());
}
}
insert(target) {
this._setContent(target, EMPTY_STRING);
target.appendChild(this.self);
}
remove(target) {
if (target.firstElementChild) {
target.removeChild(this.self);
}
}
}
export { Spinner as default };
|
const files = require('../../lib/utils/files');
describe("files.getUri",function(){
it("correct file URI",function(){
expect(files.getUri("file:///test/file")).to.equal("file:///test/file");
})
it("absolute file",function(){
expect(files.getUri("/test/file")).to.equal("file:///test/file");
})
it("relative file",function(){
var pwd = process.env["PWD"];
process.env["PWD"] = "/";
expect(files.getUri("file://test/file")).to.equal("file:///test/file");
process.env["PWD"] = pwd;
});
it("Other protocol URI",function(){
expect(files.getUri("http://test/file")).to.equal("http://test/file");
});
})
|
var sessionid = '';
var sessionrole = '';
var socket = io();
/* selector functions to interact with the HTML and server via socket.io */
$(document).ready(function() {
// when user picks a role
$("select").on("change", function() {
sessionrole = $("select option:selected").text()
//socket.emit('loggedin', {"role": sessionrole});
if (sessionrole === "admin")
sessiontext = " As an admin, you can create new post submissions and moderate posts by other admins, users and guests."
else if (sessionrole === "user")
sessiontext = " As a user, you can create new post submissions, see your submissions awaiting moderation and subscribe to published posts."
else if (sessionrole === "guest")
sessiontext = " As a guest viewer, you can create new post submissions and see published posts."
// lock selection
//$("#user-role").html('<div><h4><span class="glyphicon glyphicon-lock" aria-hidden="true"></span> '+sessionrole+'<span style="font-size:12px;"> '+sessiontext+'</span>'+'</h4></div>')
$("#all_posts").empty();
$("#all_published_posts").empty();
socket.emit('update_role', {"role": sessionrole});
})
$('[data-toggle="popover"]').popover({html : true,
content: function() {
return $('#popover_content_wrapper').html();
}
});
});
// on post submission
$('form').submit(function() {
var jsonObject = {
"role": sessionrole,
"title": $('#title').val(),
"post": $('#post').val()
};
socket.emit('on_blog_post', jsonObject);
$('#title').val('');
$('#post').val('');
return false;
});
// on trying to subscribe to newly published posts
$("#subscribe_publish").click(function() {
var jsonObject = {
"role": sessionrole,
"session": sessionid
};
socket.emit('subscribe_publish', jsonObject);
});
// on trying to subscribe to moderation dashboard
$("#subscribe_pending").click(function() {
var jsonObject = {
"role": sessionrole,
"session": sessionid
};
socket.emit('subscribe_pending', jsonObject);
});
// on trying to approve a pending post inside the moderation dashboard
$("#approve_pending").click(function() {
socket.emit('approve_pending', {"role": sessionrole});
});
// on successful approval of blog post (i.e. via admin role)
socket.on('blog_post_approved', function(response) {
var id = response._id;
var msg = response._source;
var text = '{Title:' + msg.title + ', Post: ' + msg.post + '}';
if ($("#" + id).length) {
$('#' + id).remove();
}
var img = document.createElement('img');
img.className = 'img-circle';
img.alt = 'Cinque Terre';
img.height = 25;
img.width = 25;
img.src = msg.user.url;
// add the new post as a <li>
var li = document.createElement('li');
li.className = 'list-group-item';
li.id = id;
li.appendChild(img);
li.appendChild(document.createTextNode(text));
// add a "disapprove" label
var iDiv = document.createElement('span');
iDiv.className = 'dashboard-post label label-warning';
iDiv.appendChild(document.createTextNode('Moderate'));
li.appendChild(iDiv);
// try to move to pending, (i.e. only admin role can do this)
$(iDiv).on('click', function() {
var jsonObject = {
"role": sessionrole,
"id": id
};
socket.emit('move_to_pending', jsonObject);
});
$('#all_published_posts').append(li);
});
// on creation of a blog post (adding the post to the moderation board)
socket.on('blog_post_created', function(response) {
var id = response._id;
var msg = response._source;
var text = '{Title:' + msg.title + ', Post: ' + msg.post + '}';
if ($("#" + id).length) {
$('#' + id).remove();
}
var img = document.createElement('img');
img.className = 'img-circle';
img.alt = 'Cinque Terre';
img.height = 25;
img.width = 25;
img.src = msg.user.url;
var li = document.createElement('li');
li.className = 'list-group-item';
li.id = id;
li.appendChild(img);
li.appendChild(document.createTextNode(text));
var li = document.createElement('li');
li.className = 'list-group-item';
li.id = id;
li.appendChild(img);
li.appendChild(document.createTextNode(text));
// add a "publish" action label
var iDiv = document.createElement('span');
iDiv.className = 'dashboard-post label label-success';
iDiv.appendChild(document.createTextNode('Publish'));
// add a "delete" action label
var deleteDiv = document.createElement('span');
deleteDiv.className = 'dashboard-post label label-danger';
deleteDiv.appendChild(document.createTextNode('Delete'));
li.appendChild(deleteDiv);
li.appendChild(iDiv);
// moves the post to publish board (only an admin role can do this)
$(iDiv).on('click', function() {
var jsonObject = {
"role": sessionrole,
"id": id
};
socket.emit('approve_pending', jsonObject);
});
// deletes the post (only an admin role can do this)
$(deleteDiv).on('click', function() {
var jsonObject = {
"role": sessionrole,
"id": id,
"type": "pendingpost"
};
socket.emit('delete_post', jsonObject);
});
$('#all_posts').append(li);
});
// remove the post from UI on successful deletion
socket.on('blog_post_deleted', function(response) {
var id = response._id;
$('#' + id).remove();
});
// successful pending subscription event
socket.on('subscribe_pending', function() {
$("#subscribe_pending").removeClass("btn-info").addClass("btn-success").html("<span class='glyphicon glyphicon-ok'></span> Subscribed to Pending Posts");
});
// broadcast pending subscribe count
socket.on('subscribe_pending_count', function(msg) {
$('#pending_subcount').text(msg);
});
// successful publish subscription event
socket.on('subscribe_publish', function() {
$("#subscribe_publish").removeClass("btn-info").addClass("btn-success").html("<span class='glyphicon glyphicon-ok'></span> Subscribed to Published Posts");
});
// broadcast publish subscribe count
socket.on('subscribe_publish_count', function(msg) {
$('#publish_subcount').text(msg);
});
// broadcast failure in action as alerts
socket.on('failure', function(msg) {
alert(msg);
});
// assigns a session id to this client,
// which is used for all further communications
// (like, can the client with session id x delete post y?)
socket.on('joined', function(msg) {
sessionid = msg;
});
|
/**
* Eco gulpfile
*/
/* global require */
// For auto-transpiling spec files
require("babel-register")({
presets: ["es2015"]
});
const gulp = require("gulp");
const plugins = require("gulp-load-plugins")();
function getTask(task) {
return require(`./gulp-tasks/${task}`)(gulp, plugins);
}
// Run source code through eslint
gulp.task("lint", getTask("lint"));
// Builds the project into dist/eco.min.js
gulp.task("build", gulp.parallel("lint", getTask("build").build));
// Builds the project and rebuilds when changes are made
gulp.task("watch", gulp.series("build", getTask("build").watch));
// Runs the ./spec/e2e tests within browsers and reruns if changes are made
gulp.task(
"e2e",
gulp.series("build", gulp.parallel("watch", getTask("test").e2e))
);
// Runs the benchmark test suite
gulp.task("bench", gulp.series("build", getTask("test").benchmark));
// Runs the ./spec/unit tests in node.js and reruns if changes are made
gulp.task("unit", getTask("test").watchUnitTests);
|
'use strict';
angular.module('myApp.view1', ['ngRoute', 'services', 'top-nav'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl as vm'
});
}])
.controller('View1Ctrl', ['ItemService', '$location', 'PaymentService', function(ItemService, $location, PaymentService) {
var vm = this;
// methods
vm.init = init;
vm.viewItem = viewItem;
// properties
vm.itemService = ItemService;
vm.items = [];
// activate
vm.init();
// method definitions
function init() {
vm.items = ItemService.getItems();
//PaymentService.buyItem(); Put this where users can pay for an item
}
function viewItem(item) {
$location.url('view2/' + item.id);
}
}]);
|
module.exports = {
plugins: ["tailwindcss", "autoprefixer"],
};
|
Ext.define('App.view.grid.product.stocks',{
extend : 'Ext.grid.Panel',
alias : 'widget.gridProductStocks',
store : 'App.store.product.pstocks',
columnLines : true,
columnWidth: '95%',
emptyText: 'Empty Stocks',
defaults:{
flex: 1
},
columns:[
{ header: 'id', dataIndex : 'id'},
{ header: 'total', dataIndex : 'total'},
{
header: translations.field.warehouse,
dataIndex : 'catwh_id',
renderer: function(v,m,rec){
return rec.getCatwh().get('name');
}
},
{
header: translations.field.length,
dataIndex : 'lengthfabric'
},
{
header: 'onday',
dataIndex : 'onday'
},
{ header: 'product_id', dataIndex : 'product_id'
},
{ header: 'wh_id', dataIndex : 'wh_id',
renderer: function(v,m,rec){
return rec.getWh().get('name');
}
},
{ header: 'unit_id', dataIndex : 'unit_id'
},
{ header: 'uuid', dataIndex : 'uuid'
},
{ header: 'lastupdateby_id', dataIndex : 'lastupdateby_id'
},
{ header: 'createby_id', dataIndex : 'createby_id'},
{ header: 'updated_at', dataIndex : 'updated_at'},
{ header: 'created_at', dataIndex : 'created_at'}
],
dockedItems:[
{
xtype : 'pagingtoolbar',
displayInfo:true,
dock: 'bottom',
store: 'App.store.product.pstocks',
itemId: 'pgStockId'
}
]
}); |
"use strict"
$("document").ready(function () {
setLandingImage();
});
// random background images
function setLandingImage () {
var imageFolder;
var chosenImageArray;
var fullSizeImageArray = [
"construction-rs",
"daisy-rs",
"dandelion-rs",
"forest-rs",
"hydrant-rs",
"lake-rs",
"river-rs",
"roots-rs",
"sunrise-rs"
];
var mobileImageArray = [
"hydrant",
"sunrise",
"lights",
"tree",
"fan",
"beach"
];
if (screen.width <= 699) {
imageFolder = "mobile"
chosenImageArray = mobileImageArray
} else {
imageFolder = "full_screen"
chosenImageArray = fullSizeImageArray
}
var randomNumber = Math.floor(Math.random() * chosenImageArray.length);
var randomImageName = chosenImageArray[randomNumber];
$(".landing").css("background", `url(dist/css/img/${imageFolder}/${randomImageName}.jpg) no-repeat center`)
};
// toggle section divs
function navigateLanding (page) {
$(".landing").fadeOut(600)
$(".section").each(function () {
if ($(this).attr("id") == page) {
$(this).fadeIn(1000)
} else {
$(this).hide()
}
})
}
// go back to landing page
function backToLanding (page) {
$(`.${page}`).fadeOut(600, function () {
$(".landing").fadeIn(1000)
})
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21 18.17l-2-2V14h-1c-1.1 0-2-.9-2-2V6c0-1.49 1.6-3.32 3.76-3.85.63-.15 1.24.33 1.24.98v15.04zm.19 4.44c-.39.39-1.02.39-1.41 0l-9.76-9.76c-.33.09-.66.15-1.02.15v8c0 .55-.45 1-1 1s-1-.45-1-1v-8c-2.21 0-4-1.79-4-4V5.83L1.39 4.22a.9959.9959 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0l18.38 18.38c.4.39.4 1.03.01 1.42zM6.17 9L5 7.83V9h1.17zM13 9V3c0-.55-.45-1-1-1s-1 .45-1 1v5.17l1.85 1.85c.09-.33.15-.66.15-1.02zM9 3c0-.55-.45-1-1-1s-1 .45-1 1v1.17l2 2V3z" />
, 'NoMealsRounded');
|
var edit = (function(){
// Cache DOM
var $defaultSection = $('#about_you_dashboard');
var $defaultLink = $("#user_menu li a[href='#about_you']");
var $rowSections = $('.container-fluid .hidden');
var $currentRow = $('.container-fluid .hidden' + window.location.hash + '_dashboard');
var $menuLinks = $('#user_menu li a');
var $hashLink = $.grep( $( '#user_menu li a' ), function (o) {
return o.hash == window.location.hash;
});
// Bind Events
$menuLinks.on('click', toggleMenuActive);
// Functions
function showHashLocation() {
if(window.location.hash == '') {
$defaultSection.removeClass('hidden');
$($defaultLink).parent().addClass('active');
} else {
$currentRow.removeClass('hidden');
$($hashLink).parent().addClass('active');
}
}
function toggleMenuActive() {
$menuLinks.parent().removeClass('active');
$rowSections.addClass('hidden');
$(this).parent().addClass('active');
$('.container-fluid' + this.hash + '_dashboard').removeClass('hidden');
}
showHashLocation();
return{};
})(); |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.styles = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _withStyles = _interopRequireDefault(require("../styles/withStyles"));
var _ListContext = _interopRequireDefault(require("./ListContext"));
var styles = {
/* Styles applied to the root element. */
root: {
listStyle: 'none',
margin: 0,
padding: 0,
position: 'relative'
},
/* Styles applied to the root element if `disablePadding={false}`. */
padding: {
paddingTop: 8,
paddingBottom: 8
},
/* Styles applied to the root element if dense. */
dense: {},
/* Styles applied to the root element if a `subheader` is provided. */
subheader: {
paddingTop: 0
}
};
exports.styles = styles;
var List = _react.default.forwardRef(function List(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'ul' : _props$component,
_props$dense = props.dense,
dense = _props$dense === void 0 ? false : _props$dense,
_props$disablePadding = props.disablePadding,
disablePadding = _props$disablePadding === void 0 ? false : _props$disablePadding,
subheader = props.subheader,
other = (0, _objectWithoutProperties2.default)(props, ["children", "classes", "className", "component", "dense", "disablePadding", "subheader"]);
var context = _react.default.useMemo(function () {
return {
dense: dense
};
}, [dense]);
return _react.default.createElement(_ListContext.default.Provider, {
value: context
}, _react.default.createElement(Component, (0, _extends2.default)({
className: (0, _clsx.default)(classes.root, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader, className),
ref: ref
}, other), subheader, children));
});
process.env.NODE_ENV !== "production" ? List.propTypes = {
/**
* The content of the component.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: _propTypes.default.object.isRequired,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: _propTypes.default.elementType,
/**
* If `true`, compact vertical padding designed for keyboard and mouse input will be used for
* the list and list items.
* The property is available to descendant components as the `dense` context.
*/
dense: _propTypes.default.bool,
/**
* If `true`, vertical padding will be removed from the list.
*/
disablePadding: _propTypes.default.bool,
/**
* The content of the subheader, normally `ListSubheader`.
*/
subheader: _propTypes.default.node
} : void 0;
var _default = (0, _withStyles.default)(styles, {
name: 'MuiList'
})(List);
exports.default = _default; |
$(document).ready(function () {
console.log('contact forms initialized');
});
|
/**
* SETTINGS
* --------
*
* This file explains many default values and lower level abstraction
*/
//TODO:100 get token from state!
const basicHeaderRequest = (
token = '7924JKEE2H1O1EFKRGZ28N8FZ0JBV5UHLU36YQ02K23VUK7Q12ZEAXQ79MGFQ9WOC5VZ5GMBI3Y27F6091'
) => ( {
credentials: 'same-origin', //cors
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Groups groups_token=${token}`
}
} );
export const headers = ( method, request = {} ) => {
return { ...basicHeaderRequest(), ...request, method };
};
/**
* Returns one of supported language, 'en' if not.
* Supported languages: 'nl', 'fr', 'en' (default).
* @returns {string}
*/
export function navigatorLanguage() {
const locale = ( window.navigator.userLanguage || window.navigator.language );
const parsedLocale = /..-../.test( locale ) ? locale.split( '-' )[ 0 ] : locale.split( '_' )[ 0 ];
if ( ( parsedLocale !== 'en' ) && ( parsedLocale !== 'fr' ) && ( parsedLocale !== 'nl' ) ) {
return 'en';
}
return parsedLocale;
}
function createInitialState() {
const data = {
data: [],
//keys: [],
//translations: [],
//words: [],
mappingKLN: [],
selectedNS: { id: 0, label: 'default' },
nameSpaceSet: [],
selectedTS: { id: 0, label: 'default' }
};
const auth = {
username: 'No username',
token: null,
isAuthenticated: false
};
const config = {
language: 'en',
isFetching: true,
didInvalidate: false,
lastUpdated: Date.now()
};
const notification = {
error: null,
success: null
};
//console.log('NODE_ENV = ', process.env.NODE_ENV);
if ( process.env.NODE_ENV === 'test' ) {
return {
data,
auth,
config,
notification
};
} else {
return {
data,
auth: {
...auth,
username: ( localStorage && localStorage.lastLogin ) || 'No username'
},
config: {
...config,
language: ( localStorage && localStorage.language ) || navigatorLanguage()
},
notification
};
}
}
export const initialState = createInitialState();
|
/*jshint esversion:6*/
import babelrc from 'babelrc-rollup';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
export default {
entry: 'source/js/app.js',
dest:'build/js/bundle.js',
plugins: [
nodeResolve({
jsnext: true,
main: true
}),
commonjs(),
babel(babelrc())
],
format: 'iife',
useStrict:false,
moduleName:'cashmesh'
};
|
/*!
* fancyBox - jQuery Plugin
* version: 2.1.3 (Tue, 23 Oct 2012)
* @requires jQuery v1.6 or later
*
* Examples at https://fancyapps.com/fancybox/
* License: www.fancyapps.com/fancybox/#license
*
* Copyright 2012 Janis Skarnelis - janis@fancyapps.com
*
*/
(function (window, document, $, undefined) {
"use strict";
var W = $(window),
D = $(document),
F = $.fancybox = function () {
F.open.apply( this, arguments );
},
didUpdate = null,
isTouch = document.createTouch !== undefined,
isQuery = function(obj) {
return obj && obj.hasOwnProperty && obj instanceof $;
},
isString = function(str) {
return str && $.type(str) === "string";
},
isPercentage = function(str) {
return isString(str) && str.indexOf('%') > 0;
},
isScrollable = function(el) {
return (el && !(el.style.overflow && el.style.overflow === 'hidden') && ((el.clientWidth && el.scrollWidth > el.clientWidth) || (el.clientHeight && el.scrollHeight > el.clientHeight)));
},
getScalar = function(orig, dim) {
var value = parseInt(orig, 10) || 0;
if (dim && isPercentage(orig)) {
value = F.getViewport()[ dim ] / 100 * value;
}
return Math.ceil(value);
},
getValue = function(value, dim) {
return getScalar(value, dim) + 'px';
};
$.extend(F, {
// The current version of fancyBox
version: '2.1.3',
defaults: {
padding : 15,
margin : 20,
width : 800,
height : 600,
minWidth : 100,
minHeight : 100,
maxWidth : 9999,
maxHeight : 9999,
autoSize : true,
autoHeight : false,
autoWidth : false,
autoResize : true,
autoCenter : !isTouch,
fitToView : true,
aspectRatio : false,
topRatio : 0.5,
leftRatio : 0.5,
scrolling : 'auto', // 'auto', 'yes' or 'no'
wrapCSS : '',
arrows : true,
closeBtn : true,
closeClick : false,
nextClick : false,
mouseWheel : true,
autoPlay : false,
playSpeed : 3000,
preload : 3,
modal : false,
loop : true,
ajax : {
dataType : 'html',
headers : { 'X-fancyBox': true }
},
iframe : {
scrolling : 'auto',
preload : true
},
swf : {
wmode: 'transparent',
allowfullscreen : 'true',
allowscriptaccess : 'always'
},
keys : {
next : {
13 : 'left', // enter
34 : 'up', // page down
39 : 'left', // right arrow
40 : 'up' // down arrow
},
prev : {
8 : 'right', // backspace
33 : 'down', // page up
37 : 'right', // left arrow
38 : 'down' // up arrow
},
close : [27], // escape key
play : [32], // space - start/stop slideshow
toggle : [70] // letter "f" - toggle fullscreen
},
direction : {
next : 'left',
prev : 'right'
},
scrollOutside : true,
// Override some properties
index : 0,
type : null,
href : null,
content : null,
title : null,
// HTML templates
tpl: {
wrap : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',
image : '<img class="fancybox-image" src="{href}" alt="" />',
iframe : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + ($.browser.msie ? ' allowtransparency="true"' : '') + '></iframe>',
error : '<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',
closeBtn : '<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',
next : '<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',
prev : '<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'
},
// Properties for each animation type
// Opening fancyBox
openEffect : 'fade', // 'elastic', 'fade' or 'none'
openSpeed : 250,
openEasing : 'swing',
openOpacity : true,
openMethod : 'zoomIn',
// Closing fancyBox
closeEffect : 'fade', // 'elastic', 'fade' or 'none'
closeSpeed : 250,
closeEasing : 'swing',
closeOpacity : true,
closeMethod : 'zoomOut',
// Changing next gallery item
nextEffect : 'elastic', // 'elastic', 'fade' or 'none'
nextSpeed : 250,
nextEasing : 'swing',
nextMethod : 'changeIn',
// Changing previous gallery item
prevEffect : 'elastic', // 'elastic', 'fade' or 'none'
prevSpeed : 250,
prevEasing : 'swing',
prevMethod : 'changeOut',
// Enable default helpers
helpers : {
overlay : true,
title : true
},
// Callbacks
onCancel : $.noop, // If canceling
beforeLoad : $.noop, // Before loading
afterLoad : $.noop, // After loading
beforeShow : $.noop, // Before changing in current item
afterShow : $.noop, // After opening
beforeChange : $.noop, // Before changing gallery item
beforeClose : $.noop, // Before closing
afterClose : $.noop // After closing
},
//Current state
group : {}, // Selected group
opts : {}, // Group options
previous : null, // Previous element
coming : null, // Element being loaded
current : null, // Currently loaded element
isActive : false, // Is activated
isOpen : false, // Is currently open
isOpened : false, // Have been fully opened at least once
wrap : null,
skin : null,
outer : null,
inner : null,
player : {
timer : null,
isActive : false
},
// Loaders
ajaxLoad : null,
imgPreload : null,
// Some collections
transitions : {},
helpers : {},
/*
* Static methods
*/
open: function (group, opts) {
if (!group) {
return;
}
if (!$.isPlainObject(opts)) {
opts = {};
}
// Close if already active
if (false === F.close(true)) {
return;
}
// Normalize group
if (!$.isArray(group)) {
group = isQuery(group) ? $(group).get() : [group];
}
// Recheck if the type of each element is `object` and set content type (image, ajax, etc)
$.each(group, function(i, element) {
var obj = {},
href,
title,
content,
type,
rez,
hrefParts,
selector;
if ($.type(element) === "object") {
// Check if is DOM element
if (element.nodeType) {
element = $(element);
}
if (isQuery(element)) {
obj = {
href : element.data('fancybox-href') || element.attr('href'),
title : element.data('fancybox-title') || element.attr('title'),
isDom : true,
element : element
};
if ($.metadata) {
$.extend(true, obj, element.metadata());
}
} else {
obj = element;
}
}
href = opts.href || obj.href || (isString(element) ? element : null);
title = opts.title !== undefined ? opts.title : obj.title || '';
content = opts.content || obj.content;
type = content ? 'html' : (opts.type || obj.type);
if (!type && obj.isDom) {
type = element.data('fancybox-type');
if (!type) {
rez = element.prop('class').match(/fancybox\.(\w+)/);
type = rez ? rez[1] : null;
}
}
if (isString(href)) {
// Try to guess the content type
if (!type) {
if (F.isImage(href)) {
type = 'image';
} else if (F.isSWF(href)) {
type = 'swf';
} else if (href.charAt(0) === '#') {
type = 'inline';
} else if (isString(element)) {
type = 'html';
content = element;
}
}
// Split url into two pieces with source url and content selector, e.g,
// "/mypage.html #my_id" will load "/mypage.html" and display element having id "my_id"
if (type === 'ajax') {
hrefParts = href.split(/\s+/, 2);
href = hrefParts.shift();
selector = hrefParts.shift();
}
}
if (!content) {
if (type === 'inline') {
if (href) {
content = $( isString(href) ? href.replace(/.*(?=#[^\s]+$)/, '') : href ); //strip for ie7
} else if (obj.isDom) {
content = element;
}
} else if (type === 'html') {
content = href;
} else if (!type && !href && obj.isDom) {
type = 'inline';
content = element;
}
}
$.extend(obj, {
href : href,
type : type,
content : content,
title : title,
selector : selector
});
group[ i ] = obj;
});
// Extend the defaults
F.opts = $.extend(true, {}, F.defaults, opts);
// All options are merged recursive except keys
if (opts.keys !== undefined) {
F.opts.keys = opts.keys ? $.extend({}, F.defaults.keys, opts.keys) : false;
}
F.group = group;
return F._start(F.opts.index);
},
// Cancel image loading or abort ajax request
cancel: function () {
var coming = F.coming;
if (!coming || false === F.trigger('onCancel')) {
return;
}
F.hideLoading();
if (F.ajaxLoad) {
F.ajaxLoad.abort();
}
F.ajaxLoad = null;
if (F.imgPreload) {
F.imgPreload.onload = F.imgPreload.onerror = null;
}
if (coming.wrap) {
coming.wrap.stop(true, true).trigger('onReset').remove();
}
F.coming = null;
// If the first item has been canceled, then clear everything
if (!F.current) {
F._afterZoomOut( coming );
}
},
// Start closing animation if is open; remove immediately if opening/closing
close: function (event) {
F.cancel();
if (false === F.trigger('beforeClose')) {
return;
}
F.unbindEvents();
if (!F.isActive) {
return;
}
if (!F.isOpen || event === true) {
$('.fancybox-wrap').stop(true).trigger('onReset').remove();
F._afterZoomOut();
} else {
F.isOpen = F.isOpened = false;
F.isClosing = true;
$('.fancybox-item, .fancybox-nav').remove();
F.wrap.stop(true, true).removeClass('fancybox-opened');
F.transitions[ F.current.closeMethod ]();
}
},
// Manage slideshow:
// $.fancybox.play(); - toggle slideshow
// $.fancybox.play( true ); - start
// $.fancybox.play( false ); - stop
play: function ( action ) {
var clear = function () {
clearTimeout(F.player.timer);
},
set = function () {
clear();
if (F.current && F.player.isActive) {
F.player.timer = setTimeout(F.next, F.current.playSpeed);
}
},
stop = function () {
clear();
$('body').unbind('.player');
F.player.isActive = false;
F.trigger('onPlayEnd');
},
start = function () {
if (F.current && (F.current.loop || F.current.index < F.group.length - 1)) {
F.player.isActive = true;
$('body').bind({
'afterShow.player onUpdate.player' : set,
'onCancel.player beforeClose.player' : stop,
'beforeLoad.player' : clear
});
set();
F.trigger('onPlayStart');
}
};
if (action === true || (!F.player.isActive && action !== false)) {
start();
} else {
stop();
}
},
// Navigate to next gallery item
next: function ( direction ) {
var current = F.current;
if (current) {
if (!isString(direction)) {
direction = current.direction.next;
}
F.jumpto(current.index + 1, direction, 'next');
}
},
// Navigate to previous gallery item
prev: function ( direction ) {
var current = F.current;
if (current) {
if (!isString(direction)) {
direction = current.direction.prev;
}
F.jumpto(current.index - 1, direction, 'prev');
}
},
// Navigate to gallery item by index
jumpto: function ( index, direction, router ) {
var current = F.current;
if (!current) {
return;
}
index = getScalar(index);
F.direction = direction || current.direction[ (index >= current.index ? 'next' : 'prev') ];
F.router = router || 'jumpto';
if (current.loop) {
if (index < 0) {
index = current.group.length + (index % current.group.length);
}
index = index % current.group.length;
}
if (current.group[ index ] !== undefined) {
F.cancel();
F._start(index);
}
},
// Center inside viewport and toggle position type to fixed or absolute if needed
reposition: function (e, onlyAbsolute) {
var current = F.current,
wrap = current ? current.wrap : null,
pos;
if (wrap) {
pos = F._getPosition(onlyAbsolute);
if (e && e.type === 'scroll') {
delete pos.position;
wrap.stop(true, true).animate(pos, 200);
} else {
wrap.css(pos);
current.pos = $.extend({}, current.dim, pos);
}
}
},
update: function (e) {
var type = (e && e.type),
anyway = !type || type === 'orientationchange';
if (anyway) {
clearTimeout(didUpdate);
didUpdate = null;
}
if (!F.isOpen || didUpdate) {
return;
}
didUpdate = setTimeout(function() {
var current = F.current;
if (!current || F.isClosing) {
return;
}
F.wrap.removeClass('fancybox-tmp');
if (anyway || type === 'load' || (type === 'resize' && current.autoResize)) {
F._setDimension();
}
if (!(type === 'scroll' && current.canShrink)) {
F.reposition(e);
}
F.trigger('onUpdate');
didUpdate = null;
}, (anyway && !isTouch ? 0 : 300));
},
// Shrink content to fit inside viewport or restore if resized
toggle: function ( action ) {
if (F.isOpen) {
F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView;
// Help browser to restore document dimensions
if (isTouch) {
F.wrap.removeAttr('style').addClass('fancybox-tmp');
F.trigger('onUpdate');
}
F.update();
}
},
hideLoading: function () {
D.unbind('.loading');
$('#fancybox-loading').remove();
},
showLoading: function () {
var el, viewport;
F.hideLoading();
el = $('<div id="fancybox-loading"><div></div></div>').click(F.cancel).appendTo('body');
// If user will press the escape-button, the request will be canceled
D.bind('keydown.loading', function(e) {
if ((e.which || e.keyCode) === 27) {
e.preventDefault();
F.cancel();
}
});
if (!F.defaults.fixed) {
viewport = F.getViewport();
el.css({
position : 'absolute',
top : (viewport.h * 0.5) + viewport.y,
left : (viewport.w * 0.5) + viewport.x
});
}
},
getViewport: function () {
var locked = (F.current && F.current.locked) || false,
rez = {
x: W.scrollLeft(),
y: W.scrollTop()
};
if (locked) {
rez.w = locked[0].clientWidth;
rez.h = locked[0].clientHeight;
} else {
// See https://bugs.jquery.com/ticket/6724
rez.w = isTouch && window.innerWidth ? window.innerWidth : W.width();
rez.h = isTouch && window.innerHeight ? window.innerHeight : W.height();
}
return rez;
},
// Unbind the keyboard / clicking actions
unbindEvents: function () {
if (F.wrap && isQuery(F.wrap)) {
F.wrap.unbind('.fb');
}
D.unbind('.fb');
W.unbind('.fb');
},
bindEvents: function () {
var current = F.current,
keys;
if (!current) {
return;
}
// Changing document height on iOS devices triggers a 'resize' event,
// that can change document height... repeating infinitely
W.bind('orientationchange.fb' + (isTouch ? '' : ' resize.fb') + (current.autoCenter && !current.locked ? ' scroll.fb' : ''), F.update);
keys = current.keys;
if (keys) {
D.bind('keydown.fb', function (e) {
var code = e.which || e.keyCode,
target = e.target || e.srcElement;
// Skip esc key if loading, because showLoading will cancel preloading
if (code === 27 && F.coming) {
return false;
}
// Ignore key combinations and key events within form elements
if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey && !(target && (target.type || $(target).is('[contenteditable]')))) {
$.each(keys, function(i, val) {
if (current.group.length > 1 && val[ code ] !== undefined) {
F[ i ]( val[ code ] );
e.preventDefault();
return false;
}
if ($.inArray(code, val) > -1) {
F[ i ] ();
e.preventDefault();
return false;
}
});
}
});
}
if ($.fn.mousewheel && current.mouseWheel) {
F.wrap.bind('mousewheel.fb', function (e, delta, deltaX, deltaY) {
var target = e.target || null,
parent = $(target),
canScroll = false;
while (parent.length) {
if (canScroll || parent.is('.fancybox-skin') || parent.is('.fancybox-wrap')) {
break;
}
canScroll = isScrollable( parent[0] );
parent = $(parent).parent();
}
if (delta !== 0 && !canScroll) {
if (F.group.length > 1 && !current.canShrink) {
if (deltaY > 0 || deltaX > 0) {
F.prev( deltaY > 0 ? 'down' : 'left' );
} else if (deltaY < 0 || deltaX < 0) {
F.next( deltaY < 0 ? 'up' : 'right' );
}
e.preventDefault();
}
}
});
}
},
trigger: function (event, o) {
var ret, obj = o || F.coming || F.current;
if (!obj) {
return;
}
if ($.isFunction( obj[event] )) {
ret = obj[event].apply(obj, Array.prototype.slice.call(arguments, 1));
}
if (ret === false) {
return false;
}
if (obj.helpers) {
$.each(obj.helpers, function (helper, opts) {
if (opts && F.helpers[helper] && $.isFunction(F.helpers[helper][event])) {
opts = $.extend(true, {}, F.helpers[helper].defaults, opts);
F.helpers[helper][event](opts, obj);
}
});
}
$.event.trigger(event + '.fb');
},
isImage: function (str) {
return isString(str) && str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp)((\?|#).*)?$)/i);
},
isSWF: function (str) {
return isString(str) && str.match(/\.(swf)((\?|#).*)?$/i);
},
_start: function (index) {
var coming = {},
obj,
href,
type,
margin,
padding;
index = getScalar( index );
obj = F.group[ index ] || null;
if (!obj) {
return false;
}
coming = $.extend(true, {}, F.opts, obj);
// Convert margin and padding properties to array - top, right, bottom, left
margin = coming.margin;
padding = coming.padding;
if ($.type(margin) === 'number') {
coming.margin = [margin, margin, margin, margin];
}
if ($.type(padding) === 'number') {
coming.padding = [padding, padding, padding, padding];
}
// 'modal' propery is just a shortcut
if (coming.modal) {
$.extend(true, coming, {
closeBtn : false,
closeClick : false,
nextClick : false,
arrows : false,
mouseWheel : false,
keys : null,
helpers: {
overlay : {
closeClick : false
}
}
});
}
// 'autoSize' property is a shortcut, too
if (coming.autoSize) {
coming.autoWidth = coming.autoHeight = true;
}
if (coming.width === 'auto') {
coming.autoWidth = true;
}
if (coming.height === 'auto') {
coming.autoHeight = true;
}
/*
* Add reference to the group, so it`s possible to access from callbacks, example:
* afterLoad : function() {
* this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : '');
* }
*/
coming.group = F.group;
coming.index = index;
// Give a chance for callback or helpers to update coming item (type, title, etc)
F.coming = coming;
if (false === F.trigger('beforeLoad')) {
F.coming = null;
return;
}
type = coming.type;
href = coming.href;
if (!type) {
F.coming = null;
//If we can not determine content type then drop silently or display next/prev item if looping through gallery
if (F.current && F.router && F.router !== 'jumpto') {
F.current.index = index;
return F[ F.router ]( F.direction );
}
return false;
}
F.isActive = true;
if (type === 'image' || type === 'swf') {
coming.autoHeight = coming.autoWidth = false;
coming.scrolling = 'visible';
}
if (type === 'image') {
coming.aspectRatio = true;
}
if (type === 'iframe' && isTouch) {
coming.scrolling = 'scroll';
}
// Build the neccessary markup
coming.wrap = $(coming.tpl.wrap).addClass('fancybox-' + (isTouch ? 'mobile' : 'desktop') + ' fancybox-type-' + type + ' fancybox-tmp ' + coming.wrapCSS).appendTo( coming.parent || 'body' );
$.extend(coming, {
skin : $('.fancybox-skin', coming.wrap),
outer : $('.fancybox-outer', coming.wrap),
inner : $('.fancybox-inner', coming.wrap)
});
$.each(["Top", "Right", "Bottom", "Left"], function(i, v) {
coming.skin.css('padding' + v, getValue(coming.padding[ i ]));
});
F.trigger('onReady');
// Check before try to load; 'inline' and 'html' types need content, others - href
if (type === 'inline' || type === 'html') {
if (!coming.content || !coming.content.length) {
return F._error( 'content' );
}
} else if (!href) {
return F._error( 'href' );
}
if (type === 'image') {
F._loadImage();
} else if (type === 'ajax') {
F._loadAjax();
} else if (type === 'iframe') {
F._loadIframe();
} else {
F._afterLoad();
}
},
_error: function ( type ) {
$.extend(F.coming, {
type : 'html',
autoWidth : true,
autoHeight : true,
minWidth : 0,
minHeight : 0,
scrolling : 'no',
hasError : type,
content : F.coming.tpl.error
});
F._afterLoad();
},
_loadImage: function () {
// Reset preload image so it is later possible to check "complete" property
var img = F.imgPreload = new Image();
img.onload = function () {
this.onload = this.onerror = null;
F.coming.width = this.width;
F.coming.height = this.height;
F._afterLoad();
};
img.onerror = function () {
this.onload = this.onerror = null;
F._error( 'image' );
};
img.src = F.coming.href;
if (img.complete !== true) {
F.showLoading();
}
},
_loadAjax: function () {
var coming = F.coming;
F.showLoading();
F.ajaxLoad = $.ajax($.extend({}, coming.ajax, {
url: coming.href,
error: function (jqXHR, textStatus) {
if (F.coming && textStatus !== 'abort') {
F._error( 'ajax', jqXHR );
} else {
F.hideLoading();
}
},
success: function (data, textStatus) {
if (textStatus === 'success') {
coming.content = data;
F._afterLoad();
}
}
}));
},
_loadIframe: function() {
var coming = F.coming,
iframe = $(coming.tpl.iframe.replace(/\{rnd\}/g, new Date().getTime()))
.attr('scrolling', isTouch ? 'auto' : coming.iframe.scrolling)
.attr('src', coming.href);
// This helps IE
$(coming.wrap).bind('onReset', function () {
try {
$(this).find('iframe').hide().attr('src', '//about:blank').end().empty();
} catch (e) {}
});
if (coming.iframe.preload) {
F.showLoading();
iframe.one('load', function() {
$(this).data('ready', 1);
// iOS will lose scrolling if we resize
if (!isTouch) {
$(this).bind('load.fb', F.update);
}
// Without this trick:
// - iframe won't scroll on iOS devices
// - IE7 sometimes displays empty iframe
$(this).parents('.fancybox-wrap').width('100%').removeClass('fancybox-tmp').show();
F._afterLoad();
});
}
coming.content = iframe.appendTo( coming.inner );
if (!coming.iframe.preload) {
F._afterLoad();
}
},
_preloadImages: function() {
var group = F.group,
current = F.current,
len = group.length,
cnt = current.preload ? Math.min(current.preload, len - 1) : 0,
item,
i;
for (i = 1; i <= cnt; i += 1) {
item = group[ (current.index + i ) % len ];
if (item.type === 'image' && item.href) {
new Image().src = item.href;
}
}
},
_afterLoad: function () {
var coming = F.coming,
previous = F.current,
placeholder = 'fancybox-placeholder',
current,
content,
type,
scrolling,
href,
embed;
F.hideLoading();
if (!coming || F.isActive === false) {
return;
}
if (false === F.trigger('afterLoad', coming, previous)) {
coming.wrap.stop(true).trigger('onReset').remove();
F.coming = null;
return;
}
if (previous) {
F.trigger('beforeChange', previous);
previous.wrap.stop(true).removeClass('fancybox-opened')
.find('.fancybox-item, .fancybox-nav')
.remove();
}
F.unbindEvents();
current = coming;
content = coming.content;
type = coming.type;
scrolling = coming.scrolling;
$.extend(F, {
wrap : current.wrap,
skin : current.skin,
outer : current.outer,
inner : current.inner,
current : current,
previous : previous
});
href = current.href;
switch (type) {
case 'inline':
case 'ajax':
case 'html':
if (current.selector) {
content = $('<div>').html(content).find(current.selector);
} else if (isQuery(content)) {
if (!content.data(placeholder)) {
content.data(placeholder, $('<div class="' + placeholder + '"></div>').insertAfter( content ).hide() );
}
content = content.show().detach();
current.wrap.bind('onReset', function () {
if ($(this).find(content).length) {
content.hide().replaceAll( content.data(placeholder) ).data(placeholder, false);
}
});
}
break;
case 'image':
content = current.tpl.image.replace('{href}', href);
break;
case 'swf':
content = '<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + href + '"></param>';
embed = '';
$.each(current.swf, function(name, val) {
content += '<param name="' + name + '" value="' + val + '"></param>';
embed += ' ' + name + '="' + val + '"';
});
content += '<embed src="' + href + '" type="application/x-shockwave-flash" width="100%" height="100%"' + embed + '></embed></object>';
break;
}
if (!(isQuery(content) && content.parent().is(current.inner))) {
current.inner.append( content );
}
// Give a chance for helpers or callbacks to update elements
F.trigger('beforeShow');
// Set scrolling before calculating dimensions
current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));
// Set initial dimensions and start position
F._setDimension();
F.reposition();
F.isOpen = false;
F.coming = null;
F.bindEvents();
if (!F.isOpened) {
$('.fancybox-wrap').not( current.wrap ).stop(true).trigger('onReset').remove();
} else if (previous.prevMethod) {
F.transitions[ previous.prevMethod ]();
}
F.transitions[ F.isOpened ? current.nextMethod : current.openMethod ]();
F._preloadImages();
},
_setDimension: function () {
var viewport = F.getViewport(),
steps = 0,
canShrink = false,
canExpand = false,
wrap = F.wrap,
skin = F.skin,
inner = F.inner,
current = F.current,
width = current.width,
height = current.height,
minWidth = current.minWidth,
minHeight = current.minHeight,
maxWidth = current.maxWidth,
maxHeight = current.maxHeight,
scrolling = current.scrolling,
scrollOut = current.scrollOutside ? current.scrollbarWidth : 0,
margin = current.margin,
wMargin = getScalar(margin[1] + margin[3]),
hMargin = getScalar(margin[0] + margin[2]),
wPadding,
hPadding,
wSpace,
hSpace,
origWidth,
origHeight,
origMaxWidth,
origMaxHeight,
ratio,
width_,
height_,
maxWidth_,
maxHeight_,
iframe,
body;
// Reset dimensions so we could re-check actual size
wrap.add(skin).add(inner).width('auto').height('auto').removeClass('fancybox-tmp');
wPadding = getScalar(skin.outerWidth(true) - skin.width());
hPadding = getScalar(skin.outerHeight(true) - skin.height());
// Any space between content and viewport (margin, padding, border, title)
wSpace = wMargin + wPadding;
hSpace = hMargin + hPadding;
origWidth = isPercentage(width) ? (viewport.w - wSpace) * getScalar(width) / 100 : width;
origHeight = isPercentage(height) ? (viewport.h - hSpace) * getScalar(height) / 100 : height;
if (current.type === 'iframe') {
iframe = current.content;
if (current.autoHeight && iframe.data('ready') === 1) {
try {
if (iframe[0].contentWindow.document.location) {
inner.width( origWidth ).height(9999);
body = iframe.contents().find('body');
if (scrollOut) {
body.css('overflow-x', 'hidden');
}
origHeight = body.height();
}
} catch (e) {}
}
} else if (current.autoWidth || current.autoHeight) {
inner.addClass( 'fancybox-tmp' );
// Set width or height in case we need to calculate only one dimension
if (!current.autoWidth) {
inner.width( origWidth );
}
if (!current.autoHeight) {
inner.height( origHeight );
}
if (current.autoWidth) {
origWidth = inner.width();
}
if (current.autoHeight) {
origHeight = inner.height();
}
inner.removeClass( 'fancybox-tmp' );
}
width = getScalar( origWidth );
height = getScalar( origHeight );
ratio = origWidth / origHeight;
// Calculations for the content
minWidth = getScalar(isPercentage(minWidth) ? getScalar(minWidth, 'w') - wSpace : minWidth);
maxWidth = getScalar(isPercentage(maxWidth) ? getScalar(maxWidth, 'w') - wSpace : maxWidth);
minHeight = getScalar(isPercentage(minHeight) ? getScalar(minHeight, 'h') - hSpace : minHeight);
maxHeight = getScalar(isPercentage(maxHeight) ? getScalar(maxHeight, 'h') - hSpace : maxHeight);
// These will be used to determine if wrap can fit in the viewport
origMaxWidth = maxWidth;
origMaxHeight = maxHeight;
if (current.fitToView) {
maxWidth = Math.min(viewport.w - wSpace, maxWidth);
maxHeight = Math.min(viewport.h - hSpace, maxHeight);
}
maxWidth_ = viewport.w - wMargin;
maxHeight_ = viewport.h - hMargin;
if (current.aspectRatio) {
if (width > maxWidth) {
width = maxWidth;
height = getScalar(width / ratio);
}
if (height > maxHeight) {
height = maxHeight;
width = getScalar(height * ratio);
}
if (width < minWidth) {
width = minWidth;
height = getScalar(width / ratio);
}
if (height < minHeight) {
height = minHeight;
width = getScalar(height * ratio);
}
} else {
width = Math.max(minWidth, Math.min(width, maxWidth));
if (current.autoHeight && current.type !== 'iframe') {
inner.width( width );
height = inner.height();
}
height = Math.max(minHeight, Math.min(height, maxHeight));
}
// Try to fit inside viewport (including the title)
if (current.fitToView) {
inner.width( width ).height( height );
wrap.width( width + wPadding );
// Real wrap dimensions
width_ = wrap.width();
height_ = wrap.height();
if (current.aspectRatio) {
while ((width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight) {
if (steps++ > 19) {
break;
}
height = Math.max(minHeight, Math.min(maxHeight, height - 10));
width = getScalar(height * ratio);
if (width < minWidth) {
width = minWidth;
height = getScalar(width / ratio);
}
if (width > maxWidth) {
width = maxWidth;
height = getScalar(width / ratio);
}
inner.width( width ).height( height );
wrap.width( width + wPadding );
width_ = wrap.width();
height_ = wrap.height();
}
} else {
width = Math.max(minWidth, Math.min(width, width - (width_ - maxWidth_)));
height = Math.max(minHeight, Math.min(height, height - (height_ - maxHeight_)));
}
}
if (scrollOut && scrolling === 'auto' && height < origHeight && (width + wPadding + scrollOut) < maxWidth_) {
width += scrollOut;
}
inner.width( width ).height( height );
wrap.width( width + wPadding );
width_ = wrap.width();
height_ = wrap.height();
canShrink = (width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight;
canExpand = current.aspectRatio ? (width < origMaxWidth && height < origMaxHeight && width < origWidth && height < origHeight) : ((width < origMaxWidth || height < origMaxHeight) && (width < origWidth || height < origHeight));
$.extend(current, {
dim : {
width : getValue( width_ ),
height : getValue( height_ )
},
origWidth : origWidth,
origHeight : origHeight,
canShrink : canShrink,
canExpand : canExpand,
wPadding : wPadding,
hPadding : hPadding,
wrapSpace : height_ - skin.outerHeight(true),
skinSpace : skin.height() - height
});
if (!iframe && current.autoHeight && height > minHeight && height < maxHeight && !canExpand) {
inner.height('auto');
}
},
_getPosition: function (onlyAbsolute) {
var current = F.current,
viewport = F.getViewport(),
margin = current.margin,
width = F.wrap.width() + margin[1] + margin[3],
height = F.wrap.height() + margin[0] + margin[2],
rez = {
position: 'absolute',
top : margin[0],
left : margin[3]
};
if (current.autoCenter && current.fixed && !onlyAbsolute && height <= viewport.h && width <= viewport.w) {
rez.position = 'fixed';
} else if (!current.locked) {
rez.top += viewport.y;
rez.left += viewport.x;
}
rez.top = getValue(Math.max(rez.top, rez.top + ((viewport.h - height) * current.topRatio)));
rez.left = getValue(Math.max(rez.left, rez.left + ((viewport.w - width) * current.leftRatio)));
return rez;
},
_afterZoomIn: function () {
var current = F.current;
if (!current) {
return;
}
F.isOpen = F.isOpened = true;
F.wrap.css('overflow', 'visible').addClass('fancybox-opened');
F.update();
// Assign a click event
if ( current.closeClick || (current.nextClick && F.group.length > 1) ) {
F.inner.css('cursor', 'pointer').bind('click.fb', function(e) {
if (!$(e.target).is('a') && !$(e.target).parent().is('a')) {
e.preventDefault();
F[ current.closeClick ? 'close' : 'next' ]();
}
});
}
// Create a close button
if (current.closeBtn) {
$(current.tpl.closeBtn).appendTo(F.skin).bind( isTouch ? 'touchstart.fb' : 'click.fb', function(e) {
e.preventDefault();
F.close();
});
}
// Create navigation arrows
if (current.arrows && F.group.length > 1) {
if (current.loop || current.index > 0) {
$(current.tpl.prev).appendTo(F.outer).bind('click.fb', F.prev);
}
if (current.loop || current.index < F.group.length - 1) {
$(current.tpl.next).appendTo(F.outer).bind('click.fb', F.next);
}
}
F.trigger('afterShow');
// Stop the slideshow if this is the last item
if (!current.loop && current.index === current.group.length - 1) {
F.play( false );
} else if (F.opts.autoPlay && !F.player.isActive) {
F.opts.autoPlay = false;
F.play();
}
},
_afterZoomOut: function ( obj ) {
obj = obj || F.current;
$('.fancybox-wrap').trigger('onReset').remove();
$.extend(F, {
group : {},
opts : {},
router : false,
current : null,
isActive : false,
isOpened : false,
isOpen : false,
isClosing : false,
wrap : null,
skin : null,
outer : null,
inner : null
});
F.trigger('afterClose', obj);
}
});
/*
* Default transitions
*/
F.transitions = {
getOrigPosition: function () {
var current = F.current,
element = current.element,
orig = current.orig,
pos = {},
width = 50,
height = 50,
hPadding = current.hPadding,
wPadding = current.wPadding,
viewport = F.getViewport();
if (!orig && current.isDom && element.is(':visible')) {
orig = element.find('img:first');
if (!orig.length) {
orig = element;
}
}
if (isQuery(orig)) {
pos = orig.offset();
if (orig.is('img')) {
width = orig.outerWidth();
height = orig.outerHeight();
}
} else {
pos.top = viewport.y + (viewport.h - height) * current.topRatio;
pos.left = viewport.x + (viewport.w - width) * current.leftRatio;
}
if (F.wrap.css('position') === 'fixed' || current.locked) {
pos.top -= viewport.y;
pos.left -= viewport.x;
}
pos = {
top : getValue(pos.top - hPadding * current.topRatio),
left : getValue(pos.left - wPadding * current.leftRatio),
width : getValue(width + wPadding),
height : getValue(height + hPadding)
};
return pos;
},
step: function (now, fx) {
var ratio,
padding,
value,
prop = fx.prop,
current = F.current,
wrapSpace = current.wrapSpace,
skinSpace = current.skinSpace;
if (prop === 'width' || prop === 'height') {
ratio = fx.end === fx.start ? 1 : (now - fx.start) / (fx.end - fx.start);
if (F.isClosing) {
ratio = 1 - ratio;
}
padding = prop === 'width' ? current.wPadding : current.hPadding;
value = now - padding;
F.skin[ prop ]( getScalar( prop === 'width' ? value : value - (wrapSpace * ratio) ) );
F.inner[ prop ]( getScalar( prop === 'width' ? value : value - (wrapSpace * ratio) - (skinSpace * ratio) ) );
}
},
zoomIn: function () {
var current = F.current,
startPos = current.pos,
effect = current.openEffect,
elastic = effect === 'elastic',
endPos = $.extend({opacity : 1}, startPos);
// Remove "position" property that breaks older IE
delete endPos.position;
if (elastic) {
startPos = this.getOrigPosition();
if (current.openOpacity) {
startPos.opacity = 0.1;
}
} else if (effect === 'fade') {
startPos.opacity = 0.1;
}
F.wrap.css(startPos).animate(endPos, {
duration : effect === 'none' ? 0 : current.openSpeed,
easing : current.openEasing,
step : elastic ? this.step : null,
complete : F._afterZoomIn
});
},
zoomOut: function () {
var current = F.current,
effect = current.closeEffect,
elastic = effect === 'elastic',
endPos = {opacity : 0.1};
if (elastic) {
endPos = this.getOrigPosition();
if (current.closeOpacity) {
endPos.opacity = 0.1;
}
}
F.wrap.animate(endPos, {
duration : effect === 'none' ? 0 : current.closeSpeed,
easing : current.closeEasing,
step : elastic ? this.step : null,
complete : F._afterZoomOut
});
},
changeIn: function () {
var current = F.current,
effect = current.nextEffect,
startPos = current.pos,
endPos = { opacity : 1 },
direction = F.direction,
distance = 200,
field;
startPos.opacity = 0.1;
if (effect === 'elastic') {
field = direction === 'down' || direction === 'up' ? 'top' : 'left';
if (direction === 'down' || direction === 'right') {
startPos[ field ] = getValue(getScalar(startPos[ field ]) - distance);
endPos[ field ] = '+=' + distance + 'px';
} else {
startPos[ field ] = getValue(getScalar(startPos[ field ]) + distance);
endPos[ field ] = '-=' + distance + 'px';
}
}
// Workaround for https://bugs.jquery.com/ticket/12273
if (effect === 'none') {
F._afterZoomIn();
} else {
F.wrap.css(startPos).animate(endPos, {
duration : current.nextSpeed,
easing : current.nextEasing,
complete : function() {
// This helps FireFox to properly render the box
setTimeout(F._afterZoomIn, 20);
}
});
}
},
changeOut: function () {
var previous = F.previous,
effect = previous.prevEffect,
endPos = { opacity : 0.1 },
direction = F.direction,
distance = 200;
if (effect === 'elastic') {
endPos[ direction === 'down' || direction === 'up' ? 'top' : 'left' ] = ( direction === 'up' || direction === 'left' ? '-' : '+' ) + '=' + distance + 'px';
}
previous.wrap.animate(endPos, {
duration : effect === 'none' ? 0 : previous.prevSpeed,
easing : previous.prevEasing,
complete : function () {
$(this).trigger('onReset').remove();
}
});
}
};
/*
* Overlay helper
*/
F.helpers.overlay = {
defaults : {
closeClick : true, // if true, fancyBox will be closed when user clicks on the overlay
speedOut : 200, // duration of fadeOut animation
showEarly : true, // indicates if should be opened immediately or wait until the content is ready
css : {}, // custom CSS properties
locked : !isTouch, // if true, the content will be locked into overlay
fixed : true // if false, the overlay CSS position property will not be set to "fixed"
},
overlay : null, // current handle
fixed : false, // indicates if the overlay has position "fixed"
// Public methods
create : function(opts) {
opts = $.extend({}, this.defaults, opts);
if (this.overlay) {
this.close();
}
this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( 'body' );
this.fixed = false;
if (opts.fixed && F.defaults.fixed) {
this.overlay.addClass('fancybox-overlay-fixed');
this.fixed = true;
}
},
open : function(opts) {
var that = this;
opts = $.extend({}, this.defaults, opts);
if (this.overlay) {
this.overlay.unbind('.overlay').width('auto').height('auto');
} else {
this.create(opts);
}
if (!this.fixed) {
W.bind('resize.overlay', $.proxy( this.update, this) );
this.update();
}
if (opts.closeClick) {
this.overlay.bind('click.overlay', function(e) {
if ($(e.target).hasClass('fancybox-overlay')) {
if (F.isActive) {
F.close();
} else {
that.close();
}
}
});
}
this.overlay.css( opts.css ).show();
},
close : function() {
$('.fancybox-overlay').remove();
W.unbind('resize.overlay');
this.overlay = null;
if (this.margin !== false) {
$('body').css('margin-right', this.margin);
this.margin = false;
}
if (this.el) {
this.el.removeClass('fancybox-lock');
}
},
// Private, callbacks
update : function () {
var width = '100%', offsetWidth;
// Reset width/height so it will not mess
this.overlay.width(width).height('100%');
// jQuery does not return reliable result for IE
if ($.browser.msie) {
offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
if (D.width() > offsetWidth) {
width = D.width();
}
} else if (D.width() > W.width()) {
width = D.width();
}
this.overlay.width(width).height(D.height());
},
// This is where we can manipulate DOM, because later it would cause iframes to reload
onReady : function (opts, obj) {
$('.fancybox-overlay').stop(true, true);
if (!this.overlay) {
this.margin = D.height() > W.height() || $('body').css('overflow-y') === 'scroll' ? $('body').css('margin-right') : false;
this.el = document.all && !document.querySelector ? $('html') : $('body');
this.create(opts);
}
if (opts.locked && this.fixed) {
obj.locked = this.overlay.append( obj.wrap );
obj.fixed = false;
}
if (opts.showEarly === true) {
this.beforeShow.apply(this, arguments);
}
},
beforeShow : function(opts, obj) {
if (obj.locked) {
this.el.addClass('fancybox-lock');
if (this.margin !== false) {
$('body').css('margin-right', getScalar( this.margin ) + obj.scrollbarWidth);
}
}
this.open(opts);
},
onUpdate : function() {
if (!this.fixed) {
this.update();
}
},
afterClose: function (opts) {
// Remove overlay if exists and fancyBox is not opening
// (e.g., it is not being open using afterClose callback)
if (this.overlay && !F.isActive) {
this.overlay.fadeOut(opts.speedOut, $.proxy( this.close, this ));
}
}
};
/*
* Title helper
*/
F.helpers.title = {
defaults : {
type : 'float', // 'float', 'inside', 'outside' or 'over',
position : 'bottom' // 'top' or 'bottom'
},
beforeShow: function (opts) {
var current = F.current,
text = current.title,
type = opts.type,
title,
target;
if ($.isFunction(text)) {
text = text.call(current.element, current);
}
if (!isString(text) || $.trim(text) === '') {
return;
}
title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap">' + text + '</div>');
switch (type) {
case 'inside':
target = F.skin;
break;
case 'outside':
target = F.wrap;
break;
case 'over':
target = F.inner;
break;
default: // 'float'
target = F.skin;
title.appendTo('body');
if ($.browser.msie) {
title.width( title.width() );
}
title.wrapInner('<span class="child"></span>');
//Increase bottom margin so this title will also fit into viewport
F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) );
break;
}
title[ (opts.position === 'top' ? 'prependTo' : 'appendTo') ](target);
}
};
// jQuery plugin initialization
$.fn.fancybox = function (options) {
var index,
that = $(this),
selector = this.selector || '',
run = function(e) {
var what = $(this).blur(), idx = index, relType, relVal;
if (!(e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) && !what.is('.fancybox-wrap')) {
relType = options.groupAttr || 'data-fancybox-group';
relVal = what.attr(relType);
if (!relVal) {
relType = 'rel';
relVal = what.get(0)[ relType ];
}
if (relVal && relVal !== '' && relVal !== 'nofollow') {
what = selector.length ? $(selector) : that;
what = what.filter('[' + relType + '="' + relVal + '"]');
idx = what.index(this);
}
options.index = idx;
// Stop an event from bubbling if everything is fine
if (F.open(what, options) !== false) {
e.preventDefault();
}
}
};
options = options || {};
index = options.index || 0;
if (!selector || options.live === false) {
that.unbind('click.fb-start').bind('click.fb-start', run);
} else {
D.undelegate(selector, 'click.fb-start').delegate(selector + ":not('.fancybox-item, .fancybox-nav')", 'click.fb-start', run);
}
this.filter('[data-fancybox-start=1]').trigger('click');
return this;
};
// Tests that need a body at doc ready
D.ready(function() {
if ( $.scrollbarWidth === undefined ) {
// https://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth
$.scrollbarWidth = function() {
var parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'),
child = parent.children(),
width = child.innerWidth() - child.height( 99 ).innerWidth();
parent.remove();
return width;
};
}
if ( $.support.fixedPosition === undefined ) {
$.support.fixedPosition = (function() {
var elem = $('<div style="position:fixed;top:20px;"></div>').appendTo('body'),
fixed = ( elem[0].offsetTop === 20 || elem[0].offsetTop === 15 );
elem.remove();
return fixed;
}());
}
$.extend(F.defaults, {
scrollbarWidth : $.scrollbarWidth(),
fixed : $.support.fixedPosition,
parent : $('body')
});
});
}(window, document, jQuery)); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.