webpackJsonp([1],[
/* 0 */,
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, setImmediate) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EVENT_ABORT = exports.TYPED_ARRAYS = exports.VOID = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.setLoggerFunction = setLoggerFunction;
exports.vtkLogMacro = vtkLogMacro;
exports.vtkInfoMacro = vtkInfoMacro;
exports.vtkDebugMacro = vtkDebugMacro;
exports.vtkErrorMacro = vtkErrorMacro;
exports.vtkWarningMacro = vtkWarningMacro;
exports.vtkOnceErrorMacro = vtkOnceErrorMacro;
exports.capitalize = capitalize;
exports.uncapitalize = uncapitalize;
exports.formatBytesToProperUnit = formatBytesToProperUnit;
exports.formatNumbersWithThousandSeparator = formatNumbersWithThousandSeparator;
exports.obj = obj;
exports.get = get;
exports.set = set;
exports.setGet = setGet;
exports.getArray = getArray;
exports.setArray = setArray;
exports.setGetArray = setGetArray;
exports.algo = algo;
exports.event = event;
exports.newInstance = newInstance;
exports.chain = chain;
exports.isVtkObject = isVtkObject;
exports.traverseInstanceTree = traverseInstanceTree;
exports.debounce = debounce;
exports.throttle = throttle;
exports.keystore = keystore;
exports.proxy = proxy;
exports.proxyPropertyMapping = proxyPropertyMapping;
exports.proxyPropertyState = proxyPropertyState;
exports.normalizeWheel = normalizeWheel;
var _vtk = __webpack_require__(63);
var _vtk2 = _interopRequireDefault(_vtk);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(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 globalMTime = 0;
var VOID = exports.VOID = Symbol('void');
function getCurrentGlobalMTime() {
return globalMTime;
}
// ----------------------------------------------------------------------------
// Logging function calls
// ----------------------------------------------------------------------------
/* eslint-disable no-prototype-builtins */
var fakeConsole = {};
function noOp() {}
var consoleMethods = ['log', 'debug', 'info', 'warn', 'error', 'time', 'timeEnd', 'group', 'groupEnd'];
consoleMethods.forEach(function (methodName) {
fakeConsole[methodName] = noOp;
});
global.console = console.hasOwnProperty('log') ? console : fakeConsole;
var loggerFunctions = {
debug: noOp, // Don't print debug by default
error: global.console.error || noOp,
info: global.console.info || noOp,
log: global.console.log || noOp,
warn: global.console.warn || noOp
};
function setLoggerFunction(name, fn) {
if (loggerFunctions[name]) {
loggerFunctions[name] = fn || noOp;
}
}
function vtkLogMacro() {
loggerFunctions.log.apply(loggerFunctions, arguments);
}
function vtkInfoMacro() {
loggerFunctions.info.apply(loggerFunctions, arguments);
}
function vtkDebugMacro() {
loggerFunctions.debug.apply(loggerFunctions, arguments);
}
function vtkErrorMacro() {
loggerFunctions.error.apply(loggerFunctions, arguments);
}
function vtkWarningMacro() {
loggerFunctions.warn.apply(loggerFunctions, arguments);
}
var ERROR_ONCE_MAP = {};
function vtkOnceErrorMacro(str) {
if (!ERROR_ONCE_MAP[str]) {
loggerFunctions.error(str);
ERROR_ONCE_MAP[str] = true;
}
}
// ----------------------------------------------------------------------------
// TypedArray
// ----------------------------------------------------------------------------
var TYPED_ARRAYS = exports.TYPED_ARRAYS = {
Float32Array: Float32Array,
Float64Array: Float64Array,
Uint8Array: Uint8Array,
Int8Array: Int8Array,
Uint16Array: Uint16Array,
Int16Array: Int16Array,
Uint32Array: Uint32Array,
Int32Array: Int32Array
};
// ----------------------------------------------------------------------------
// capitilze provided string
// ----------------------------------------------------------------------------
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function uncapitalize(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
// ----------------------------------------------------------------------------
// Convert byte size into a well formatted string
// ----------------------------------------------------------------------------
function formatBytesToProperUnit(size) {
var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var chunkSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000;
var units = ['TB', 'GB', 'MB', 'KB'];
var value = Number(size);
var currentUnit = 'B';
while (value > chunkSize) {
value /= chunkSize;
currentUnit = units.pop();
}
return value.toFixed(precision) + ' ' + currentUnit;
}
// ----------------------------------------------------------------------------
// Convert thousand number with proper seperator
// ----------------------------------------------------------------------------
function formatNumbersWithThousandSeparator(n) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' ';
var sections = [];
var size = n;
while (size > 1000) {
sections.push(('000' + size % 1000).slice(-3));
size = Math.floor(size / 1000);
}
if (size > 0) {
sections.push(size);
}
sections.reverse();
return sections.join(separator);
}
// ----------------------------------------------------------------------------
// Array helper
// ----------------------------------------------------------------------------
function safeArrays(model) {
Object.keys(model).forEach(function (key) {
if (Array.isArray(model[key])) {
model[key] = [].concat(model[key]);
}
});
}
// ----------------------------------------------------------------------------
function enumToString(e, value) {
return Object.keys(e).find(function (key) {
return e[key] === value;
});
}
function getStateArrayMapFunc(item) {
if (item.isA) {
return item.getState();
}
return item;
}
// ----------------------------------------------------------------------------
// vtkObject: modified(), onModified(callback), delete()
// ----------------------------------------------------------------------------
function obj() {
var publicAPI = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var model = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// Ensure each instance as a unique ref of array
safeArrays(model);
var callbacks = [];
if (!Number.isInteger(model.mtime)) {
model.mtime = ++globalMTime;
}
model.classHierarchy = ['vtkObject'];
function off(index) {
callbacks[index] = null;
}
function on(index) {
function unsubscribe() {
off(index);
}
return Object.freeze({
unsubscribe: unsubscribe
});
}
publicAPI.isDeleted = function () {
return !!model.deleted;
};
publicAPI.modified = function (otherMTime) {
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
if (otherMTime && otherMTime < publicAPI.getMTime()) {
return;
}
model.mtime = ++globalMTime;
callbacks.forEach(function (callback) {
return callback && callback(publicAPI);
});
};
publicAPI.onModified = function (callback) {
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return null;
}
var index = callbacks.length;
callbacks.push(callback);
return on(index);
};
publicAPI.getMTime = function () {
return model.mtime;
};
publicAPI.isA = function (className) {
var count = model.classHierarchy.length;
// we go backwards as that is more likely for
// early termination
while (count--) {
if (model.classHierarchy[count] === className) {
return true;
}
}
return false;
};
publicAPI.getClassName = function () {
var depth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return model.classHierarchy[model.classHierarchy.length - 1 - depth];
};
publicAPI.set = function () {
var map = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var noWarning = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var noFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var ret = false;
Object.keys(map).forEach(function (name) {
var fn = noFunction ? null : publicAPI['set' + capitalize(name)];
if (fn && Array.isArray(map[name]) && fn.length > 1) {
ret = fn.apply(undefined, _toConsumableArray(map[name])) || ret;
} else if (fn) {
ret = fn(map[name]) || ret;
} else {
// Set data on model directly
if (['mtime'].indexOf(name) === -1 && !noWarning) {
vtkWarningMacro('Warning: Set value to model directly ' + name + ', ' + map[name]);
}
model[name] = map[name];
ret = true;
}
});
return ret;
};
publicAPI.get = function () {
for (var _len = arguments.length, list = Array(_len), _key = 0; _key < _len; _key++) {
list[_key] = arguments[_key];
}
if (!list.length) {
return model;
}
var subset = {};
list.forEach(function (name) {
subset[name] = model[name];
});
return subset;
};
publicAPI.getReferenceByName = function (val) {
return model[val];
};
publicAPI.delete = function () {
Object.keys(model).forEach(function (field) {
return delete model[field];
});
callbacks.forEach(function (el, index) {
return off(index);
});
// Flag the instance being deleted
model.deleted = true;
};
// Add serialization support
publicAPI.getState = function () {
var jsonArchive = Object.assign({}, model, {
vtkClass: publicAPI.getClassName()
});
// Convert every vtkObject to its serializable form
Object.keys(jsonArchive).forEach(function (keyName) {
if (jsonArchive[keyName] === null || jsonArchive[keyName] === undefined) {
delete jsonArchive[keyName];
} else if (jsonArchive[keyName].isA) {
jsonArchive[keyName] = jsonArchive[keyName].getState();
} else if (Array.isArray(jsonArchive[keyName])) {
jsonArchive[keyName] = jsonArchive[keyName].map(getStateArrayMapFunc);
}
});
// Sort resulting object by key name
var sortedObj = {};
Object.keys(jsonArchive).sort().forEach(function (name) {
sortedObj[name] = jsonArchive[name];
});
// Remove mtime
if (sortedObj.mtime) {
delete sortedObj.mtime;
}
return sortedObj;
};
// Add shallowCopy(otherInstance) support
publicAPI.shallowCopy = function (other) {
var debug = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (other.getClassName() !== publicAPI.getClassName()) {
throw new Error('Cannot ShallowCopy ' + other.getClassName() + ' into ' + publicAPI.getClassName());
}
var otherModel = other.get();
var keyList = Object.keys(model).sort();
var otherKeyList = Object.keys(otherModel).sort();
otherKeyList.forEach(function (key) {
var keyIdx = keyList.indexOf(key);
if (keyIdx === -1) {
if (debug) {
vtkDebugMacro('add ' + key + ' in shallowCopy');
}
} else {
keyList.splice(keyIdx, 1);
}
model[key] = otherModel[key];
});
if (keyList.length && debug) {
vtkDebugMacro('Untouched keys: ' + keyList.join(', '));
}
publicAPI.modified();
};
// Allow usage as decorator
return publicAPI;
}
// ----------------------------------------------------------------------------
// getXXX: add getters
// ----------------------------------------------------------------------------
function get(publicAPI, model, fieldNames) {
fieldNames.forEach(function (field) {
if ((typeof field === 'undefined' ? 'undefined' : _typeof(field)) === 'object') {
publicAPI['get' + capitalize(field.name)] = function () {
return model[field.name];
};
} else {
publicAPI['get' + capitalize(field)] = function () {
return model[field];
};
}
});
}
// ----------------------------------------------------------------------------
// setXXX: add setters
// ----------------------------------------------------------------------------
var objectSetterMap = {
enum: function _enum(publicAPI, model, field) {
return function (value) {
if (typeof value === 'string') {
if (field.enum[value] !== undefined) {
if (model[field.name] !== field.enum[value]) {
model[field.name] = field.enum[value];
publicAPI.modified();
return true;
}
return false;
}
vtkErrorMacro('Set Enum with invalid argument ' + field + ', ' + value);
throw new RangeError('Set Enum with invalid string argument');
}
if (typeof value === 'number') {
if (model[field.name] !== value) {
if (Object.keys(field.enum).map(function (key) {
return field.enum[key];
}).indexOf(value) !== -1) {
model[field.name] = value;
publicAPI.modified();
return true;
}
vtkErrorMacro('Set Enum outside numeric range ' + field + ', ' + value);
throw new RangeError('Set Enum outside numeric range');
}
return false;
}
vtkErrorMacro('Set Enum with invalid argument (String/Number) ' + field + ', ' + value);
throw new TypeError('Set Enum with invalid argument (String/Number)');
};
}
};
function findSetter(field) {
if ((typeof field === 'undefined' ? 'undefined' : _typeof(field)) === 'object') {
var fn = objectSetterMap[field.type];
if (fn) {
return function (publicAPI, model) {
return fn(publicAPI, model, field);
};
}
vtkErrorMacro('No setter for field ' + field);
throw new TypeError('No setter for field');
}
return function getSetter(publicAPI, model) {
return function setter(value) {
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return false;
}
if (model[field] !== value) {
model[field] = value;
publicAPI.modified();
return true;
}
return false;
};
};
}
function set(publicAPI, model, fields) {
fields.forEach(function (field) {
if ((typeof field === 'undefined' ? 'undefined' : _typeof(field)) === 'object') {
publicAPI['set' + capitalize(field.name)] = findSetter(field)(publicAPI, model);
} else {
publicAPI['set' + capitalize(field)] = findSetter(field)(publicAPI, model);
}
});
}
// ----------------------------------------------------------------------------
// set/get XXX: add both setters and getters
// ----------------------------------------------------------------------------
function setGet(publicAPI, model, fieldNames) {
get(publicAPI, model, fieldNames);
set(publicAPI, model, fieldNames);
}
// ----------------------------------------------------------------------------
// getXXX: add getters for object of type array with copy to be safe
// getXXXByReference: add getters for object of type array without copy
// ----------------------------------------------------------------------------
function getArray(publicAPI, model, fieldNames) {
fieldNames.forEach(function (field) {
publicAPI['get' + capitalize(field)] = function () {
return [].concat(model[field]);
};
publicAPI['get' + capitalize(field) + 'ByReference'] = function () {
return model[field];
};
});
}
// ----------------------------------------------------------------------------
// setXXX: add setter for object of type array
// if 'defaultVal' is supplied, shorter arrays will be padded to 'size' with 'defaultVal'
// set...From: fast path to copy the content of an array to the current one without call to modified.
// ----------------------------------------------------------------------------
function setArray(publicAPI, model, fieldNames, size) {
var defaultVal = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined;
fieldNames.forEach(function (field) {
publicAPI['set' + capitalize(field)] = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return false;
}
var array = args;
// allow an array passed as a single arg.
if (array.length === 1 && Array.isArray(array[0])) {
/* eslint-disable prefer-destructuring */
array = array[0];
/* eslint-enable prefer-destructuring */
}
if (array.length !== size) {
if (array.length < size && defaultVal !== undefined) {
array = [].concat(array);
while (array.length < size) {
array.push(defaultVal);
}
} else {
throw new RangeError('Invalid number of values for array setter');
}
}
var changeDetected = false;
model[field].forEach(function (item, index) {
if (item !== array[index]) {
if (changeDetected) {
return;
}
changeDetected = true;
}
});
if (changeDetected || model[field].length !== array.length) {
model[field] = [].concat(array);
publicAPI.modified();
}
return true;
};
publicAPI['set' + capitalize(field) + 'From'] = function (otherArray) {
var target = model[field];
otherArray.forEach(function (v, i) {
target[i] = v;
});
};
});
}
// ----------------------------------------------------------------------------
// set/get XXX: add setter and getter for object of type array
// ----------------------------------------------------------------------------
function setGetArray(publicAPI, model, fieldNames, size) {
var defaultVal = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined;
getArray(publicAPI, model, fieldNames);
setArray(publicAPI, model, fieldNames, size, defaultVal);
}
// ----------------------------------------------------------------------------
// vtkAlgorithm: setInputData(), setInputConnection(), getOutputData(), getOutputPort()
// ----------------------------------------------------------------------------
function algo(publicAPI, model, numberOfInputs, numberOfOutputs) {
if (model.inputData) {
model.inputData = model.inputData.map(_vtk2.default);
} else {
model.inputData = [];
}
if (model.inputConnection) {
model.inputConnection = model.inputConnection.map(_vtk2.default);
} else {
model.inputConnection = [];
}
if (model.output) {
model.output = model.output.map(_vtk2.default);
} else {
model.output = [];
}
if (model.inputArrayToProcess) {
model.inputArrayToProcess = model.inputArrayToProcess.map(_vtk2.default);
} else {
model.inputArrayToProcess = [];
}
// Cache the argument for later manipulation
model.numberOfInputs = numberOfInputs;
// Methods
function setInputData(dataset) {
var port = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
if (port >= model.numberOfInputs) {
var msg = 'algorithm ' + publicAPI.getClassName() + ' only has ';
msg += '' + model.numberOfInputs;
msg += ' input ports. To add more input ports, use addInputData()';
vtkErrorMacro(msg);
return;
}
if (model.inputData[port] !== dataset || model.inputConnection[port]) {
model.inputData[port] = dataset;
model.inputConnection[port] = null;
if (publicAPI.modified) {
publicAPI.modified();
}
}
}
function getInputData() {
var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
if (model.inputConnection[port]) {
model.inputData[port] = model.inputConnection[port]();
}
return model.inputData[port];
}
function setInputConnection(outputPort) {
var port = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
if (port >= model.numberOfInputs) {
var msg = 'algorithm ' + publicAPI.getClassName() + ' only has ';
msg += '' + model.numberOfInputs;
msg += ' input ports. To add more input ports, use addInputConnection()';
vtkErrorMacro(msg);
return;
}
model.inputData[port] = null;
model.inputConnection[port] = outputPort;
}
function getInputConnection() {
var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return model.inputConnection[port];
}
function addInputConnection(outputPort) {
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
model.numberOfInputs++;
setInputConnection(outputPort, model.numberOfInputs - 1);
}
function addInputData(dataset) {
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
model.numberOfInputs++;
setInputData(dataset, model.numberOfInputs - 1);
}
function getOutputData() {
var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return null;
}
if (publicAPI.shouldUpdate()) {
publicAPI.update();
}
return model.output[port];
}
publicAPI.shouldUpdate = function () {
var localMTime = publicAPI.getMTime();
var count = numberOfOutputs;
var minOutputMTime = Infinity;
while (count--) {
if (!model.output[count]) {
return true;
}
var mt = model.output[count].getMTime();
if (mt < localMTime) {
return true;
}
if (mt < minOutputMTime) {
minOutputMTime = mt;
}
}
count = model.numberOfInputs;
while (count--) {
if (model.inputConnection[count] && model.inputConnection[count].filter.shouldUpdate()) {
return true;
}
}
count = model.numberOfInputs;
while (count--) {
if (publicAPI.getInputData(count) && publicAPI.getInputData(count).getMTime() > minOutputMTime) {
return true;
}
}
return false;
};
function getOutputPort() {
var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var outputPortAccess = function outputPortAccess() {
return getOutputData(port);
};
// Add reference to filter
outputPortAccess.filter = publicAPI;
return outputPortAccess;
}
// Handle input if needed
if (model.numberOfInputs) {
// Reserve inputs
var count = model.numberOfInputs;
while (count--) {
model.inputData.push(null);
model.inputConnection.push(null);
}
// Expose public methods
publicAPI.setInputData = setInputData;
publicAPI.setInputConnection = setInputConnection;
publicAPI.addInputData = addInputData;
publicAPI.addInputConnection = addInputConnection;
publicAPI.getInputData = getInputData;
publicAPI.getInputConnection = getInputConnection;
}
if (numberOfOutputs) {
publicAPI.getOutputData = getOutputData;
publicAPI.getOutputPort = getOutputPort;
}
publicAPI.update = function () {
var ins = [];
if (model.numberOfInputs) {
var _count = 0;
while (_count < model.numberOfInputs) {
ins[_count] = publicAPI.getInputData(_count);
_count++;
}
}
if (publicAPI.shouldUpdate() && publicAPI.requestData) {
publicAPI.requestData(ins, model.output);
}
};
publicAPI.getNumberOfInputPorts = function () {
return model.numberOfInputs;
};
publicAPI.getNumberOfOutputPorts = function () {
return numberOfOutputs;
};
publicAPI.getInputArrayToProcess = function (inputPort) {
var arrayDesc = model.inputArrayToProcess[inputPort];
var ds = model.inputData[inputPort];
if (arrayDesc && ds) {
return ds['get' + arrayDesc.fieldAssociation]().getArray(arrayDesc.arrayName);
}
return null;
};
publicAPI.setInputArrayToProcess = function (inputPort, arrayName, fieldAssociation) {
var attributeType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'Scalars';
while (model.inputArrayToProcess.length < inputPort) {
model.inputArrayToProcess.push(null);
}
model.inputArrayToProcess[inputPort] = {
arrayName: arrayName,
fieldAssociation: fieldAssociation,
attributeType: attributeType
};
};
}
// ----------------------------------------------------------------------------
// Event handling: onXXX(callback), invokeXXX(args...)
// ----------------------------------------------------------------------------
var EVENT_ABORT = exports.EVENT_ABORT = Symbol('Event abort');
function event(publicAPI, model, eventName) {
var callbacks = [];
var previousDelete = publicAPI.delete;
var curCallbackID = 1;
function off(callbackID) {
for (var i = 0; i < callbacks.length; ++i) {
var _callbacks$i = _slicedToArray(callbacks[i], 1),
cbID = _callbacks$i[0];
if (cbID === callbackID) {
callbacks.splice(i, 1);
return;
}
}
}
function on(callbackID) {
function unsubscribe() {
off(callbackID);
}
return Object.freeze({
unsubscribe: unsubscribe
});
}
function invoke() {
var _arguments = arguments;
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
/* eslint-disable prefer-rest-params */
// Go through a copy of the callbacks array in case new callbacks
// get prepended within previous callbacks
var currentCallbacks = callbacks.slice();
var _loop = function _loop(index) {
var _currentCallbacks$ind = _slicedToArray(currentCallbacks[index], 3),
cb = _currentCallbacks$ind[1],
priority = _currentCallbacks$ind[2];
if (priority < 0) {
setTimeout(function () {
return cb.apply(publicAPI, _arguments);
}, 1 - priority);
} else if (cb) {
// Abort only if the callback explicitly returns false
var continueNext = cb.apply(publicAPI, _arguments);
if (continueNext === EVENT_ABORT) {
return 'break';
}
}
};
for (var index = 0; index < currentCallbacks.length; ++index) {
var _ret = _loop(index);
if (_ret === 'break') break;
}
/* eslint-enable prefer-rest-params */
}
publicAPI['invoke' + capitalize(eventName)] = invoke;
publicAPI['on' + capitalize(eventName)] = function (callback) {
var priority = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.0;
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return null;
}
var callbackID = curCallbackID++;
callbacks.push([callbackID, callback, priority]);
callbacks.sort(function (cb1, cb2) {
return cb2[2] - cb1[2];
});
return on(callbackID);
};
publicAPI.delete = function () {
previousDelete();
callbacks.forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
cbID = _ref2[0];
return off(cbID);
});
};
}
// ----------------------------------------------------------------------------
// newInstance
// ----------------------------------------------------------------------------
function newInstance(extend, className) {
var constructor = function constructor() {
var initialValues = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var model = {};
var publicAPI = {};
extend(publicAPI, model, initialValues);
return Object.freeze(publicAPI);
};
// Register constructor to factory
if (className) {
_vtk2.default.register(className, constructor);
}
return constructor;
}
// ----------------------------------------------------------------------------
// Chain function calls
// ----------------------------------------------------------------------------
function chain() {
for (var _len3 = arguments.length, fn = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
fn[_key3] = arguments[_key3];
}
return function () {
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return fn.filter(function (i) {
return !!i;
}).forEach(function (i) {
return i.apply(undefined, args);
});
};
}
// ----------------------------------------------------------------------------
// Some utility methods for vtk objects
// ----------------------------------------------------------------------------
function isVtkObject(instance) {
return instance && instance.isA && instance.isA('vtkObject');
}
function traverseInstanceTree(instance, extractFunction) {
var accumulator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var visitedInstances = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
if (isVtkObject(instance)) {
if (visitedInstances.indexOf(instance) >= 0) {
// avoid cycles
return accumulator;
}
visitedInstances.push(instance);
var result = extractFunction(instance);
if (result !== undefined) {
accumulator.push(result);
}
// Now go through this instance's model
var model = instance.get();
Object.keys(model).forEach(function (key) {
var modelObj = model[key];
if (Array.isArray(modelObj)) {
modelObj.forEach(function (subObj) {
traverseInstanceTree(subObj, extractFunction, accumulator, visitedInstances);
});
} else {
traverseInstanceTree(modelObj, extractFunction, accumulator, visitedInstances);
}
});
}
return accumulator;
}
// ----------------------------------------------------------------------------
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var _this = this;
var timeout = void 0;
return function () {
for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
var context = _this;
var later = function later() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
// ----------------------------------------------------------------------------
// Creates a throttled function that only invokes `func` at most once per
// every `wait` milliseconds.
function throttle(callback, delay) {
var isThrottled = false;
var argsToUse = null;
function next() {
isThrottled = false;
if (argsToUse !== null) {
wrapper.apply(undefined, _toConsumableArray(argsToUse)); // eslint-disable-line
argsToUse = null;
}
}
function wrapper() {
for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
if (isThrottled) {
argsToUse = args;
return;
}
isThrottled = true;
callback.apply(undefined, args);
setTimeout(next, delay);
}
return wrapper;
}
// ----------------------------------------------------------------------------
// keystore(publicAPI, model, initialKeystore)
//
// - initialKeystore: Initial keystore. This can be either a Map or an
// object.
//
// Generated API
// setKey(key, value) : mixed (returns value)
// getKey(key) : mixed
// getAllKeys() : [mixed]
// deleteKey(key) : Boolean
// ----------------------------------------------------------------------------
function keystore(publicAPI, model) {
var initialKeystore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
model.keystore = Object.assign(model.keystore || {}, initialKeystore);
publicAPI.setKey = function (key, value) {
model.keystore[key] = value;
};
publicAPI.getKey = function (key, value) {
return model.keystore[key];
};
publicAPI.getAllKeys = function (key, value) {
return Object.keys(model.keystore);
};
publicAPI.deleteKey = function (key, value) {
return delete model.keystore[key];
};
publicAPI.clearKeystore = function () {
return publicAPI.getAllKeys().forEach(function (key) {
return delete model.keystore[key];
});
};
}
// ----------------------------------------------------------------------------
// proxy(publicAPI, model, sectionName, propertyUI)
//
// - sectionName: Name of the section for UI
// - propertyUI: List of props with their UI description
//
// Generated API
// getProxyId() : String
// listProxyProperties() : [string]
// updateProxyProperty(name, prop)
// getProxySection() => List of properties for UI generation
// ----------------------------------------------------------------------------
var nextProxyId = 1;
var ROOT_GROUP_NAME = '__root__';
function proxy(publicAPI, model) {
// Proxies are keystores
keystore(publicAPI, model);
var parentDelete = publicAPI.delete;
// getProxyId
model.proxyId = '' + nextProxyId++;
// ui handling
model.ui = JSON.parse(JSON.stringify(model.ui || [])); // deep copy
get(publicAPI, model, ['proxyId', 'proxyGroup', 'proxyName']);
setGet(publicAPI, model, ['proxyManager']);
// group properties
var propertyMap = {};
var groupChildrenNames = {};
function registerProperties(descriptionList, currentGroupName) {
if (!groupChildrenNames[currentGroupName]) {
groupChildrenNames[currentGroupName] = [];
}
var childrenNames = groupChildrenNames[currentGroupName];
for (var i = 0; i < descriptionList.length; i++) {
childrenNames.push(descriptionList[i].name);
propertyMap[descriptionList[i].name] = descriptionList[i];
if (descriptionList[i].children && descriptionList[i].children.length) {
registerProperties(descriptionList[i].children, descriptionList[i].name);
}
}
}
registerProperties(model.ui, ROOT_GROUP_NAME);
publicAPI.updateUI = function (ui) {
model.ui = JSON.parse(JSON.stringify(ui || [])); // deep copy
Object.keys(propertyMap).forEach(function (k) {
return delete propertyMap[k];
});
Object.keys(groupChildrenNames).forEach(function (k) {
return delete groupChildrenNames[k];
});
registerProperties(model.ui, ROOT_GROUP_NAME);
publicAPI.modified();
};
function listProxyProperties() {
var gName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ROOT_GROUP_NAME;
return groupChildrenNames[gName];
}
publicAPI.updateProxyProperty = function (propertyName, propUI) {
var prop = propertyMap[propertyName];
if (prop) {
Object.assign(prop, propUI);
} else {
propertyMap[propertyName] = Object.assign({}, propUI);
}
};
publicAPI.activate = function () {
if (model.proxyManager) {
var setActiveMethod = 'setActive' + capitalize(publicAPI.getProxyGroup().slice(0, -1));
if (model.proxyManager[setActiveMethod]) {
model.proxyManager[setActiveMethod](publicAPI);
}
}
};
// property link
model.propertyLinkSubscribers = {};
publicAPI.registerPropertyLinkForGC = function (otherLink, type) {
if (!(type in model.propertyLinkSubscribers)) {
model.propertyLinkSubscribers[type] = [];
}
model.propertyLinkSubscribers[type].push(otherLink);
};
publicAPI.gcPropertyLinks = function (type) {
var subscribers = model.propertyLinkSubscribers[type] || [];
while (subscribers.length) {
subscribers.pop().unbind(publicAPI);
}
};
model.propertyLinkMap = {};
publicAPI.getPropertyLink = function (id) {
var persistent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (model.propertyLinkMap[id]) {
return model.propertyLinkMap[id];
}
var value = null;
var links = [];
var count = 0;
var updateInProgress = false;
function update(source) {
var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (updateInProgress) {
return null;
}
var needUpdate = [];
var sourceLink = null;
count = links.length;
while (count--) {
var link = links[count];
if (link.instance === source) {
sourceLink = link;
} else {
needUpdate.push(link);
}
}
if (!sourceLink) {
return null;
}
var newValue = sourceLink.instance['get' + capitalize(sourceLink.propertyName)]();
if (newValue !== value || force) {
value = newValue;
updateInProgress = true;
while (needUpdate.length) {
var linkToUpdate = needUpdate.pop();
linkToUpdate.instance.set(_defineProperty({}, linkToUpdate.propertyName, value));
}
updateInProgress = false;
}
if (model.propertyLinkMap[id].persistent) {
model.propertyLinkMap[id].value = newValue;
}
return newValue;
}
function unbind(instance, propertyName) {
var indexToDelete = [];
count = links.length;
while (count--) {
var link = links[count];
if (link.instance === instance && (link.propertyName === propertyName || propertyName === undefined)) {
link.subscription.unsubscribe();
indexToDelete.push(count);
}
}
while (indexToDelete.length) {
links.splice(indexToDelete.pop(), 1);
}
}
function bind(instance, propertyName) {
var updateMe = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var subscription = instance.onModified(update);
var other = links[0];
links.push({
instance: instance,
propertyName: propertyName,
subscription: subscription
});
if (updateMe) {
if (model.propertyLinkMap[id].persistent && model.propertyLinkMap[id].value !== undefined) {
instance.set(_defineProperty({}, propertyName, model.propertyLinkMap[id].value));
} else if (other) {
update(other.instance, true);
}
}
return {
unsubscribe: function unsubscribe() {
return unbind(instance, propertyName);
}
};
}
function unsubscribe() {
while (links.length) {
links.pop().subscription.unsubscribe();
}
}
var linkHandler = {
bind: bind,
unbind: unbind,
unsubscribe: unsubscribe,
persistent: persistent
};
model.propertyLinkMap[id] = linkHandler;
return linkHandler;
};
// extract values
function getProperties() {
var groupName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ROOT_GROUP_NAME;
var values = [];
var id = model.proxyId;
var propertyNames = listProxyProperties(groupName) || [];
for (var i = 0; i < propertyNames.length; i++) {
var name = propertyNames[i];
var method = publicAPI['get' + capitalize(name)];
var value = method ? method() : undefined;
var prop = {
id: id,
name: name,
value: value
};
var children = getProperties(name);
if (children.length) {
prop.children = children;
}
values.push(prop);
}
return values;
}
publicAPI.listPropertyNames = function () {
return getProperties().map(function (p) {
return p.name;
});
};
publicAPI.getPropertyByName = function (name) {
return getProperties().find(function (p) {
return p.name === name;
});
};
publicAPI.getPropertyDomainByName = function (name) {
return propertyMap[name].domain;
};
// ui section
publicAPI.getProxySection = function () {
return {
id: model.proxyId,
name: model.proxyGroup,
ui: model.ui,
properties: getProperties()
};
};
// free resources
publicAPI.delete = function () {
var list = Object.keys(model.propertyLinkMap);
var count = list.length;
while (count--) {
model.propertyLinkMap[list[count]].unsubscribe();
}
Object.keys(model.propertyLinkSubscribers).forEach(publicAPI.gcPropertyLinks);
parentDelete();
};
function registerLinks() {
// Allow dynamic registration of links at the application level
if (model.links) {
for (var i = 0; i < model.links.length; i++) {
var _model$links$i = model.links[i],
link = _model$links$i.link,
property = _model$links$i.property,
persistent = _model$links$i.persistent,
updateOnBind = _model$links$i.updateOnBind,
type = _model$links$i.type;
if (type === 'application') {
var sLink = model.proxyManager.getPropertyLink(link, persistent);
publicAPI.registerPropertyLinkForGC(sLink, 'application');
sLink.bind(publicAPI, property, updateOnBind);
}
}
}
}
setImmediate(registerLinks);
}
// ----------------------------------------------------------------------------
// proxyPropertyMapping(publicAPI, model, map)
//
// map = {
// opacity: { modelKey: 'property', property: 'opacity' },
// }
//
// Generated API:
// Elevate set/get methods from internal object stored in the model to current one
// ----------------------------------------------------------------------------
function proxyPropertyMapping(publicAPI, model, map) {
var parentDelete = publicAPI.delete;
var subscriptions = [];
var propertyNames = Object.keys(map);
var count = propertyNames.length;
while (count--) {
var propertyName = propertyNames[count];
var _map$propertyName = map[propertyName],
modelKey = _map$propertyName.modelKey,
property = _map$propertyName.property,
_map$propertyName$mod = _map$propertyName.modified,
modified = _map$propertyName$mod === undefined ? true : _map$propertyName$mod;
var methodSrc = capitalize(property);
var methodDst = capitalize(propertyName);
publicAPI['get' + methodDst] = model[modelKey]['get' + methodSrc];
publicAPI['set' + methodDst] = model[modelKey]['set' + methodSrc];
if (modified) {
subscriptions.push(model[modelKey].onModified(publicAPI.modified));
}
}
publicAPI.delete = function () {
while (subscriptions.length) {
subscriptions.pop().unsubscribe();
}
parentDelete();
};
}
// ----------------------------------------------------------------------------
// proxyPropertyState(publicAPI, model, state, defaults)
//
// state = {
// representation: {
// 'Surface with edges': { property: { edgeVisibility: true, representation: 2 } },
// Surface: { property: { edgeVisibility: false, representation: 2 } },
// Wireframe: { property: { edgeVisibility: false, representation: 1 } },
// Points: { property: { edgeVisibility: false, representation: 0 } },
// },
// }
//
// defaults = {
// representation: 'Surface',
// }
//
// Generated API
// get / set Representation ( string ) => push state to various internal objects
// ----------------------------------------------------------------------------
function proxyPropertyState(publicAPI, model) {
var state = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var defaults = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
model.this = publicAPI;
function applyState(map) {
var modelKeys = Object.keys(map);
var count = modelKeys.length;
while (count--) {
var modelKey = modelKeys[count];
model[modelKey].set(map[modelKey]);
}
}
var modelKeys = Object.keys(defaults);
var count = modelKeys.length;
var _loop2 = function _loop2() {
// Add default
var key = modelKeys[count];
model[key] = defaults[key];
// Add set method
var mapping = state[key];
publicAPI['set' + capitalize(key)] = function (value) {
if (value !== model[key]) {
model[key] = value;
var propValues = mapping[value];
applyState(propValues);
publicAPI.modified();
}
};
};
while (count--) {
_loop2();
}
// Add getter
if (modelKeys.length) {
get(publicAPI, model, modelKeys);
}
}
// ----------------------------------------------------------------------------
// From : https://github.com/facebookarchive/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
//
//
// Copyright (c) 2015, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
//
// Mouse wheel (and 2-finger trackpad) support on the web sucks. It is
// complicated, thus this doc is long and (hopefully) detailed enough to answer
// your questions.
//
// If you need to react to the mouse wheel in a predictable way, this code is
// like your bestest friend.// hugs//
//
// As of today, there are 4 DOM event types you can listen to:
//
// 'wheel' -- Chrome(31+), FF(17+), IE(9+)
// 'mousewheel' -- Chrome, IE(6+), Opera, Safari
// 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!
// 'DOMMouseScroll' -- FF(0.9.7+) since 2003
//
// So what to do? The is the best:
//
// normalizeWheel.getEventType();
//
// In your event callback, use this code to get sane interpretation of the
// deltas. This code will return an object with properties:
//
// spinX -- normalized spin speed (use for zoom) - x plane
// spinY -- " - y plane
// pixelX -- normalized distance (to pixels) - x plane
// pixelY -- " - y plane
//
// Wheel values are provided by the browser assuming you are using the wheel to
// scroll a web page by a number of lines or pixels (or pages). Values can vary
// significantly on different platforms and browsers, forgetting that you can
// scroll at different speeds. Some devices (like trackpads) emit more events
// at smaller increments with fine granularity, and some emit massive jumps with
// linear speed or acceleration.
//
// This code does its best to normalize the deltas for you:
//
// - spin is trying to normalize how far the wheel was spun (or trackpad
// dragged). This is super useful for zoom support where you want to
// throw away the chunky scroll steps on the PC and make those equal to
// the slow and smooth tiny steps on the Mac. Key data: This code tries to
// resolve a single slow step on a wheel to 1.
//
// - pixel is normalizing the desired scroll delta in pixel units. You'll
// get the crazy differences between browsers, but at least it'll be in
// pixels!
//
// - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This
// should translate to positive value zooming IN, negative zooming OUT.
// This matches the newer 'wheel' event.
//
// Why are there spinX, spinY (or pixels)?
//
// - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn
// with a mouse. It results in side-scrolling in the browser by default.
//
// - spinY is what you expect -- it's the classic axis of a mouse wheel.
//
// - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and
// probably is by browsers in conjunction with fancy 3D controllers .. but
// you know.
//
// Implementation info:
//
// Examples of 'wheel' event if you scroll slowly (down) by one step with an
// average mouse:
//
// OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)
// OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)
// OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)
// Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)
// Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)
//
// On the trackpad:
//
// OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)
// OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)
//
// On other/older browsers.. it's more complicated as there can be multiple and
// also missing delta values.
//
// The 'wheel' event is more standard:
//
// http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
//
// The basics is that it includes a unit, deltaMode (pixels, lines, pages), and
// deltaX, deltaY and deltaZ. Some browsers provide other values to maintain
// backward compatibility with older events. Those other values help us
// better normalize spin speed. Example of what the browsers provide:
//
// | event.wheelDelta | event.detail
// ------------------+------------------+--------------
// Safari v5/OS X | -120 | 0
// Safari v5/Win7 | -120 | 0
// Chrome v17/OS X | -120 | 0
// Chrome v17/Win7 | -120 | 0
// IE9/Win7 | -120 | undefined
// Firefox v4/OS X | undefined | 1
// Firefox v4/Win7 | undefined | 3
//
// ----------------------------------------------------------------------------
// Reasonable defaults
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
function normalizeWheel(wheelEvent) {
var sX = 0; // spinX
var sY = 0; // spinY
var pX = 0; // pixelX
var pY = 0; // pixelY
// Legacy
if ('detail' in wheelEvent) {
sY = wheelEvent.detail;
}
if ('wheelDelta' in wheelEvent) {
sY = -wheelEvent.wheelDelta / 120;
}
if ('wheelDeltaY' in wheelEvent) {
sY = -wheelEvent.wheelDeltaY / 120;
}
if ('wheelDeltaX' in wheelEvent) {
sX = -wheelEvent.wheelDeltaX / 120;
}
// side scrolling on FF with DOMMouseScroll
if ('axis' in wheelEvent && wheelEvent.axis === wheelEvent.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in wheelEvent) {
pY = wheelEvent.deltaY;
}
if ('deltaX' in wheelEvent) {
pX = wheelEvent.deltaX;
}
if ((pX || pY) && wheelEvent.deltaMode) {
if (wheelEvent.deltaMode === 1) {
// delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
} else {
// delta in PAGE units
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) {
sX = pX < 1 ? -1 : 1;
}
if (pY && !sY) {
sY = pY < 1 ? -1 : 1;
}
return {
spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY
};
}
// ----------------------------------------------------------------------------
// Default export
// ----------------------------------------------------------------------------
exports.default = {
EVENT_ABORT: EVENT_ABORT,
VOID: VOID,
TYPED_ARRAYS: TYPED_ARRAYS,
algo: algo,
capitalize: capitalize,
uncapitalize: uncapitalize,
chain: chain,
enumToString: enumToString,
event: event,
get: get,
getArray: getArray,
getCurrentGlobalMTime: getCurrentGlobalMTime,
getStateArrayMapFunc: getStateArrayMapFunc,
isVtkObject: isVtkObject,
keystore: keystore,
newInstance: newInstance,
obj: obj,
safeArrays: safeArrays,
set: set,
setArray: setArray,
setGet: setGet,
setGetArray: setGetArray,
setLoggerFunction: setLoggerFunction,
traverseInstanceTree: traverseInstanceTree,
vtkDebugMacro: vtkDebugMacro,
vtkErrorMacro: vtkErrorMacro,
vtkOnceErrorMacro: vtkOnceErrorMacro,
vtkInfoMacro: vtkInfoMacro,
vtkLogMacro: vtkLogMacro,
vtkWarningMacro: vtkWarningMacro,
debounce: debounce,
throttle: throttle,
proxy: proxy,
proxyPropertyMapping: proxyPropertyMapping,
proxyPropertyState: proxyPropertyState,
formatBytesToProperUnit: formatBytesToProperUnit,
formatNumbersWithThousandSeparator: formatNumbersWithThousandSeparator,
normalizeWheel: normalizeWheel
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25), __webpack_require__(165).setImmediate))
/***/ }),
/* 2 */,
/* 3 */,
/* 4 */,
/* 5 */,
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */,
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _seedrandom = __webpack_require__(530);
var _seedrandom2 = _interopRequireDefault(_seedrandom);
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var vtkErrorMacro = _macro2.default.vtkErrorMacro,
vtkWarningMacro = _macro2.default.vtkWarningMacro;
// ----------------------------------------------------------------------------
/* eslint-disable camelcase */
/* eslint-disable no-cond-assign */
/* eslint-disable no-bitwise */
/* eslint-disable no-multi-assign */
// ----------------------------------------------------------------------------
var randomSeedValue = 0;
var VTK_MAX_ROTATIONS = 20;
var VTK_SMALL_NUMBER = 1.0e-12;
function notImplemented(method) {
return function () {
return vtkErrorMacro('vtkMath::' + method + ' - NOT IMPLEMENTED');
};
}
function vtkSwapVectors3(v1, v2) {
for (var i = 0; i < 3; i++) {
var tmp = v1[i];
v1[i] = v2[i];
v2[i] = tmp;
}
}
function createArray() {
var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3;
var array = [];
while (array.length < size) {
array.push(0);
}
return array;
}
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
var Pi = function Pi() {
return Math.PI;
};
var radiansFromDegrees = function radiansFromDegrees(deg) {
return deg / 180 * Math.PI;
};
var degreesFromRadians = function degreesFromRadians(rad) {
return rad * 180 / Math.PI;
};
var round = Math.round,
floor = Math.floor,
ceil = Math.ceil,
min = Math.min,
max = Math.max;
function arrayMin(arr) {
var minValue = Infinity;
for (var i = 0, len = arr.length; i < len; ++i) {
if (arr[i] < minValue) {
minValue = arr[i];
}
}
return minValue;
}
function arrayMax(arr) {
var maxValue = -Infinity;
for (var i = 0, len = arr.length; i < len; ++i) {
if (maxValue < arr[i]) {
maxValue = arr[i];
}
}
return maxValue;
}
var ceilLog2 = notImplemented('ceilLog2');
var factorial = notImplemented('factorial');
function nearestPowerOfTwo(xi) {
var v = 1;
while (v < xi) {
v *= 2;
}
return v;
}
function isPowerOfTwo(x) {
return x === nearestPowerOfTwo(x);
}
function binomial(m, n) {
var r = 1;
for (var i = 1; i <= n; ++i) {
r *= (m - i + 1) / i;
}
return Math.floor(r);
}
function beginCombination(m, n) {
if (m < n) {
return 0;
}
var r = createArray(n);
for (var i = 0; i < n; ++i) {
r[i] = i;
}
return r;
}
function nextCombination(m, n, r) {
var status = 0;
for (var i = n - 1; i >= 0; --i) {
if (r[i] < m - n + i) {
var j = r[i] + 1;
while (i < n) {
r[i++] = j++;
}
status = 1;
break;
}
}
return status;
}
var randomSeed = function randomSeed(seed) {
(0, _seedrandom2.default)('' + seed, { global: true });
randomSeedValue = seed;
};
var getSeed = function getSeed() {
return randomSeedValue;
};
function random() {
var minValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var maxValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var delta = maxValue - minValue;
return minValue + delta * Math.random();
}
var gaussian = notImplemented('gaussian');
// Vect3 operations
function add(a, b, out) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
}
function subtract(a, b, out) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
}
function multiplyScalar(vec, scalar) {
vec[0] *= scalar;
vec[1] *= scalar;
vec[2] *= scalar;
}
function multiplyScalar2D(vec, scalar) {
vec[0] *= scalar;
vec[1] *= scalar;
}
function dot(x, y) {
return x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
}
function outer(x, y, out_3x3) {
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
out_3x3[i][j] = x[i] * y[j];
}
}
}
function cross(x, y, out) {
var Zx = x[1] * y[2] - x[2] * y[1];
var Zy = x[2] * y[0] - x[0] * y[2];
var Zz = x[0] * y[1] - x[1] * y[0];
out[0] = Zx;
out[1] = Zy;
out[2] = Zz;
}
function norm(x) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
switch (n) {
case 1:
return Math.abs(x);
case 2:
return Math.sqrt(x[0] * x[0] + x[1] * x[1]);
case 3:
return Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
default:
{
var sum = 0;
for (var i = 0; i < n; i++) {
sum += x[i] * x[i];
}
return Math.sqrt(sum);
}
}
}
function normalize(x) {
var den = norm(x);
if (den !== 0.0) {
x[0] /= den;
x[1] /= den;
x[2] /= den;
}
return den;
}
function perpendiculars(x, y, z, theta) {
var x2 = x[0] * x[0];
var y2 = x[1] * x[1];
var z2 = x[2] * x[2];
var r = Math.sqrt(x2 + y2 + z2);
var dx = void 0;
var dy = void 0;
var dz = void 0;
// transpose the vector to avoid divide-by-zero error
if (x2 > y2 && x2 > z2) {
dx = 0;
dy = 1;
dz = 2;
} else if (y2 > z2) {
dx = 1;
dy = 2;
dz = 0;
} else {
dx = 2;
dy = 0;
dz = 1;
}
var a = x[dx] / r;
var b = x[dy] / r;
var c = x[dz] / r;
var tmp = Math.sqrt(a * a + c * c);
if (theta !== 0) {
var sintheta = Math.sin(theta);
var costheta = Math.cos(theta);
if (y) {
y[dx] = (c * costheta - a * b * sintheta) / tmp;
y[dy] = sintheta * tmp;
y[dz] = (-(a * costheta) - b * c * sintheta) / tmp;
}
if (z) {
z[dx] = (-(c * sintheta) - a * b * costheta) / tmp;
z[dy] = costheta * tmp;
z[dz] = (a * sintheta - b * c * costheta) / tmp;
}
} else {
if (y) {
y[dx] = c / tmp;
y[dy] = 0;
y[dz] = -a / tmp;
}
if (z) {
z[dx] = -a * b / tmp;
z[dy] = tmp;
z[dz] = -b * c / tmp;
}
}
}
function projectVector(a, b, projection) {
var bSquared = dot(b, b);
if (bSquared === 0) {
projection[0] = 0;
projection[1] = 0;
projection[2] = 0;
return false;
}
var scale = dot(a, b) / bSquared;
for (var i = 0; i < 3; i++) {
projection[i] = b[i];
}
multiplyScalar(projection, scale);
return true;
}
function dot2D(x, y) {
return x[0] * y[0] + x[1] * y[1];
}
function projectVector2D(a, b, projection) {
var bSquared = dot2D(b, b);
if (bSquared === 0) {
projection[0] = 0;
projection[1] = 0;
return false;
}
var scale = dot2D(a, b) / bSquared;
for (var i = 0; i < 2; i++) {
projection[i] = b[i];
}
multiplyScalar2D(projection, scale);
return true;
}
function distance2BetweenPoints(x, y) {
return (x[0] - y[0]) * (x[0] - y[0]) + (x[1] - y[1]) * (x[1] - y[1]) + (x[2] - y[2]) * (x[2] - y[2]);
}
function angleBetweenVectors(v1, v2) {
var crossVect = [0, 0, 0];
cross(v1, v2, crossVect);
return Math.atan2(norm(crossVect), dot(v1, v2));
}
function gaussianAmplitude(mean, variance, position) {
var distanceFromMean = Math.abs(mean - position);
return 1 / Math.sqrt(2 * Math.PI * variance) * Math.exp(-Math.pow(distanceFromMean, 2) / (2 * variance));
}
function gaussianWeight(mean, variance, position) {
var distanceFromMean = Math.abs(mean - position);
return Math.exp(-Math.pow(distanceFromMean, 2) / (2 * variance));
}
function outer2D(x, y, out_2x2) {
for (var i = 0; i < 2; i++) {
for (var j = 0; j < 2; j++) {
out_2x2[i][j] = x[i] * y[j];
}
}
}
function norm2D(x2D) {
return Math.sqrt(x2D[0] * x2D[0] + x2D[1] * x2D[1]);
}
function normalize2D(x) {
var den = norm2D(x);
if (den !== 0.0) {
x[0] /= den;
x[1] /= den;
}
return den;
}
function determinant2x2() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === 2) {
return args[0][0] * args[1][1] - args[1][0] * args[0][1];
}
if (args.length === 4) {
return args[0] * args[3] - args[1] * args[2];
}
return Number.NaN;
}
function LUFactor3x3(mat_3x3, index_3) {
var maxI = void 0;
var tmp = void 0;
var largest = void 0;
var scale = [0, 0, 0];
// Loop over rows to get implicit scaling information
for (var i = 0; i < 3; i++) {
largest = Math.abs(mat_3x3[i][0]);
if ((tmp = Math.abs(mat_3x3[i][1])) > largest) {
largest = tmp;
}
if ((tmp = Math.abs(mat_3x3[i][2])) > largest) {
largest = tmp;
}
scale[i] = 1 / largest;
}
// Loop over all columns using Crout's method
// first column
largest = scale[0] * Math.abs(mat_3x3[0][0]);
maxI = 0;
if ((tmp = scale[1] * Math.abs(mat_3x3[1][0])) >= largest) {
largest = tmp;
maxI = 1;
}
if ((tmp = scale[2] * Math.abs(mat_3x3[2][0])) >= largest) {
maxI = 2;
}
if (maxI !== 0) {
vtkSwapVectors3(mat_3x3[maxI], mat_3x3[0]);
scale[maxI] = scale[0];
}
index_3[0] = maxI;
mat_3x3[1][0] /= mat_3x3[0][0];
mat_3x3[2][0] /= mat_3x3[0][0];
// second column
mat_3x3[1][1] -= mat_3x3[1][0] * mat_3x3[0][1];
mat_3x3[2][1] -= mat_3x3[2][0] * mat_3x3[0][1];
largest = scale[1] * Math.abs(mat_3x3[1][1]);
maxI = 1;
if ((tmp = scale[2] * Math.abs(mat_3x3[2][1])) >= largest) {
maxI = 2;
vtkSwapVectors3(mat_3x3[2], mat_3x3[1]);
scale[2] = scale[1];
}
index_3[1] = maxI;
mat_3x3[2][1] /= mat_3x3[1][1];
// third column
mat_3x3[1][2] -= mat_3x3[1][0] * mat_3x3[0][2];
mat_3x3[2][2] -= mat_3x3[2][0] * mat_3x3[0][2] + mat_3x3[2][1] * mat_3x3[1][2];
index_3[2] = 2;
}
function LUSolve3x3(mat_3x3, index_3, x_3) {
// forward substitution
var sum = x_3[index_3[0]];
x_3[index_3[0]] = x_3[0];
x_3[0] = sum;
sum = x_3[index_3[1]];
x_3[index_3[1]] = x_3[1];
x_3[1] = sum - mat_3x3[1][0] * x_3[0];
sum = x_3[index_3[2]];
x_3[index_3[2]] = x_3[2];
x_3[2] = sum - mat_3x3[2][0] * x_3[0] - mat_3x3[2][1] * x_3[1];
// back substitution
x_3[2] /= mat_3x3[2][2];
x_3[1] = (x_3[1] - mat_3x3[1][2] * x_3[2]) / mat_3x3[1][1];
x_3[0] = (x_3[0] - mat_3x3[0][1] * x_3[1] - mat_3x3[0][2] * x_3[2]) / mat_3x3[0][0];
}
function linearSolve3x3(mat_3x3, x_3, y_3) {
var a1 = mat_3x3[0][0];
var b1 = mat_3x3[0][1];
var c1 = mat_3x3[0][2];
var a2 = mat_3x3[1][0];
var b2 = mat_3x3[1][1];
var c2 = mat_3x3[1][2];
var a3 = mat_3x3[2][0];
var b3 = mat_3x3[2][1];
var c3 = mat_3x3[2][2];
// Compute the adjoint
var d1 = +determinant2x2(b2, b3, c2, c3);
var d2 = -determinant2x2(a2, a3, c2, c3);
var d3 = +determinant2x2(a2, a3, b2, b3);
var e1 = -determinant2x2(b1, b3, c1, c3);
var e2 = +determinant2x2(a1, a3, c1, c3);
var e3 = -determinant2x2(a1, a3, b1, b3);
var f1 = +determinant2x2(b1, b2, c1, c2);
var f2 = -determinant2x2(a1, a2, c1, c2);
var f3 = +determinant2x2(a1, a2, b1, b2);
// Compute the determinant
var det = a1 * d1 + b1 * d2 + c1 * d3;
// Multiply by the adjoint
var v1 = d1 * x_3[0] + e1 * x_3[1] + f1 * x_3[2];
var v2 = d2 * x_3[0] + e2 * x_3[1] + f2 * x_3[2];
var v3 = d3 * x_3[0] + e3 * x_3[1] + f3 * x_3[2];
// Divide by the determinant
y_3[0] = v1 / det;
y_3[1] = v2 / det;
y_3[2] = v3 / det;
}
function multiply3x3_vect3(mat_3x3, in_3, out_3) {
var x = mat_3x3[0][0] * in_3[0] + mat_3x3[0][1] * in_3[1] + mat_3x3[0][2] * in_3[2];
var y = mat_3x3[1][0] * in_3[0] + mat_3x3[1][1] * in_3[1] + mat_3x3[1][2] * in_3[2];
var z = mat_3x3[2][0] * in_3[0] + mat_3x3[2][1] * in_3[1] + mat_3x3[2][2] * in_3[2];
out_3[0] = x;
out_3[1] = y;
out_3[2] = z;
}
function multiply3x3_mat3(a_3x3, b_3x3, out_3x3) {
var tmp = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
for (var i = 0; i < 3; i++) {
tmp[0][i] = a_3x3[0][0] * b_3x3[0][i] + a_3x3[0][1] * b_3x3[1][i] + a_3x3[0][2] * b_3x3[2][i];
tmp[1][i] = a_3x3[1][0] * b_3x3[0][i] + a_3x3[1][1] * b_3x3[1][i] + a_3x3[1][2] * b_3x3[2][i];
tmp[2][i] = a_3x3[2][0] * b_3x3[0][i] + a_3x3[2][1] * b_3x3[1][i] + a_3x3[2][2] * b_3x3[2][i];
}
for (var j = 0; j < 3; j++) {
out_3x3[j][0] = tmp[j][0];
out_3x3[j][1] = tmp[j][1];
out_3x3[j][2] = tmp[j][2];
}
}
function multiplyMatrix(a, b, rowA, colA, rowB, colB, out_rowXcol) {
// we need colA == rowB
if (colA !== rowB) {
vtkErrorMacro('Number of columns of A must match number of rows of B.');
}
// output matrix is rowA*colB
// output row
for (var i = 0; i < rowA; i++) {
// output col
for (var j = 0; j < colB; j++) {
out_rowXcol[i][j] = 0;
// sum for this point
for (var k = 0; k < colA; k++) {
out_rowXcol[i][j] += a[i][k] * b[k][j];
}
}
}
}
function transpose3x3(in_3x3, outT_3x3) {
var tmp = void 0;
tmp = in_3x3[1][0];
outT_3x3[1][0] = in_3x3[0][1];
outT_3x3[0][1] = tmp;
tmp = in_3x3[2][0];
outT_3x3[2][0] = in_3x3[0][2];
outT_3x3[0][2] = tmp;
tmp = in_3x3[2][1];
outT_3x3[2][1] = in_3x3[1][2];
outT_3x3[1][2] = tmp;
outT_3x3[0][0] = in_3x3[0][0];
outT_3x3[1][1] = in_3x3[1][1];
outT_3x3[2][2] = in_3x3[2][2];
}
function invert3x3(in_3x3, outI_3x3) {
var a1 = in_3x3[0][0];
var b1 = in_3x3[0][1];
var c1 = in_3x3[0][2];
var a2 = in_3x3[1][0];
var b2 = in_3x3[1][1];
var c2 = in_3x3[1][2];
var a3 = in_3x3[2][0];
var b3 = in_3x3[2][1];
var c3 = in_3x3[2][2];
// Compute the adjoint
var d1 = +determinant2x2(b2, b3, c2, c3);
var d2 = -determinant2x2(a2, a3, c2, c3);
var d3 = +determinant2x2(a2, a3, b2, b3);
var e1 = -determinant2x2(b1, b3, c1, c3);
var e2 = +determinant2x2(a1, a3, c1, c3);
var e3 = -determinant2x2(a1, a3, b1, b3);
var f1 = +determinant2x2(b1, b2, c1, c2);
var f2 = -determinant2x2(a1, a2, c1, c2);
var f3 = +determinant2x2(a1, a2, b1, b2);
// Divide by the determinant
var det = a1 * d1 + b1 * d2 + c1 * d3;
outI_3x3[0][0] = d1 / det;
outI_3x3[1][0] = d2 / det;
outI_3x3[2][0] = d3 / det;
outI_3x3[0][1] = e1 / det;
outI_3x3[1][1] = e2 / det;
outI_3x3[2][1] = e3 / det;
outI_3x3[0][2] = f1 / det;
outI_3x3[1][2] = f2 / det;
outI_3x3[2][2] = f3 / det;
}
function identity3x3(mat_3x3) {
for (var i = 0; i < 3; i++) {
mat_3x3[i][0] = mat_3x3[i][1] = mat_3x3[i][2] = 0;
mat_3x3[i][i] = 1;
}
}
function determinant3x3(mat_3x3) {
return mat_3x3[0][0] * mat_3x3[1][1] * mat_3x3[2][2] + mat_3x3[1][0] * mat_3x3[2][1] * mat_3x3[0][2] + mat_3x3[2][0] * mat_3x3[0][1] * mat_3x3[1][2] - mat_3x3[0][0] * mat_3x3[2][1] * mat_3x3[1][2] - mat_3x3[1][0] * mat_3x3[0][1] * mat_3x3[2][2] - mat_3x3[2][0] * mat_3x3[1][1] * mat_3x3[0][2];
}
function quaternionToMatrix3x3(quat_4, mat_3x3) {
var ww = quat_4[0] * quat_4[0];
var wx = quat_4[0] * quat_4[1];
var wy = quat_4[0] * quat_4[2];
var wz = quat_4[0] * quat_4[3];
var xx = quat_4[1] * quat_4[1];
var yy = quat_4[2] * quat_4[2];
var zz = quat_4[3] * quat_4[3];
var xy = quat_4[1] * quat_4[2];
var xz = quat_4[1] * quat_4[3];
var yz = quat_4[2] * quat_4[3];
var rr = xx + yy + zz;
// normalization factor, just in case quaternion was not normalized
var f = 1 / (ww + rr);
var s = (ww - rr) * f;
f *= 2;
mat_3x3[0][0] = xx * f + s;
mat_3x3[1][0] = (xy + wz) * f;
mat_3x3[2][0] = (xz - wy) * f;
mat_3x3[0][1] = (xy - wz) * f;
mat_3x3[1][1] = yy * f + s;
mat_3x3[2][1] = (yz + wx) * f;
mat_3x3[0][2] = (xz + wy) * f;
mat_3x3[1][2] = (yz - wx) * f;
mat_3x3[2][2] = zz * f + s;
}
function areMatricesEqual(matA, matB) {
if (!matA.length === matB.length) {
return false;
}
function isEqual(element, index) {
return element === matB[index];
}
return matA.every(isEqual);
}
function jacobiN(a, n, w, v) {
var i = void 0;
var j = void 0;
var k = void 0;
var iq = void 0;
var ip = void 0;
var numPos = void 0;
var tresh = void 0;
var theta = void 0;
var t = void 0;
var tau = void 0;
var sm = void 0;
var s = void 0;
var h = void 0;
var g = void 0;
var c = void 0;
var tmp = void 0;
var b = createArray(n);
var z = createArray(n);
var vtkROTATE = function vtkROTATE(aa, ii, jj, kk, ll) {
g = aa[ii][jj];
h = aa[kk][ll];
aa[ii][jj] = g - s * (h + g * tau);
aa[kk][ll] = h + s * (g - h * tau);
};
// initialize
for (ip = 0; ip < n; ip++) {
for (iq = 0; iq < n; iq++) {
v[ip][iq] = 0.0;
}
v[ip][ip] = 1.0;
}
for (ip = 0; ip < n; ip++) {
b[ip] = w[ip] = a[ip][ip];
z[ip] = 0.0;
}
// begin rotation sequence
for (i = 0; i < VTK_MAX_ROTATIONS; i++) {
sm = 0.0;
for (ip = 0; ip < n - 1; ip++) {
for (iq = ip + 1; iq < n; iq++) {
sm += Math.abs(a[ip][iq]);
}
}
if (sm === 0.0) {
break;
}
// first 3 sweeps
if (i < 3) {
tresh = 0.2 * sm / (n * n);
} else {
tresh = 0.0;
}
for (ip = 0; ip < n - 1; ip++) {
for (iq = ip + 1; iq < n; iq++) {
g = 100.0 * Math.abs(a[ip][iq]);
// after 4 sweeps
if (i > 3 && Math.abs(w[ip]) + g === Math.abs(w[ip]) && Math.abs(w[iq]) + g === Math.abs(w[iq])) {
a[ip][iq] = 0.0;
} else if (Math.abs(a[ip][iq]) > tresh) {
h = w[iq] - w[ip];
if (Math.abs(h) + g === Math.abs(h)) {
t = a[ip][iq] / h;
} else {
theta = 0.5 * h / a[ip][iq];
t = 1.0 / (Math.abs(theta) + Math.sqrt(1.0 + theta * theta));
if (theta < 0.0) {
t = -t;
}
}
c = 1.0 / Math.sqrt(1 + t * t);
s = t * c;
tau = s / (1.0 + c);
h = t * a[ip][iq];
z[ip] -= h;
z[iq] += h;
w[ip] -= h;
w[iq] += h;
a[ip][iq] = 0.0;
// ip already shifted left by 1 unit
for (j = 0; j <= ip - 1; j++) {
vtkROTATE(a, j, ip, j, iq);
}
// ip and iq already shifted left by 1 unit
for (j = ip + 1; j <= iq - 1; j++) {
vtkROTATE(a, ip, j, j, iq);
}
// iq already shifted left by 1 unit
for (j = iq + 1; j < n; j++) {
vtkROTATE(a, ip, j, iq, j);
}
for (j = 0; j < n; j++) {
vtkROTATE(v, j, ip, j, iq);
}
}
}
}
for (ip = 0; ip < n; ip++) {
b[ip] += z[ip];
w[ip] = b[ip];
z[ip] = 0.0;
}
}
// this is NEVER called
if (i >= VTK_MAX_ROTATIONS) {
vtkWarningMacro('vtkMath::Jacobi: Error extracting eigenfunctions');
return 0;
}
// sort eigenfunctions: these changes do not affect accuracy
for (j = 0; j < n - 1; j++) {
// boundary incorrect
k = j;
tmp = w[k];
for (i = j + 1; i < n; i++) {
// boundary incorrect, shifted already
if (w[i] >= tmp) {
// why exchange if same?
k = i;
tmp = w[k];
}
}
if (k !== j) {
w[k] = w[j];
w[j] = tmp;
for (i = 0; i < n; i++) {
tmp = v[i][j];
v[i][j] = v[i][k];
v[i][k] = tmp;
}
}
}
// ensure eigenvector consistency (i.e., Jacobi can compute vectors that
// are negative of one another (.707,.707,0) and (-.707,-.707,0). This can
// reek havoc in hyperstreamline/other stuff. We will select the most
// positive eigenvector.
var ceil_half_n = (n >> 1) + (n & 1);
for (j = 0; j < n; j++) {
for (numPos = 0, i = 0; i < n; i++) {
if (v[i][j] >= 0.0) {
numPos++;
}
}
// if ( numPos < ceil(double(n)/double(2.0)) )
if (numPos < ceil_half_n) {
for (i = 0; i < n; i++) {
v[i][j] *= -1.0;
}
}
}
return 1;
}
function matrix3x3ToQuaternion(mat_3x3, quat_4) {
var tmp = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
// on-diagonal elements
tmp[0][0] = mat_3x3[0][0] + mat_3x3[1][1] + mat_3x3[2][2];
tmp[1][1] = mat_3x3[0][0] - mat_3x3[1][1] - mat_3x3[2][2];
tmp[2][2] = -mat_3x3[0][0] + mat_3x3[1][1] - mat_3x3[2][2];
tmp[3][3] = -mat_3x3[0][0] - mat_3x3[1][1] + mat_3x3[2][2];
// off-diagonal elements
tmp[0][1] = tmp[1][0] = mat_3x3[2][1] - mat_3x3[1][2];
tmp[0][2] = tmp[2][0] = mat_3x3[0][2] - mat_3x3[2][0];
tmp[0][3] = tmp[3][0] = mat_3x3[1][0] - mat_3x3[0][1];
tmp[1][2] = tmp[2][1] = mat_3x3[1][0] + mat_3x3[0][1];
tmp[1][3] = tmp[3][1] = mat_3x3[0][2] + mat_3x3[2][0];
tmp[2][3] = tmp[3][2] = mat_3x3[2][1] + mat_3x3[1][2];
var eigenvectors = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
var eigenvalues = [0, 0, 0, 0];
// convert into format that JacobiN can use,
// then use Jacobi to find eigenvalues and eigenvectors
var NTemp = [0, 0, 0, 0];
var eigenvectorsTemp = [0, 0, 0, 0];
for (var i = 0; i < 4; i++) {
NTemp[i] = tmp[i];
eigenvectorsTemp[i] = eigenvectors[i];
}
jacobiN(NTemp, 4, eigenvalues, eigenvectorsTemp);
// the first eigenvector is the one we want
quat_4[0] = eigenvectors[0][0];
quat_4[1] = eigenvectors[1][0];
quat_4[2] = eigenvectors[2][0];
quat_4[3] = eigenvectors[3][0];
}
function multiplyQuaternion(quat_1, quat_2, quat_out) {
var ww = quat_1[0] * quat_2[0];
var wx = quat_1[0] * quat_2[1];
var wy = quat_1[0] * quat_2[2];
var wz = quat_1[0] * quat_2[3];
var xw = quat_1[1] * quat_2[0];
var xx = quat_1[1] * quat_2[1];
var xy = quat_1[1] * quat_2[2];
var xz = quat_1[1] * quat_2[3];
var yw = quat_1[2] * quat_2[0];
var yx = quat_1[2] * quat_2[1];
var yy = quat_1[2] * quat_2[2];
var yz = quat_1[2] * quat_2[3];
var zw = quat_1[3] * quat_2[0];
var zx = quat_1[3] * quat_2[1];
var zy = quat_1[3] * quat_2[2];
var zz = quat_1[3] * quat_2[3];
quat_out[0] = ww - xx - yy - zz;
quat_out[1] = wx + xw + yz - zy;
quat_out[2] = wy - xz + yw + zx;
quat_out[3] = wz + xy - yx + zw;
}
function orthogonalize3x3(a_3x3, out_3x3) {
// copy the matrix
for (var i = 0; i < 3; i++) {
out_3x3[0][i] = a_3x3[0][i];
out_3x3[1][i] = a_3x3[1][i];
out_3x3[2][i] = a_3x3[2][i];
}
// Pivot the matrix to improve accuracy
var scale = createArray(3);
var index = createArray(3);
var largest = void 0;
// Loop over rows to get implicit scaling information
for (var _i = 0; _i < 3; _i++) {
var _x5 = Math.abs(out_3x3[_i][0]);
var _x6 = Math.abs(out_3x3[_i][1]);
var _x7 = Math.abs(out_3x3[_i][2]);
largest = _x6 > _x5 ? _x6 : _x5;
largest = _x7 > largest ? _x7 : largest;
scale[_i] = 1;
if (largest !== 0) {
scale[_i] /= largest;
}
}
// first column
var x1 = Math.abs(out_3x3[0][0]) * scale[0];
var x2 = Math.abs(out_3x3[1][0]) * scale[1];
var x3 = Math.abs(out_3x3[2][0]) * scale[2];
index[0] = 0;
largest = x1;
if (x2 >= largest) {
largest = x2;
index[0] = 1;
}
if (x3 >= largest) {
index[0] = 2;
}
if (index[0] !== 0) {
vtkSwapVectors3(out_3x3[index[0]], out_3x3[0]);
scale[index[0]] = scale[0];
}
// second column
var y2 = Math.abs(out_3x3[1][1]) * scale[1];
var y3 = Math.abs(out_3x3[2][1]) * scale[2];
index[1] = 1;
largest = y2;
if (y3 >= largest) {
index[1] = 2;
vtkSwapVectors3(out_3x3[2], out_3x3[1]);
}
// third column
index[2] = 2;
// A quaternion can only describe a pure rotation, not
// a rotation with a flip, therefore the flip must be
// removed before the matrix is converted to a quaternion.
var flip = 0;
if (determinant3x3(out_3x3) < 0) {
flip = 1;
for (var _i2 = 0; _i2 < 3; _i2++) {
out_3x3[0][_i2] = -out_3x3[0][_i2];
out_3x3[1][_i2] = -out_3x3[1][_i2];
out_3x3[2][_i2] = -out_3x3[2][_i2];
}
}
// Do orthogonalization using a quaternion intermediate
// (this, essentially, does the orthogonalization via
// diagonalization of an appropriately constructed symmetric
// 4x4 matrix rather than by doing SVD of the 3x3 matrix)
var quat = createArray(4);
matrix3x3ToQuaternion(out_3x3, quat);
quaternionToMatrix3x3(quat, out_3x3);
// Put the flip back into the orthogonalized matrix.
if (flip) {
for (var _i3 = 0; _i3 < 3; _i3++) {
out_3x3[0][_i3] = -out_3x3[0][_i3];
out_3x3[1][_i3] = -out_3x3[1][_i3];
out_3x3[2][_i3] = -out_3x3[2][_i3];
}
}
// Undo the pivoting
if (index[1] !== 1) {
vtkSwapVectors3(out_3x3[index[1]], out_3x3[1]);
}
if (index[0] !== 0) {
vtkSwapVectors3(out_3x3[index[0]], out_3x3[0]);
}
}
function diagonalize3x3(a_3x3, w_3, v_3x3) {
var i = void 0;
var j = void 0;
var k = void 0;
var maxI = void 0;
var tmp = void 0;
var maxVal = void 0;
// do the matrix[3][3] to **matrix conversion for Jacobi
var C = [createArray(3), createArray(3), createArray(3)];
var ATemp = createArray(3);
var VTemp = createArray(3);
for (i = 0; i < 3; i++) {
C[i][0] = a_3x3[i][0];
C[i][1] = a_3x3[i][1];
C[i][2] = a_3x3[i][2];
ATemp[i] = C[i];
VTemp[i] = v_3x3[i];
}
// diagonalize using Jacobi
jacobiN(ATemp, 3, w_3, VTemp);
// if all the eigenvalues are the same, return identity matrix
if (w_3[0] === w_3[1] && w_3[0] === w_3[2]) {
identity3x3(v_3x3);
return;
}
// transpose temporarily, it makes it easier to sort the eigenvectors
transpose3x3(v_3x3, v_3x3);
// if two eigenvalues are the same, re-orthogonalize to optimally line
// up the eigenvectors with the x, y, and z axes
for (i = 0; i < 3; i++) {
// two eigenvalues are the same
if (w_3[(i + 1) % 3] === w_3[(i + 2) % 3]) {
// find maximum element of the independent eigenvector
maxVal = Math.abs(v_3x3[i][0]);
maxI = 0;
for (j = 1; j < 3; j++) {
if (maxVal < (tmp = Math.abs(v_3x3[i][j]))) {
maxVal = tmp;
maxI = j;
}
}
// swap the eigenvector into its proper position
if (maxI !== i) {
tmp = w_3[maxI];
w_3[maxI] = w_3[i];
w_3[i] = tmp;
vtkSwapVectors3(v_3x3[i], v_3x3[maxI]);
}
// maximum element of eigenvector should be positive
if (v_3x3[maxI][maxI] < 0) {
v_3x3[maxI][0] = -v_3x3[maxI][0];
v_3x3[maxI][1] = -v_3x3[maxI][1];
v_3x3[maxI][2] = -v_3x3[maxI][2];
}
// re-orthogonalize the other two eigenvectors
j = (maxI + 1) % 3;
k = (maxI + 2) % 3;
v_3x3[j][0] = 0.0;
v_3x3[j][1] = 0.0;
v_3x3[j][2] = 0.0;
v_3x3[j][j] = 1.0;
cross(v_3x3[maxI], v_3x3[j], v_3x3[k]);
normalize(v_3x3[k]);
cross(v_3x3[k], v_3x3[maxI], v_3x3[j]);
// transpose vectors back to columns
transpose3x3(v_3x3, v_3x3);
return;
}
}
// the three eigenvalues are different, just sort the eigenvectors
// to align them with the x, y, and z axes
// find the vector with the largest x element, make that vector
// the first vector
maxVal = Math.abs(v_3x3[0][0]);
maxI = 0;
for (i = 1; i < 3; i++) {
if (maxVal < (tmp = Math.abs(v_3x3[i][0]))) {
maxVal = tmp;
maxI = i;
}
}
// swap eigenvalue and eigenvector
if (maxI !== 0) {
tmp = w_3[maxI];
w_3[maxI] = w_3[0];
w_3[0] = tmp;
vtkSwapVectors3(v_3x3[maxI], v_3x3[0]);
}
// do the same for the y element
if (Math.abs(v_3x3[1][1]) < Math.abs(v_3x3[2][1])) {
tmp = w_3[2];
w_3[2] = w_3[1];
w_3[1] = tmp;
vtkSwapVectors3(v_3x3[2], v_3x3[1]);
}
// ensure that the sign of the eigenvectors is correct
for (i = 0; i < 2; i++) {
if (v_3x3[i][i] < 0) {
v_3x3[i][0] = -v_3x3[i][0];
v_3x3[i][1] = -v_3x3[i][1];
v_3x3[i][2] = -v_3x3[i][2];
}
}
// set sign of final eigenvector to ensure that determinant is positive
if (determinant3x3(v_3x3) < 0) {
v_3x3[2][0] = -v_3x3[2][0];
v_3x3[2][1] = -v_3x3[2][1];
v_3x3[2][2] = -v_3x3[2][2];
}
// transpose the eigenvectors back again
transpose3x3(v_3x3, v_3x3);
}
function singularValueDecomposition3x3(a_3x3, u_3x3, w_3, vT_3x3) {
var i = void 0;
var B = [createArray(3), createArray(3), createArray(3)];
// copy so that A can be used for U or VT without risk
for (i = 0; i < 3; i++) {
B[0][i] = a_3x3[0][i];
B[1][i] = a_3x3[1][i];
B[2][i] = a_3x3[2][i];
}
// temporarily flip if determinant is negative
var d = determinant3x3(B);
if (d < 0) {
for (i = 0; i < 3; i++) {
B[0][i] = -B[0][i];
B[1][i] = -B[1][i];
B[2][i] = -B[2][i];
}
}
// orthogonalize, diagonalize, etc.
orthogonalize3x3(B, u_3x3);
transpose3x3(B, B);
multiply3x3_mat3(B, u_3x3, vT_3x3);
diagonalize3x3(vT_3x3, w_3, vT_3x3);
multiply3x3_mat3(u_3x3, vT_3x3, u_3x3);
transpose3x3(vT_3x3, vT_3x3);
// re-create the flip
if (d < 0) {
w_3[0] = -w_3[0];
w_3[1] = -w_3[1];
w_3[2] = -w_3[2];
}
}
function luFactorLinearSystem(A, index, size) {
var i = void 0;
var j = void 0;
var k = void 0;
var largest = void 0;
var maxI = 0;
var sum = void 0;
var temp1 = void 0;
var temp2 = void 0;
var scale = createArray(size);
//
// Loop over rows to get implicit scaling information
//
for (i = 0; i < size; i++) {
for (largest = 0.0, j = 0; j < size; j++) {
if ((temp2 = Math.abs(A[i][j])) > largest) {
largest = temp2;
}
}
if (largest === 0.0) {
vtkWarningMacro('Unable to factor linear system');
return 0;
}
scale[i] = 1.0 / largest;
}
//
// Loop over all columns using Crout's method
//
for (j = 0; j < size; j++) {
for (i = 0; i < j; i++) {
sum = A[i][j];
for (k = 0; k < i; k++) {
sum -= A[i][k] * A[k][j];
}
A[i][j] = sum;
}
//
// Begin search for largest pivot element
//
for (largest = 0.0, i = j; i < size; i++) {
sum = A[i][j];
for (k = 0; k < j; k++) {
sum -= A[i][k] * A[k][j];
}
A[i][j] = sum;
if ((temp1 = scale[i] * Math.abs(sum)) >= largest) {
largest = temp1;
maxI = i;
}
}
//
// Check for row interchange
//
if (j !== maxI) {
for (k = 0; k < size; k++) {
temp1 = A[maxI][k];
A[maxI][k] = A[j][k];
A[j][k] = temp1;
}
scale[maxI] = scale[j];
}
//
// Divide by pivot element and perform elimination
//
index[j] = maxI;
if (Math.abs(A[j][j]) <= VTK_SMALL_NUMBER) {
vtkWarningMacro('Unable to factor linear system');
return 0;
}
if (j !== size - 1) {
temp1 = 1.0 / A[j][j];
for (i = j + 1; i < size; i++) {
A[i][j] *= temp1;
}
}
}
return 1;
}
function luSolveLinearSystem(A, index, x, size) {
var i = void 0;
var j = void 0;
var ii = void 0;
var idx = void 0;
var sum = void 0;
//
// Proceed with forward and backsubstitution for L and U
// matrices. First, forward substitution.
//
for (ii = -1, i = 0; i < size; i++) {
idx = index[i];
sum = x[idx];
x[idx] = x[i];
if (ii >= 0) {
for (j = ii; j <= i - 1; j++) {
sum -= A[i][j] * x[j];
}
} else if (sum !== 0.0) {
ii = i;
}
x[i] = sum;
}
//
// Now, back substitution
//
for (i = size - 1; i >= 0; i--) {
sum = x[i];
for (j = i + 1; j < size; j++) {
sum -= A[i][j] * x[j];
}
x[i] = sum / A[i][i];
}
}
function solveLinearSystem(A, x, size) {
// if we solving something simple, just solve it
if (size === 2) {
var y = createArray(2);
var det = determinant2x2(A[0][0], A[0][1], A[1][0], A[1][1]);
if (det === 0.0) {
// Unable to solve linear system
return 0;
}
y[0] = (A[1][1] * x[0] - A[0][1] * x[1]) / det;
y[1] = (-(A[1][0] * x[0]) + A[0][0] * x[1]) / det;
x[0] = y[0];
x[1] = y[1];
return 1;
} else if (size === 1) {
if (A[0][0] === 0.0) {
// Unable to solve linear system
return 0;
}
x[0] /= A[0][0];
return 1;
}
//
// System of equations is not trivial, use Crout's method
//
// Check on allocation of working vectors
var index = createArray(size);
// Factor and solve matrix
if (luFactorLinearSystem(A, index, size) === 0) {
return 0;
}
luSolveLinearSystem(A, index, x, size);
return 1;
}
function invertMatrix(A, AI, size) {
var index = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var column = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
var tmp1Size = index || createArray(size);
var tmp2Size = column || createArray(size);
// Factor matrix; then begin solving for inverse one column at a time.
// Note: tmp1Size returned value is used later, tmp2Size is just working
// memory whose values are not used in LUSolveLinearSystem
if (luFactorLinearSystem(A, tmp1Size, size, tmp2Size) === 0) {
return 0;
}
for (var j = 0; j < size; j++) {
for (var i = 0; i < size; i++) {
tmp2Size[i] = 0.0;
}
tmp2Size[j] = 1.0;
luSolveLinearSystem(A, tmp1Size, tmp2Size, size);
for (var _i4 = 0; _i4 < size; _i4++) {
AI[_i4][j] = tmp2Size[_i4];
}
}
return 1;
}
function estimateMatrixCondition(A, size) {
var minValue = +Number.MAX_VALUE;
var maxValue = -Number.MAX_VALUE;
// find the maximum value
for (var i = 0; i < size; i++) {
for (var j = i; j < size; j++) {
if (Math.abs(A[i][j]) > max) {
maxValue = Math.abs(A[i][j]);
}
}
}
// find the minimum diagonal value
for (var _i5 = 0; _i5 < size; _i5++) {
if (Math.abs(A[_i5][_i5]) < min) {
minValue = Math.abs(A[_i5][_i5]);
}
}
if (minValue === 0.0) {
return Number.MAX_VALUE;
}
return maxValue / minValue;
}
function jacobi(a_3x3, w, v) {
return jacobiN(a_3x3, 3, w, v);
}
function solveHomogeneousLeastSquares(numberOfSamples, xt, xOrder, mt) {
// check dimensional consistency
if (numberOfSamples < xOrder) {
vtkWarningMacro('Insufficient number of samples. Underdetermined.');
return 0;
}
var i = void 0;
var j = void 0;
var k = void 0;
// set up intermediate variables
// Allocate matrix to hold X times transpose of X
var XXt = createArray(xOrder); // size x by x
// Allocate the array of eigenvalues and eigenvectors
var eigenvals = createArray(xOrder);
var eigenvecs = createArray(xOrder);
// Clear the upper triangular region (and btw, allocate the eigenvecs as well)
for (i = 0; i < xOrder; i++) {
eigenvecs[i] = createArray(xOrder);
XXt[i] = createArray(xOrder);
for (j = 0; j < xOrder; j++) {
XXt[i][j] = 0.0;
}
}
// Calculate XXt upper half only, due to symmetry
for (k = 0; k < numberOfSamples; k++) {
for (i = 0; i < xOrder; i++) {
for (j = i; j < xOrder; j++) {
XXt[i][j] += xt[k][i] * xt[k][j];
}
}
}
// now fill in the lower half of the XXt matrix
for (i = 0; i < xOrder; i++) {
for (j = 0; j < i; j++) {
XXt[i][j] = XXt[j][i];
}
}
// Compute the eigenvectors and eigenvalues
jacobiN(XXt, xOrder, eigenvals, eigenvecs);
// Smallest eigenval is at the end of the list (xOrder-1), and solution is
// corresponding eigenvec.
for (i = 0; i < xOrder; i++) {
mt[i][0] = eigenvecs[i][xOrder - 1];
}
return 1;
}
function solveLeastSquares(numberOfSamples, xt, xOrder, yt, yOrder, mt) {
var checkHomogeneous = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : true;
// check dimensional consistency
if (numberOfSamples < xOrder || numberOfSamples < yOrder) {
vtkWarningMacro('Insufficient number of samples. Underdetermined.');
return 0;
}
var homogenFlags = createArray(yOrder);
var allHomogeneous = 1;
var hmt = void 0;
var homogRC = 0;
var i = void 0;
var j = void 0;
var k = void 0;
var someHomogeneous = 0;
// Ok, first init some flags check and see if all the systems are homogeneous
if (checkHomogeneous) {
// If Y' is zero, it's a homogeneous system and can't be solved via
// the pseudoinverse method. Detect this case, warn the user, and
// invoke SolveHomogeneousLeastSquares instead. Note that it doesn't
// really make much sense for yOrder to be greater than one in this case,
// since that's just yOrder occurrences of a 0 vector on the RHS, but
// we allow it anyway. N
// Initialize homogeneous flags on a per-right-hand-side basis
for (j = 0; j < yOrder; j++) {
homogenFlags[j] = 1;
}
for (i = 0; i < numberOfSamples; i++) {
for (j = 0; j < yOrder; j++) {
if (Math.abs(yt[i][j]) > VTK_SMALL_NUMBER) {
allHomogeneous = 0;
homogenFlags[j] = 0;
}
}
}
// If we've got one system, and it's homogeneous, do it and bail out quickly.
if (allHomogeneous && yOrder === 1) {
vtkWarningMacro('Detected homogeneous system (Y=0), calling SolveHomogeneousLeastSquares()');
return solveHomogeneousLeastSquares(numberOfSamples, xt, xOrder, mt);
}
// Ok, we've got more than one system of equations.
// Figure out if we need to calculate the homogeneous equation solution for
// any of them.
if (allHomogeneous) {
someHomogeneous = 1;
} else {
for (j = 0; j < yOrder; j++) {
if (homogenFlags[j]) {
someHomogeneous = 1;
}
}
}
}
// If necessary, solve the homogeneous problem
if (someHomogeneous) {
// hmt is the homogeneous equation version of mt, the general solution.
hmt = createArray(xOrder);
for (j = 0; j < xOrder; j++) {
// Only allocate 1 here, not yOrder, because here we're going to solve
// just the one homogeneous equation subset of the entire problem
hmt[j] = [0];
}
// Ok, solve the homogeneous problem
homogRC = solveHomogeneousLeastSquares(numberOfSamples, xt, xOrder, hmt);
}
// set up intermediate variables
var XXt = createArray(xOrder); // size x by x
var XXtI = createArray(xOrder); // size x by x
var XYt = createArray(xOrder); // size x by y
for (i = 0; i < xOrder; i++) {
XXt[i] = createArray(xOrder);
XXtI[i] = createArray(xOrder);
for (j = 0; j < xOrder; j++) {
XXt[i][j] = 0.0;
XXtI[i][j] = 0.0;
}
XYt[i] = createArray(yOrder);
for (j = 0; j < yOrder; j++) {
XYt[i][j] = 0.0;
}
}
// first find the pseudoinverse matrix
for (k = 0; k < numberOfSamples; k++) {
for (i = 0; i < xOrder; i++) {
// first calculate the XXt matrix, only do the upper half (symmetrical)
for (j = i; j < xOrder; j++) {
XXt[i][j] += xt[k][i] * xt[k][j];
}
// now calculate the XYt matrix
for (j = 0; j < yOrder; j++) {
XYt[i][j] += xt[k][i] * yt[k][j];
}
}
}
// now fill in the lower half of the XXt matrix
for (i = 0; i < xOrder; i++) {
for (j = 0; j < i; j++) {
XXt[i][j] = XXt[j][i];
}
}
var successFlag = invertMatrix(XXt, XXtI, xOrder);
// next get the inverse of XXt
if (successFlag) {
for (i = 0; i < xOrder; i++) {
for (j = 0; j < yOrder; j++) {
mt[i][j] = 0.0;
for (k = 0; k < xOrder; k++) {
mt[i][j] += XXtI[i][k] * XYt[k][j];
}
}
}
}
// Fix up any of the solutions that correspond to the homogeneous equation
// problem.
if (someHomogeneous) {
for (j = 0; j < yOrder; j++) {
if (homogenFlags[j]) {
// Fix this one
for (i = 0; i < xOrder; i++) {
mt[i][j] = hmt[i][0];
}
}
}
}
if (someHomogeneous) {
return homogRC && successFlag;
}
return successFlag;
}
function hex2float(hexStr) {
var outFloatArray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0, 0.5, 1];
switch (hexStr.length) {
case 3:
// abc => #aabbcc
outFloatArray[0] = parseInt(hexStr[0], 16) * 17 / 255;
outFloatArray[1] = parseInt(hexStr[1], 16) * 17 / 255;
outFloatArray[2] = parseInt(hexStr[2], 16) * 17 / 255;
return outFloatArray;
case 4:
// #abc => #aabbcc
outFloatArray[0] = parseInt(hexStr[1], 16) * 17 / 255;
outFloatArray[1] = parseInt(hexStr[2], 16) * 17 / 255;
outFloatArray[2] = parseInt(hexStr[3], 16) * 17 / 255;
return outFloatArray;
case 6:
// ab01df => #ab01df
outFloatArray[0] = parseInt(hexStr.substr(0, 2), 16) / 255;
outFloatArray[1] = parseInt(hexStr.substr(2, 2), 16) / 255;
outFloatArray[2] = parseInt(hexStr.substr(4, 2), 16) / 255;
return outFloatArray;
case 7:
// #ab01df
outFloatArray[0] = parseInt(hexStr.substr(1, 2), 16) / 255;
outFloatArray[1] = parseInt(hexStr.substr(3, 2), 16) / 255;
outFloatArray[2] = parseInt(hexStr.substr(5, 2), 16) / 255;
return outFloatArray;
case 9:
// #ab01df00
outFloatArray[0] = parseInt(hexStr.substr(1, 2), 16) / 255;
outFloatArray[1] = parseInt(hexStr.substr(3, 2), 16) / 255;
outFloatArray[2] = parseInt(hexStr.substr(5, 2), 16) / 255;
outFloatArray[3] = parseInt(hexStr.substr(7, 2), 16) / 255;
return outFloatArray;
default:
return outFloatArray;
}
}
function rgb2hsv(rgb, hsv) {
var h = void 0;
var s = void 0;
var _rgb = _slicedToArray(rgb, 3),
r = _rgb[0],
g = _rgb[1],
b = _rgb[2];
var onethird = 1.0 / 3.0;
var onesixth = 1.0 / 6.0;
var twothird = 2.0 / 3.0;
var cmax = r;
var cmin = r;
if (g > cmax) {
cmax = g;
} else if (g < cmin) {
cmin = g;
}
if (b > cmax) {
cmax = b;
} else if (b < cmin) {
cmin = b;
}
var v = cmax;
if (v > 0.0) {
s = (cmax - cmin) / cmax;
} else {
s = 0.0;
}
if (s > 0) {
if (r === cmax) {
h = onesixth * (g - b) / (cmax - cmin);
} else if (g === cmax) {
h = onethird + onesixth * (b - r) / (cmax - cmin);
} else {
h = twothird + onesixth * (r - g) / (cmax - cmin);
}
if (h < 0.0) {
h += 1.0;
}
} else {
h = 0.0;
}
// Set the values back to the array
hsv[0] = h;
hsv[1] = s;
hsv[2] = v;
}
function hsv2rgb(hsv, rgb) {
var _hsv = _slicedToArray(hsv, 3),
h = _hsv[0],
s = _hsv[1],
v = _hsv[2];
var onethird = 1.0 / 3.0;
var onesixth = 1.0 / 6.0;
var twothird = 2.0 / 3.0;
var fivesixth = 5.0 / 6.0;
var r = void 0;
var g = void 0;
var b = void 0;
// compute RGB from HSV
if (h > onesixth && h <= onethird) {
// green/red
g = 1.0;
r = (onethird - h) / onesixth;
b = 0.0;
} else if (h > onethird && h <= 0.5) {
// green/blue
g = 1.0;
b = (h - onethird) / onesixth;
r = 0.0;
} else if (h > 0.5 && h <= twothird) {
// blue/green
b = 1.0;
g = (twothird - h) / onesixth;
r = 0.0;
} else if (h > twothird && h <= fivesixth) {
// blue/red
b = 1.0;
r = (h - twothird) / onesixth;
g = 0.0;
} else if (h > fivesixth && h <= 1.0) {
// red/blue
r = 1.0;
b = (1.0 - h) / onesixth;
g = 0.0;
} else {
// red/green
r = 1.0;
g = h / onesixth;
b = 0.0;
}
// add Saturation to the equation.
r = s * r + (1.0 - s);
g = s * g + (1.0 - s);
b = s * b + (1.0 - s);
r *= v;
g *= v;
b *= v;
// Assign back to the array
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
}
function lab2xyz(lab, xyz) {
// LAB to XYZ
var _lab = _slicedToArray(lab, 3),
L = _lab[0],
a = _lab[1],
b = _lab[2];
var var_Y = (L + 16) / 116;
var var_X = a / 500 + var_Y;
var var_Z = var_Y - b / 200;
if (Math.pow(var_Y, 3) > 0.008856) {
var_Y = Math.pow(var_Y, 3);
} else {
var_Y = (var_Y - 16.0 / 116.0) / 7.787;
}
if (Math.pow(var_X, 3) > 0.008856) {
var_X = Math.pow(var_X, 3);
} else {
var_X = (var_X - 16.0 / 116.0) / 7.787;
}
if (Math.pow(var_Z, 3) > 0.008856) {
var_Z = Math.pow(var_Z, 3);
} else {
var_Z = (var_Z - 16.0 / 116.0) / 7.787;
}
var ref_X = 0.9505;
var ref_Y = 1.0;
var ref_Z = 1.089;
xyz[0] = ref_X * var_X; // ref_X = 0.9505 Observer= 2 deg Illuminant= D65
xyz[1] = ref_Y * var_Y; // ref_Y = 1.000
xyz[2] = ref_Z * var_Z; // ref_Z = 1.089
}
function xyz2lab(xyz, lab) {
var _xyz = _slicedToArray(xyz, 3),
x = _xyz[0],
y = _xyz[1],
z = _xyz[2];
var ref_X = 0.9505;
var ref_Y = 1.0;
var ref_Z = 1.089;
var var_X = x / ref_X; // ref_X = 0.9505 Observer= 2 deg, Illuminant= D65
var var_Y = y / ref_Y; // ref_Y = 1.000
var var_Z = z / ref_Z; // ref_Z = 1.089
if (var_X > 0.008856) {
var_X = Math.pow(var_X, 1.0 / 3.0);
} else var_X = 7.787 * var_X + 16.0 / 116.0;
if (var_Y > 0.008856) {
var_Y = Math.pow(var_Y, 1.0 / 3.0);
} else var_Y = 7.787 * var_Y + 16.0 / 116.0;
if (var_Z > 0.008856) {
var_Z = Math.pow(var_Z, 1.0 / 3.0);
} else var_Z = 7.787 * var_Z + 16.0 / 116.0;
lab[0] = 116 * var_Y - 16;
lab[1] = 500 * (var_X - var_Y);
lab[2] = 200 * (var_Y - var_Z);
}
function xyz2rgb(xyz, rgb) {
var _xyz2 = _slicedToArray(xyz, 3),
x = _xyz2[0],
y = _xyz2[1],
z = _xyz2[2];
var r = x * 3.2406 + y * -1.5372 + z * -0.4986;
var g = x * -0.9689 + y * 1.8758 + z * 0.0415;
var b = x * 0.0557 + y * -0.204 + z * 1.057;
// The following performs a "gamma correction" specified by the sRGB color
// space. sRGB is defined by a canonical definition of a display monitor and
// has been standardized by the International Electrotechnical Commission (IEC
// 61966-2-1). The nonlinearity of the correction is designed to make the
// colors more perceptually uniform. This color space has been adopted by
// several applications including Adobe Photoshop and Microsoft Windows color
// management. OpenGL is agnostic on its RGB color space, but it is reasonable
// to assume it is close to this one.
if (r > 0.0031308) r = 1.055 * Math.pow(r, 1 / 2.4) - 0.055;else r *= 12.92;
if (g > 0.0031308) g = 1.055 * Math.pow(g, 1 / 2.4) - 0.055;else g *= 12.92;
if (b > 0.0031308) b = 1.055 * Math.pow(b, 1 / 2.4) - 0.055;else b *= 12.92;
// Clip colors. ideally we would do something that is perceptually closest
// (since we can see colors outside of the display gamut), but this seems to
// work well enough.
var maxVal = r;
if (maxVal < g) maxVal = g;
if (maxVal < b) maxVal = b;
if (maxVal > 1.0) {
r /= maxVal;
g /= maxVal;
b /= maxVal;
}
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
// Push values back to array
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
}
function rgb2xyz(rgb, xyz) {
var _rgb2 = _slicedToArray(rgb, 3),
r = _rgb2[0],
g = _rgb2[1],
b = _rgb2[2];
// The following performs a "gamma correction" specified by the sRGB color
// space. sRGB is defined by a canonical definition of a display monitor and
// has been standardized by the International Electrotechnical Commission (IEC
// 61966-2-1). The nonlinearity of the correction is designed to make the
// colors more perceptually uniform. This color space has been adopted by
// several applications including Adobe Photoshop and Microsoft Windows color
// management. OpenGL is agnostic on its RGB color space, but it is reasonable
// to assume it is close to this one.
if (r > 0.04045) r = Math.pow((r + 0.055) / 1.055, 2.4);else r /= 12.92;
if (g > 0.04045) g = Math.pow((g + 0.055) / 1.055, 2.4);else g /= 12.92;
if (b > 0.04045) b = Math.pow((b + 0.055) / 1.055, 2.4);else b /= 12.92;
// Observer. = 2 deg, Illuminant = D65
xyz[0] = r * 0.4124 + g * 0.3576 + b * 0.1805;
xyz[1] = r * 0.2126 + g * 0.7152 + b * 0.0722;
xyz[2] = r * 0.0193 + g * 0.1192 + b * 0.9505;
}
function rgb2lab(rgb, lab) {
var xyz = [0, 0, 0];
rgb2xyz(rgb, xyz);
xyz2lab(xyz, lab);
}
function lab2rgb(lab, rgb) {
var xyz = [0, 0, 0];
lab2xyz(lab, xyz);
xyz2rgb(xyz, rgb);
}
function uninitializeBounds(bounds) {
bounds[0] = 1.0;
bounds[1] = -1.0;
bounds[2] = 1.0;
bounds[3] = -1.0;
bounds[4] = 1.0;
bounds[5] = -1.0;
}
function areBoundsInitialized(bounds) {
return !(bounds[1] - bounds[0] < 0.0);
}
function clampValue(value, minValue, maxValue) {
if (value < minValue) {
return minValue;
}
if (value > maxValue) {
return maxValue;
}
return value;
}
function clampAndNormalizeValue(value, range) {
var result = 0;
if (range[0] !== range[1]) {
// clamp
if (value < range[0]) {
result = range[0];
} else if (value > range[1]) {
result = range[1];
} else {
result = value;
}
// normalize
result = (result - range[0]) / (range[1] - range[0]);
}
return result;
}
var getScalarTypeFittingRange = notImplemented('GetScalarTypeFittingRange');
var getAdjustedScalarRange = notImplemented('GetAdjustedScalarRange');
function extentIsWithinOtherExtent(extent1, extent2) {
if (!extent1 || !extent2) {
return 0;
}
for (var i = 0; i < 6; i += 2) {
if (extent1[i] < extent2[i] || extent1[i] > extent2[i + 1] || extent1[i + 1] < extent2[i] || extent1[i + 1] > extent2[i + 1]) {
return 0;
}
}
return 1;
}
function boundsIsWithinOtherBounds(bounds1_6, bounds2_6, delta_3) {
if (!bounds1_6 || !bounds2_6) {
return 0;
}
for (var i = 0; i < 6; i += 2) {
if (bounds1_6[i] + delta_3[i / 2] < bounds2_6[i] || bounds1_6[i] - delta_3[i / 2] > bounds2_6[i + 1] || bounds1_6[i + 1] + delta_3[i / 2] < bounds2_6[i] || bounds1_6[i + 1] - delta_3[i / 2] > bounds2_6[i + 1]) {
return 0;
}
}
return 1;
}
function pointIsWithinBounds(point_3, bounds_6, delta_3) {
if (!point_3 || !bounds_6 || !delta_3) {
return 0;
}
for (var i = 0; i < 3; i++) {
if (point_3[i] + delta_3[i] < bounds_6[2 * i] || point_3[i] - delta_3[i] > bounds_6[2 * i + 1]) {
return 0;
}
}
return 1;
}
function solve3PointCircle(p1, p2, p3, center) {
var v21 = createArray(3);
var v32 = createArray(3);
var v13 = createArray(3);
var v12 = createArray(3);
var v23 = createArray(3);
var v31 = createArray(3);
for (var i = 0; i < 3; ++i) {
v21[i] = p1[i] - p2[i];
v32[i] = p2[i] - p3[i];
v13[i] = p3[i] - p1[i];
v12[i] = -v21[i];
v23[i] = -v32[i];
v31[i] = -v13[i];
}
var norm12 = norm(v12);
var norm23 = norm(v23);
var norm13 = norm(v13);
var crossv21v32 = createArray(3);
cross(v21, v32, crossv21v32);
var normCross = norm(crossv21v32);
var radius = norm12 * norm23 * norm13 / (2 * normCross);
var normCross22 = 2 * normCross * normCross;
var alpha = norm23 * norm23 * dot(v21, v31) / normCross22;
var beta = norm13 * norm13 * dot(v12, v32) / normCross22;
var gamma = norm12 * norm12 * dot(v13, v23) / normCross22;
for (var _i6 = 0; _i6 < 3; ++_i6) {
center[_i6] = alpha * p1[_i6] + beta * p2[_i6] + gamma * p3[_i6];
}
return radius;
}
var inf = Infinity;
var negInf = -Infinity;
var isInf = function isInf(value) {
return !Number.isFinite(value);
};
var isFinite = Number.isFinite,
isNaN = Number.isNaN;
// JavaScript - add-on ----------------------
function createUninitializedBounds() {
return [].concat([Number.MAX_VALUE, -Number.MAX_VALUE, // X
Number.MAX_VALUE, -Number.MAX_VALUE, // Y
Number.MAX_VALUE, -Number.MAX_VALUE] // Z
);
}
function getMajorAxisIndex(vector) {
var maxValue = -1;
var axisIndex = -1;
for (var i = 0; i < vector.length; i++) {
var value = Math.abs(vector[i]);
if (value > maxValue) {
axisIndex = i;
maxValue = value;
}
}
return axisIndex;
}
// ----------------------------------------------------------------------------
// Only Static API
// ----------------------------------------------------------------------------
exports.default = {
Pi: Pi,
radiansFromDegrees: radiansFromDegrees,
degreesFromRadians: degreesFromRadians,
round: round,
floor: floor,
ceil: ceil,
ceilLog2: ceilLog2,
min: min,
max: max,
arrayMin: arrayMin,
arrayMax: arrayMax,
isPowerOfTwo: isPowerOfTwo,
nearestPowerOfTwo: nearestPowerOfTwo,
factorial: factorial,
binomial: binomial,
beginCombination: beginCombination,
nextCombination: nextCombination,
randomSeed: randomSeed,
getSeed: getSeed,
random: random,
gaussian: gaussian,
add: add,
subtract: subtract,
multiplyScalar: multiplyScalar,
multiplyScalar2D: multiplyScalar2D,
dot: dot,
outer: outer,
cross: cross,
norm: norm,
normalize: normalize,
perpendiculars: perpendiculars,
projectVector: projectVector,
projectVector2D: projectVector2D,
distance2BetweenPoints: distance2BetweenPoints,
angleBetweenVectors: angleBetweenVectors,
gaussianAmplitude: gaussianAmplitude,
gaussianWeight: gaussianWeight,
dot2D: dot2D,
outer2D: outer2D,
norm2D: norm2D,
normalize2D: normalize2D,
determinant2x2: determinant2x2,
LUFactor3x3: LUFactor3x3,
LUSolve3x3: LUSolve3x3,
linearSolve3x3: linearSolve3x3,
multiply3x3_vect3: multiply3x3_vect3,
multiply3x3_mat3: multiply3x3_mat3,
multiplyMatrix: multiplyMatrix,
transpose3x3: transpose3x3,
invert3x3: invert3x3,
identity3x3: identity3x3,
determinant3x3: determinant3x3,
quaternionToMatrix3x3: quaternionToMatrix3x3,
areMatricesEqual: areMatricesEqual,
matrix3x3ToQuaternion: matrix3x3ToQuaternion,
multiplyQuaternion: multiplyQuaternion,
orthogonalize3x3: orthogonalize3x3,
diagonalize3x3: diagonalize3x3,
singularValueDecomposition3x3: singularValueDecomposition3x3,
solveLinearSystem: solveLinearSystem,
invertMatrix: invertMatrix,
luFactorLinearSystem: luFactorLinearSystem,
luSolveLinearSystem: luSolveLinearSystem,
estimateMatrixCondition: estimateMatrixCondition,
jacobi: jacobi,
jacobiN: jacobiN,
solveHomogeneousLeastSquares: solveHomogeneousLeastSquares,
solveLeastSquares: solveLeastSquares,
hex2float: hex2float,
rgb2hsv: rgb2hsv,
hsv2rgb: hsv2rgb,
lab2xyz: lab2xyz,
xyz2lab: xyz2lab,
xyz2rgb: xyz2rgb,
rgb2xyz: rgb2xyz,
rgb2lab: rgb2lab,
lab2rgb: lab2rgb,
uninitializeBounds: uninitializeBounds,
areBoundsInitialized: areBoundsInitialized,
clampValue: clampValue,
clampAndNormalizeValue: clampAndNormalizeValue,
getScalarTypeFittingRange: getScalarTypeFittingRange,
getAdjustedScalarRange: getAdjustedScalarRange,
extentIsWithinOtherExtent: extentIsWithinOtherExtent,
boundsIsWithinOtherBounds: boundsIsWithinOtherBounds,
pointIsWithinBounds: pointIsWithinBounds,
solve3PointCircle: solve3PointCircle,
inf: inf,
negInf: negInf,
isInf: isInf,
isNan: isNaN,
isNaN: isNaN,
isFinite: isFinite,
// JS add-on
createUninitializedBounds: createUninitializedBounds,
getMajorAxisIndex: getMajorAxisIndex
};
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var support = __webpack_require__(44);
var base64 = __webpack_require__(296);
var nodejsUtils = __webpack_require__(111);
var setImmediate = __webpack_require__(630);
var external = __webpack_require__(91);
/**
* Convert a string that pass as a "binary string": it should represent a byte
* array but may have > 255 char codes. Be sure to take only the first byte
* and returns the byte array.
* @param {String} str the string to transform.
* @return {Array|Uint8Array} the string in a binary format.
*/
function string2binary(str) {
var result = null;
if (support.uint8array) {
result = new Uint8Array(str.length);
} else {
result = new Array(str.length);
}
return stringToArrayLike(str, result);
}
/**
* Create a new blob with the given content and the given type.
* @param {Array[String|ArrayBuffer]} parts the content to put in the blob. DO NOT use
* an Uint8Array because the stock browser of android 4 won't accept it (it
* will be silently converted to a string, "[object Uint8Array]").
* @param {String} type the mime type of the blob.
* @return {Blob} the created blob.
*/
exports.newBlob = function(parts, type) {
exports.checkSupport("blob");
try {
// Blob constructor
return new Blob(parts, {
type: type
});
}
catch (e) {
try {
// deprecated, browser only, old way
var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i++) {
builder.append(parts[i]);
}
return builder.getBlob(type);
}
catch (e) {
// well, fuck ?!
throw new Error("Bug : can't construct the Blob.");
}
}
};
/**
* The identity function.
* @param {Object} input the input.
* @return {Object} the same input.
*/
function identity(input) {
return input;
}
/**
* Fill in an array with a string.
* @param {String} str the string to use.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
*/
function stringToArrayLike(str, array) {
for (var i = 0; i < str.length; ++i) {
array[i] = str.charCodeAt(i) & 0xFF;
}
return array;
}
/**
* An helper for the function arrayLikeToString.
* This contains static informations and functions that
* can be optimized by the browser JIT compiler.
*/
var arrayToStringHelper = {
/**
* Transform an array of int into a string, chunk by chunk.
* See the performances notes on arrayLikeToString.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @param {String} type the type of the array.
* @param {Integer} chunk the chunk size.
* @return {String} the resulting string.
* @throws Error if the chunk is too big for the stack.
*/
stringifyByChunk: function(array, type, chunk) {
var result = [], k = 0, len = array.length;
// shortcut
if (len <= chunk) {
return String.fromCharCode.apply(null, array);
}
while (k < len) {
if (type === "array" || type === "nodebuffer") {
result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
}
else {
result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
}
k += chunk;
}
return result.join("");
},
/**
* Call String.fromCharCode on every item in the array.
* This is the naive implementation, which generate A LOT of intermediate string.
* This should be used when everything else fail.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @return {String} the result.
*/
stringifyByChar: function(array){
var resultStr = "";
for(var i = 0; i < array.length; i++) {
resultStr += String.fromCharCode(array[i]);
}
return resultStr;
},
applyCanBeUsed : {
/**
* true if the browser accepts to use String.fromCharCode on Uint8Array
*/
uint8array : (function () {
try {
return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
} catch (e) {
return false;
}
})(),
/**
* true if the browser accepts to use String.fromCharCode on nodejs Buffer.
*/
nodebuffer : (function () {
try {
return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.newBuffer(1)).length === 1;
} catch (e) {
return false;
}
})()
}
};
/**
* Transform an array-like object to a string.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @return {String} the result.
*/
function arrayLikeToString(array) {
// Performances notes :
// --------------------
// String.fromCharCode.apply(null, array) is the fastest, see
// see http://jsperf.com/converting-a-uint8array-to-a-string/2
// but the stack is limited (and we can get huge arrays !).
//
// result += String.fromCharCode(array[i]); generate too many strings !
//
// This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
// TODO : we now have workers that split the work. Do we still need that ?
var chunk = 65536,
type = exports.getTypeOf(array),
canUseApply = true;
if (type === "uint8array") {
canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
} else if (type === "nodebuffer") {
canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
}
if (canUseApply) {
while (chunk > 1) {
try {
return arrayToStringHelper.stringifyByChunk(array, type, chunk);
} catch (e) {
chunk = Math.floor(chunk / 2);
}
}
}
// no apply or chunk error : slow and painful algorithm
// default browser on android 4.*
return arrayToStringHelper.stringifyByChar(array);
}
exports.applyFromCharCode = arrayLikeToString;
/**
* Copy the data from an array-like to an other array-like.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
*/
function arrayLikeToArrayLike(arrayFrom, arrayTo) {
for (var i = 0; i < arrayFrom.length; i++) {
arrayTo[i] = arrayFrom[i];
}
return arrayTo;
}
// a matrix containing functions to transform everything into everything.
var transform = {};
// string to ?
transform["string"] = {
"string": identity,
"array": function(input) {
return stringToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return transform["string"]["uint8array"](input).buffer;
},
"uint8array": function(input) {
return stringToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": function(input) {
return stringToArrayLike(input, nodejsUtils.newBuffer(input.length));
}
};
// array to ?
transform["array"] = {
"string": arrayLikeToString,
"array": identity,
"arraybuffer": function(input) {
return (new Uint8Array(input)).buffer;
},
"uint8array": function(input) {
return new Uint8Array(input);
},
"nodebuffer": function(input) {
return nodejsUtils.newBuffer(input);
}
};
// arraybuffer to ?
transform["arraybuffer"] = {
"string": function(input) {
return arrayLikeToString(new Uint8Array(input));
},
"array": function(input) {
return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
},
"arraybuffer": identity,
"uint8array": function(input) {
return new Uint8Array(input);
},
"nodebuffer": function(input) {
return nodejsUtils.newBuffer(new Uint8Array(input));
}
};
// uint8array to ?
transform["uint8array"] = {
"string": arrayLikeToString,
"array": function(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
// copy the uint8array: DO NOT propagate the original ArrayBuffer, it
// can be way larger (the whole zip file for example).
var copy = new Uint8Array(input.length);
if (input.length) {
copy.set(input, 0);
}
return copy.buffer;
},
"uint8array": identity,
"nodebuffer": function(input) {
return nodejsUtils.newBuffer(input);
}
};
// nodebuffer to ?
transform["nodebuffer"] = {
"string": arrayLikeToString,
"array": function(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return transform["nodebuffer"]["uint8array"](input).buffer;
},
"uint8array": function(input) {
return arrayLikeToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": identity
};
/**
* Transform an input into any type.
* The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
* If no output type is specified, the unmodified input will be returned.
* @param {String} outputType the output type.
* @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
* @throws {Error} an Error if the browser doesn't support the requested output type.
*/
exports.transformTo = function(outputType, input) {
if (!input) {
// undefined, null, etc
// an empty string won't harm.
input = "";
}
if (!outputType) {
return input;
}
exports.checkSupport(outputType);
var inputType = exports.getTypeOf(input);
var result = transform[inputType][outputType](input);
return result;
};
/**
* Return the type of the input.
* The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
* @param {Object} input the input to identify.
* @return {String} the (lowercase) type of the input.
*/
exports.getTypeOf = function(input) {
if (typeof input === "string") {
return "string";
}
if (Object.prototype.toString.call(input) === "[object Array]") {
return "array";
}
if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
return "nodebuffer";
}
if (support.uint8array && input instanceof Uint8Array) {
return "uint8array";
}
if (support.arraybuffer && input instanceof ArrayBuffer) {
return "arraybuffer";
}
};
/**
* Throw an exception if the type is not supported.
* @param {String} type the type to check.
* @throws {Error} an Error if the browser doesn't support the requested type.
*/
exports.checkSupport = function(type) {
var supported = support[type.toLowerCase()];
if (!supported) {
throw new Error(type + " is not supported by this platform");
}
};
exports.MAX_VALUE_16BITS = 65535;
exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
/**
* Prettify a string read as binary.
* @param {string} str the string to prettify.
* @return {string} a pretty string.
*/
exports.pretty = function(str) {
var res = '',
code, i;
for (i = 0; i < (str || "").length; i++) {
code = str.charCodeAt(i);
res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
}
return res;
};
/**
* Defer the call of a function.
* @param {Function} callback the function to call asynchronously.
* @param {Array} args the arguments to give to the callback.
*/
exports.delay = function(callback, args, self) {
setImmediate(function () {
callback.apply(self || null, args || []);
});
};
/**
* Extends a prototype with an other, without calling a constructor with
* side effects. Inspired by nodejs' `utils.inherits`
* @param {Function} ctor the constructor to augment
* @param {Function} superCtor the parent constructor to use
*/
exports.inherits = function (ctor, superCtor) {
var Obj = function() {};
Obj.prototype = superCtor.prototype;
ctor.prototype = new Obj();
};
/**
* Merge the objects passed as parameters into a new one.
* @private
* @param {...Object} var_args All objects to merge.
* @return {Object} a new object with the data of the others.
*/
exports.extend = function() {
var result = {}, i, attr;
for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
for (attr in arguments[i]) {
if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
result[attr] = arguments[i][attr];
}
}
}
return result;
};
/**
* Transform arbitrary content into a Promise.
* @param {String} name a name for the content being processed.
* @param {Object} inputData the content to process.
* @param {Boolean} isBinary true if the content is not an unicode string
* @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
* @param {Boolean} isBase64 true if the string content is encoded with base64.
* @return {Promise} a promise in a format usable by JSZip.
*/
exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
// if inputData is already a promise, this flatten it.
var promise = external.Promise.resolve(inputData).then(function(data) {
var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
if (isBlob && typeof FileReader !== "undefined") {
return new external.Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function(e) {
resolve(e.target.result);
};
reader.onerror = function(e) {
reject(e.target.error);
};
reader.readAsArrayBuffer(data);
});
} else {
return data;
}
});
return promise.then(function(data) {
var dataType = exports.getTypeOf(data);
if (!dataType) {
return external.Promise.reject(
new Error("The data of '" + name + "' is in an unsupported format !")
);
}
// special case : it's way easier to work with Uint8Array than with ArrayBuffer
if (dataType === "arraybuffer") {
data = exports.transformTo("uint8array", data);
} else if (dataType === "string") {
if (isBase64) {
data = base64.decode(data);
}
else if (isBinary) {
// optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
if (isOptimizedBinaryString !== true) {
// this is a string, not in a base64 format.
// Be sure that this is a correct "binary string"
data = string2binary(data);
}
}
}
return data;
});
};
/***/ }),
/* 12 */,
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.vec4 = exports.vec3 = exports.vec2 = exports.quat2 = exports.quat = exports.mat4 = exports.mat3 = exports.mat2d = exports.mat2 = exports.glMatrix = undefined;
var _common = __webpack_require__(36);
var glMatrix = _interopRequireWildcard(_common);
var _mat = __webpack_require__(539);
var mat2 = _interopRequireWildcard(_mat);
var _mat2d = __webpack_require__(540);
var mat2d = _interopRequireWildcard(_mat2d);
var _mat2 = __webpack_require__(266);
var mat3 = _interopRequireWildcard(_mat2);
var _mat3 = __webpack_require__(267);
var mat4 = _interopRequireWildcard(_mat3);
var _quat = __webpack_require__(268);
var quat = _interopRequireWildcard(_quat);
var _quat2 = __webpack_require__(541);
var quat2 = _interopRequireWildcard(_quat2);
var _vec = __webpack_require__(542);
var vec2 = _interopRequireWildcard(_vec);
var _vec2 = __webpack_require__(269);
var vec3 = _interopRequireWildcard(_vec2);
var _vec3 = __webpack_require__(270);
var vec4 = _interopRequireWildcard(_vec3);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* @fileoverview gl-matrix - High performance matrix and vector operations
* @author Brandon Jones
* @author Colin MacKenzie IV
* @version 2.4.0
*/
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
// END HEADER
exports.glMatrix = glMatrix;
exports.mat2 = mat2;
exports.mat2d = mat2d;
exports.mat3 = mat3;
exports.mat4 = mat4;
exports.quat = quat;
exports.quat2 = quat2;
exports.vec2 = vec2;
exports.vec3 = vec3;
exports.vec4 = vec4;
/***/ }),
/* 14 */,
/* 15 */,
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = exports.STATIC = undefined;
exports.extend = extend;
var _Constants = __webpack_require__(32);
var _Constants2 = _interopRequireDefault(_Constants);
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Math = __webpack_require__(10);
var _Math2 = _interopRequireDefault(_Math);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DefaultDataType = _Constants2.default.DefaultDataType;
var TUPLE_HOLDER = [];
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
function createRangeHelper() {
var min = Number.MAX_VALUE;
var max = -Number.MAX_VALUE;
var count = 0;
var sum = 0;
return {
add: function add(value) {
if (min > value) {
min = value;
}
if (max < value) {
max = value;
}
count++;
sum += value;
},
get: function get() {
return { min: min, max: max, count: count, sum: sum, mean: sum / count };
},
getRange: function getRange() {
return { min: min, max: max };
}
};
}
function computeRange(values) {
var component = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var numberOfComponents = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
var helper = createRangeHelper();
var size = values.length;
var value = 0;
if (component < 0 && numberOfComponents > 1) {
// Compute magnitude
for (var i = 0; i < size; i += numberOfComponents) {
value = 0;
for (var j = 0; j < numberOfComponents; j++) {
value += values[i + j] * values[i + j];
}
value = Math.pow(value, 0.5);
helper.add(value);
}
return helper.getRange();
}
var offset = component < 0 ? 0 : component;
for (var _i = offset; _i < size; _i += numberOfComponents) {
helper.add(values[_i]);
}
return helper.getRange();
}
function ensureRangeSize(rangeArray) {
var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var ranges = rangeArray || [];
// Pad ranges with null value to get the
while (ranges.length <= size) {
ranges.push(null);
}
return ranges;
}
function getDataType(typedArray) {
return Object.prototype.toString.call(typedArray).split(' ')[1].slice(0, -1);
}
function getMaxNorm(normArray) {
var numComps = normArray.getNumberOfComponents();
var maxNorm = 0.0;
for (var i = 0; i < normArray.getNumberOfTuples(); ++i) {
var norm = _Math2.default.norm(normArray.getTuple(i), numComps);
if (norm > maxNorm) {
maxNorm = norm;
}
}
return maxNorm;
}
// ----------------------------------------------------------------------------
// Static API
// ----------------------------------------------------------------------------
var STATIC = exports.STATIC = {
computeRange: computeRange,
createRangeHelper: createRangeHelper,
getDataType: getDataType,
getMaxNorm: getMaxNorm
};
// ----------------------------------------------------------------------------
// vtkDataArray methods
// ----------------------------------------------------------------------------
function vtkDataArray(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkDataArray');
function dataChange() {
model.ranges = null;
publicAPI.modified();
}
publicAPI.getElementComponentSize = function () {
return model.values.BYTES_PER_ELEMENT;
};
// Description:
// Return the data component at the location specified by tupleIdx and
// compIdx.
publicAPI.getComponent = function (tupleIdx) {
var compIdx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return model.values[tupleIdx * model.numberOfComponents + compIdx];
};
// Description:
// Set the data component at the location specified by tupleIdx and compIdx
// to value.
// Note that i is less than NumberOfTuples and j is less than
// NumberOfComponents. Make sure enough memory has been allocated
// (use SetNumberOfTuples() and SetNumberOfComponents()).
publicAPI.setComponent = function (tupleIdx, compIdx, value) {
if (value !== model.values[tupleIdx * model.numberOfComponents + compIdx]) {
model.values[tupleIdx * model.numberOfComponents + compIdx] = value;
dataChange();
}
};
publicAPI.getData = function () {
return model.values;
};
publicAPI.getRange = function () {
var componentIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
var rangeIdx = componentIndex < 0 ? model.numberOfComponents : componentIndex;
var range = null;
if (!model.ranges) {
model.ranges = ensureRangeSize(model.ranges, model.numberOfComponents);
}
range = model.ranges[rangeIdx];
if (range) {
model.rangeTuple[0] = range.min;
model.rangeTuple[1] = range.max;
return model.rangeTuple;
}
// Need to compute ranges...
range = computeRange(model.values, componentIndex, model.numberOfComponents);
model.ranges[rangeIdx] = range;
model.rangeTuple[0] = range.min;
model.rangeTuple[1] = range.max;
return model.rangeTuple;
};
publicAPI.setTuple = function (idx, tuple) {
var offset = idx * model.numberOfComponents;
for (var i = 0; i < model.numberOfComponents; i++) {
model.values[offset + i] = tuple[i];
}
};
publicAPI.getTuple = function (idx) {
var tupleToFill = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : TUPLE_HOLDER;
var numberOfComponents = model.numberOfComponents || 1;
if (tupleToFill.length !== numberOfComponents) {
tupleToFill.length = numberOfComponents;
}
var offset = idx * numberOfComponents;
// Check most common component sizes first
// to avoid doing a for loop if possible
if (numberOfComponents === 1) {
tupleToFill[0] = model.values[offset];
} else if (numberOfComponents === 2) {
tupleToFill[0] = model.values[offset];
tupleToFill[1] = model.values[offset + 1];
} else if (numberOfComponents === 3) {
tupleToFill[0] = model.values[offset];
tupleToFill[1] = model.values[offset + 1];
tupleToFill[2] = model.values[offset + 2];
} else if (numberOfComponents === 4) {
tupleToFill[0] = model.values[offset];
tupleToFill[1] = model.values[offset + 1];
tupleToFill[2] = model.values[offset + 2];
tupleToFill[3] = model.values[offset + 3];
} else {
for (var i = 0; i < numberOfComponents; i++) {
tupleToFill[i] = model.values[offset + i];
}
}
return tupleToFill;
};
publicAPI.getTupleLocation = function () {
var idx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return idx * model.numberOfComponents;
};
publicAPI.getNumberOfComponents = function () {
return model.numberOfComponents;
};
publicAPI.getNumberOfValues = function () {
return model.values.length;
};
publicAPI.getNumberOfTuples = function () {
return model.values.length / model.numberOfComponents;
};
publicAPI.getDataType = function () {
return model.dataType;
};
/* eslint-disable no-use-before-define */
publicAPI.newClone = function () {
return newInstance({
empty: true,
name: model.name,
dataType: model.dataType,
numberOfComponents: model.numberOfComponents
});
};
/* eslint-enable no-use-before-define */
publicAPI.getName = function () {
if (!model.name) {
publicAPI.modified();
model.name = 'vtkDataArray' + publicAPI.getMTime();
}
return model.name;
};
publicAPI.setData = function (typedArray, numberOfComponents) {
model.values = typedArray;
model.size = typedArray.length;
model.dataType = getDataType(typedArray);
if (numberOfComponents) {
model.numberOfComponents = numberOfComponents;
}
if (model.size % model.numberOfComponents !== 0) {
model.numberOfComponents = 1;
}
dataChange();
};
/* eslint-disable no-use-before-define */
publicAPI.shallowCopy = function () {
return newInstance(Object.assign({}, model));
};
/* eslint-enable no-use-before-define */
// Override serialization support
publicAPI.getState = function () {
var jsonArchive = Object.assign({}, model, {
vtkClass: publicAPI.getClassName()
});
// Convert typed array to regular array
jsonArchive.values = Array.from(jsonArchive.values);
delete jsonArchive.buffer;
// Clean any empty data
Object.keys(jsonArchive).forEach(function (keyName) {
if (!jsonArchive[keyName]) {
delete jsonArchive[keyName];
}
});
// Sort resulting object by key name
var sortedObj = {};
Object.keys(jsonArchive).sort().forEach(function (name) {
sortedObj[name] = jsonArchive[name];
});
// Remove mtime
if (sortedObj.mtime) {
delete sortedObj.mtime;
}
return sortedObj;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
name: '',
numberOfComponents: 1,
size: 0,
dataType: DefaultDataType,
rangeTuple: [0, 0]
// values: null,
// ranges: null,
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
if (!model.empty && !model.values && !model.size) {
throw new TypeError('Cannot create vtkDataArray object without: size > 0, values');
}
if (!model.values) {
model.values = new window[model.dataType](model.size);
} else if (Array.isArray(model.values)) {
model.values = window[model.dataType].from(model.values);
}
if (model.values) {
model.size = model.values.length;
model.dataType = getDataType(model.values);
}
// Object methods
_macro2.default.obj(publicAPI, model);
_macro2.default.set(publicAPI, model, ['name', 'numberOfComponents']);
// Object specific methods
vtkDataArray(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkDataArray');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, STATIC, _Constants2.default);
/***/ }),
/* 17 */,
/* 18 */,
/* 19 */,
/* 20 */,
/* 21 */,
/* 22 */,
/* 23 */,
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var vtkErrorMacro = _macro2.default.vtkErrorMacro;
var PASS_TYPES = ['Build', 'Render'];
// ----------------------------------------------------------------------------
// vtkViewNode methods
// ----------------------------------------------------------------------------
function vtkViewNode(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkViewNode');
// Builds myself.
publicAPI.build = function (prepass) {};
// Renders myself
publicAPI.render = function (prepass) {};
publicAPI.traverse = function (renderPass) {
// we can choose to do special
// traversal here based on pass
var passTraversal = renderPass.getTraverseOperation();
var fn = publicAPI[passTraversal];
if (fn) {
fn(renderPass);
return;
}
// default traversal
publicAPI.apply(renderPass, true);
for (var index = 0; index < model.children.length; index++) {
model.children[index].traverse(renderPass);
}
publicAPI.apply(renderPass, false);
};
publicAPI.apply = function (renderPass, prepass) {
var customRenderPass = publicAPI[renderPass.getOperation()];
if (customRenderPass) {
customRenderPass(prepass, renderPass);
}
};
publicAPI.getViewNodeFor = function (dataObject) {
if (model.renderable === dataObject) {
return publicAPI;
}
for (var index = 0; index < model.children.length; ++index) {
var child = model.children[index];
var vn = child.getViewNodeFor(dataObject);
if (vn) {
return vn;
}
}
return undefined;
};
publicAPI.getFirstAncestorOfType = function (type) {
if (!model.parent) {
return null;
}
if (model.parent.isA(type)) {
return model.parent;
}
return model.parent.getFirstAncestorOfType(type);
};
publicAPI.addMissingNode = function (dobj) {
if (!dobj) {
return;
}
var result = model.renderableChildMap.get(dobj);
// if found just mark as visited
if (result !== undefined) {
result.setVisited(true);
} else {
// otherwise create a node
var newNode = publicAPI.createViewNode(dobj);
if (newNode) {
newNode.setParent(publicAPI);
newNode.setVisited(true);
model.renderableChildMap.set(dobj, newNode);
model.children.push(newNode);
}
}
};
publicAPI.addMissingNodes = function (dataObjs) {
if (!dataObjs || !dataObjs.length) {
return;
}
for (var index = 0; index < dataObjs.length; ++index) {
var dobj = dataObjs[index];
var result = model.renderableChildMap.get(dobj);
// if found just mark as visited
if (result !== undefined) {
result.setVisited(true);
} else {
// otherwise create a node
var newNode = publicAPI.createViewNode(dobj);
if (newNode) {
newNode.setParent(publicAPI);
newNode.setVisited(true);
model.renderableChildMap.set(dobj, newNode);
model.children.push(newNode);
}
}
}
};
publicAPI.prepareNodes = function () {
for (var index = 0; index < model.children.length; ++index) {
model.children[index].setVisited(false);
}
};
publicAPI.setVisited = function (val) {
model.visited = val;
};
publicAPI.removeUnusedNodes = function () {
var deleted = null;
for (var index = 0; index < model.children.length; ++index) {
var child = model.children[index];
var visited = child.getVisited();
if (!visited) {
var renderable = child.getRenderable();
if (renderable) {
model.renderableChildMap.delete(renderable);
}
if (!deleted) {
deleted = [];
}
deleted.push(child);
} else {
child.setVisited(false);
}
}
if (deleted) {
// slow does alloc but not as common
model.children = model.children.filter(function (el) {
return !deleted.includes(el);
});
}
};
publicAPI.createViewNode = function (dataObj) {
if (!model.myFactory) {
vtkErrorMacro('Cannot create view nodes without my own factory');
return null;
}
var ret = model.myFactory.createNode(dataObj);
if (ret) {
ret.setRenderable(dataObj);
}
return ret;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
parent: null,
renderable: null,
myFactory: null,
children: [],
visited: false
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
_macro2.default.obj(publicAPI, model);
_macro2.default.event(publicAPI, model, 'event');
model.renderableChildMap = new Map();
_macro2.default.get(publicAPI, model, ['visited']);
_macro2.default.setGet(publicAPI, model, ['parent', 'renderable', 'myFactory']);
_macro2.default.getArray(publicAPI, model, ['children']);
// Object methods
vtkViewNode(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = _macro2.default.newInstance(extend, 'vtkViewNode');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend, PASS_TYPES: PASS_TYPES };
/***/ }),
/* 25 */,
/* 26 */,
/* 27 */,
/* 28 */
/***/ (function(module, exports) {
module.exports = function() {
throw new Error("define cannot be used indirect");
};
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* A worker that does nothing but passing chunks to the next one. This is like
* a nodejs stream but with some differences. On the good side :
* - it works on IE 6-9 without any issue / polyfill
* - it weights less than the full dependencies bundled with browserify
* - it forwards errors (no need to declare an error handler EVERYWHERE)
*
* A chunk is an object with 2 attributes : `meta` and `data`. The former is an
* object containing anything (`percent` for example), see each worker for more
* details. The latter is the real data (String, Uint8Array, etc).
*
* @constructor
* @param {String} name the name of the stream (mainly used for debugging purposes)
*/
function GenericWorker(name) {
// the name of the worker
this.name = name || "default";
// an object containing metadata about the workers chain
this.streamInfo = {};
// an error which happened when the worker was paused
this.generatedError = null;
// an object containing metadata to be merged by this worker into the general metadata
this.extraStreamInfo = {};
// true if the stream is paused (and should not do anything), false otherwise
this.isPaused = true;
// true if the stream is finished (and should not do anything), false otherwise
this.isFinished = false;
// true if the stream is locked to prevent further structure updates (pipe), false otherwise
this.isLocked = false;
// the event listeners
this._listeners = {
'data':[],
'end':[],
'error':[]
};
// the previous worker, if any
this.previous = null;
}
GenericWorker.prototype = {
/**
* Push a chunk to the next workers.
* @param {Object} chunk the chunk to push
*/
push : function (chunk) {
this.emit("data", chunk);
},
/**
* End the stream.
* @return {Boolean} true if this call ended the worker, false otherwise.
*/
end : function () {
if (this.isFinished) {
return false;
}
this.flush();
try {
this.emit("end");
this.cleanUp();
this.isFinished = true;
} catch (e) {
this.emit("error", e);
}
return true;
},
/**
* End the stream with an error.
* @param {Error} e the error which caused the premature end.
* @return {Boolean} true if this call ended the worker with an error, false otherwise.
*/
error : function (e) {
if (this.isFinished) {
return false;
}
if(this.isPaused) {
this.generatedError = e;
} else {
this.isFinished = true;
this.emit("error", e);
// in the workers chain exploded in the middle of the chain,
// the error event will go downward but we also need to notify
// workers upward that there has been an error.
if(this.previous) {
this.previous.error(e);
}
this.cleanUp();
}
return true;
},
/**
* Add a callback on an event.
* @param {String} name the name of the event (data, end, error)
* @param {Function} listener the function to call when the event is triggered
* @return {GenericWorker} the current object for chainability
*/
on : function (name, listener) {
this._listeners[name].push(listener);
return this;
},
/**
* Clean any references when a worker is ending.
*/
cleanUp : function () {
this.streamInfo = this.generatedError = this.extraStreamInfo = null;
this._listeners = [];
},
/**
* Trigger an event. This will call registered callback with the provided arg.
* @param {String} name the name of the event (data, end, error)
* @param {Object} arg the argument to call the callback with.
*/
emit : function (name, arg) {
if (this._listeners[name]) {
for(var i = 0; i < this._listeners[name].length; i++) {
this._listeners[name][i].call(this, arg);
}
}
},
/**
* Chain a worker with an other.
* @param {Worker} next the worker receiving events from the current one.
* @return {worker} the next worker for chainability
*/
pipe : function (next) {
return next.registerPrevious(this);
},
/**
* Same as `pipe` in the other direction.
* Using an API with `pipe(next)` is very easy.
* Implementing the API with the point of view of the next one registering
* a source is easier, see the ZipFileWorker.
* @param {Worker} previous the previous worker, sending events to this one
* @return {Worker} the current worker for chainability
*/
registerPrevious : function (previous) {
if (this.isLocked) {
throw new Error("The stream '" + this + "' has already been used.");
}
// sharing the streamInfo...
this.streamInfo = previous.streamInfo;
// ... and adding our own bits
this.mergeStreamInfo();
this.previous = previous;
var self = this;
previous.on('data', function (chunk) {
self.processChunk(chunk);
});
previous.on('end', function () {
self.end();
});
previous.on('error', function (e) {
self.error(e);
});
return this;
},
/**
* Pause the stream so it doesn't send events anymore.
* @return {Boolean} true if this call paused the worker, false otherwise.
*/
pause : function () {
if(this.isPaused || this.isFinished) {
return false;
}
this.isPaused = true;
if(this.previous) {
this.previous.pause();
}
return true;
},
/**
* Resume a paused stream.
* @return {Boolean} true if this call resumed the worker, false otherwise.
*/
resume : function () {
if(!this.isPaused || this.isFinished) {
return false;
}
this.isPaused = false;
// if true, the worker tried to resume but failed
var withError = false;
if(this.generatedError) {
this.error(this.generatedError);
withError = true;
}
if(this.previous) {
this.previous.resume();
}
return !withError;
},
/**
* Flush any remaining bytes as the stream is ending.
*/
flush : function () {},
/**
* Process a chunk. This is usually the method overridden.
* @param {Object} chunk the chunk to process.
*/
processChunk : function(chunk) {
this.push(chunk);
},
/**
* Add a key/value to be added in the workers chain streamInfo once activated.
* @param {String} key the key to use
* @param {Object} value the associated value
* @return {Worker} the current worker for chainability
*/
withStreamInfo : function (key, value) {
this.extraStreamInfo[key] = value;
this.mergeStreamInfo();
return this;
},
/**
* Merge this worker's streamInfo into the chain's streamInfo.
*/
mergeStreamInfo : function () {
for(var key in this.extraStreamInfo) {
if (!this.extraStreamInfo.hasOwnProperty(key)) {
continue;
}
this.streamInfo[key] = this.extraStreamInfo[key];
}
},
/**
* Lock the stream to prevent further updates on the workers chain.
* After calling this method, all calls to pipe will fail.
*/
lock: function () {
if (this.isLocked) {
throw new Error("The stream '" + this + "' has already been used.");
}
this.isLocked = true;
if (this.previous) {
this.previous.lock();
}
},
/**
*
* Pretty print the workers chain.
*/
toString : function () {
var me = "Worker " + this.name;
if (this.previous) {
return this.previous + " -> " + me;
} else {
return me;
}
}
};
module.exports = GenericWorker;
/***/ }),
/* 30 */,
/* 31 */,
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var DataTypeByteSize = exports.DataTypeByteSize = {
Int8Array: 1,
Uint8Array: 1,
Uint8ClampedArray: 1,
Int16Array: 2,
Uint16Array: 2,
Int32Array: 4,
Uint32Array: 4,
Float32Array: 4,
Float64Array: 8
};
var VtkDataTypes = exports.VtkDataTypes = {
VOID: '', // not sure to know what that shoud be
CHAR: 'Int8Array',
SIGNED_CHAR: 'Int8Array',
UNSIGNED_CHAR: 'Uint8Array',
SHORT: 'Int16Array',
UNSIGNED_SHORT: 'Uint16Array',
INT: 'Int32Array',
UNSIGNED_INT: 'Uint32Array',
FLOAT: 'Float32Array',
DOUBLE: 'Float64Array'
};
var DefaultDataType = exports.DefaultDataType = VtkDataTypes.FLOAT;
exports.default = {
DefaultDataType: DefaultDataType,
DataTypeByteSize: DataTypeByteSize,
VtkDataTypes: VtkDataTypes
};
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _vtk = __webpack_require__(63);
var _vtk2 = _interopRequireDefault(_vtk);
var _CellArray = __webpack_require__(601);
var _CellArray2 = _interopRequireDefault(_CellArray);
var _PointSet = __webpack_require__(602);
var _PointSet2 = _interopRequireDefault(_PointSet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var POLYDATA_FIELDS = ['verts', 'lines', 'polys', 'strips'];
// ----------------------------------------------------------------------------
// vtkPolyData methods
// ----------------------------------------------------------------------------
function vtkPolyData(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkPolyData');
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (letter) {
return letter.toUpperCase();
}).replace(/\s+/g, '');
}
// build empty cell arrays and set methods
POLYDATA_FIELDS.forEach(function (type) {
publicAPI['getNumberOf' + camelize(type)] = function () {
return model[type].getNumberOfCells();
};
if (!model[type]) {
model[type] = _CellArray2.default.newInstance();
} else {
model[type] = (0, _vtk2.default)(model[type]);
}
});
publicAPI.getNumberOfCells = function () {
return POLYDATA_FIELDS.reduce(function (num, cellType) {
return num + model[cellType].getNumberOfCells();
}, 0);
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
// verts: null,
// lines: null,
// polys: null,
// strips: null,
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
_PointSet2.default.extend(publicAPI, model, initialValues);
_macro2.default.setGet(publicAPI, model, ['verts', 'lines', 'polys', 'strips']);
// Object specific methods
vtkPolyData(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkPolyData');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 34 */,
/* 35 */,
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setMatrixArrayType = setMatrixArrayType;
exports.toRadian = toRadian;
exports.equals = equals;
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
/**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
var EPSILON = exports.EPSILON = 0.000001;
var ARRAY_TYPE = exports.ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
var RANDOM = exports.RANDOM = Math.random;
/**
* Sets the type of array used when creating new vectors and matrices
*
* @param {Type} type Array type, such as Float32Array or Array
*/
function setMatrixArrayType(type) {
exports.ARRAY_TYPE = ARRAY_TYPE = type;
}
var degree = Math.PI / 180;
/**
* Convert Degree To Radian
*
* @param {Number} a Angle in Degrees
*/
function toRadian(a) {
return a * degree;
}
/**
* Tests whether or not the arguments have approximately the same value, within an absolute
* or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
* than or equal to 1.0, and a relative tolerance is used for larger values)
*
* @param {Number} a The first number to test.
* @param {Number} b The second number to test.
* @returns {Boolean} True if the numbers are approximately equal, false otherwise.
*/
function equals(a, b) {
return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
}
/***/ }),
/* 37 */,
/* 38 */,
/* 39 */,
/* 40 */,
/* 41 */,
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Shader = __webpack_require__(565);
var _Shader2 = _interopRequireDefault(_Shader);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var vtkErrorMacro = _macro2.default.vtkErrorMacro;
// perform in place string substitutions, indicate if a substitution was done
// this is useful for building up shader strings which typically involve
// lots of string substitutions. Return true if a substitution was done.
function substitute(source, search, replace) {
var all = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var replaceStr = Array.isArray(replace) ? replace.join('\n') : replace;
var replaced = false;
if (source.search(search) !== -1) {
replaced = true;
}
var gflag = '';
if (all) {
gflag = 'g';
}
var regex = new RegExp(search, gflag);
var resultstr = source.replace(regex, replaceStr);
return { replace: replaced, result: resultstr };
}
// ----------------------------------------------------------------------------
// vtkShaderProgram methods
// ----------------------------------------------------------------------------
function vtkShaderProgram(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkShaderProgram');
publicAPI.compileShader = function () {
if (!model.vertexShader.compile()) {
vtkErrorMacro(model.vertexShader.getSource().split('\n').map(function (line, index) {
return index + ': ' + line;
}).join('\n'));
vtkErrorMacro(model.vertexShader.getError());
return 0;
}
if (!model.fragmentShader.compile()) {
vtkErrorMacro(model.fragmentShader.getSource().split('\n').map(function (line, index) {
return index + ': ' + line;
}).join('\n'));
vtkErrorMacro(model.fragmentShader.getError());
return 0;
}
// skip geometry for now
if (!publicAPI.attachShader(model.vertexShader)) {
vtkErrorMacro(model.error);
return 0;
}
if (!publicAPI.attachShader(model.fragmentShader)) {
vtkErrorMacro(model.error);
return 0;
}
if (!publicAPI.link()) {
vtkErrorMacro('Links failed: ' + model.error);
return 0;
}
publicAPI.setCompiled(true);
return 1;
};
publicAPI.cleanup = function () {
if (model.shaderType === 'Unknown' || model.handle === 0) {
return;
}
model.context.deleteShader(model.handle);
model.handle = 0;
};
publicAPI.bind = function () {
if (!model.linked && !model.link()) {
return false;
}
model.context.useProgram(model.handle);
publicAPI.setBound(true);
return true;
};
publicAPI.isBound = function () {
return !!model.bound;
};
publicAPI.release = function () {
model.context.useProgram(null);
publicAPI.setBound(false);
};
publicAPI.setContext = function (ctx) {
model.vertexShader.setContext(ctx);
model.fragmentShader.setContext(ctx);
model.geometryShader.setContext(ctx);
};
publicAPI.link = function () {
if (model.inked) {
return true;
}
if (model.handle === 0) {
model.error = 'Program has not been initialized, and/or does not have shaders.';
return false;
}
// clear out the list of uniforms used
model.uniformLocs = {};
model.context.linkProgram(model.handle);
var isCompiled = model.context.getProgramParameter(model.handle, model.context.LINK_STATUS);
if (!isCompiled) {
var lastError = model.context.getProgramInfoLog(model.handle);
vtkErrorMacro('Error linking shader ' + lastError);
model.handle = 0;
return false;
}
publicAPI.setLinked(true);
model.attributeLocs = {};
return true;
};
publicAPI.setUniformMatrix = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniformMatrix4fv(location, false, v);
return true;
};
publicAPI.setUniformMatrix3x3 = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniformMatrix3fv(location, false, v);
return true;
};
publicAPI.setUniformf = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform1f(location, v);
return true;
};
publicAPI.setUniformfv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform1fv(location, v);
return true;
};
publicAPI.setUniformi = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform1i(location, v);
return true;
};
publicAPI.setUniformiv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform1iv(location, v);
return true;
};
publicAPI.setUniform2f = function (name, v1, v2) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
if (v2 === undefined) {
throw new RangeError('Invalid number of values for array');
}
model.context.uniform2f(location, v1, v2);
return true;
};
publicAPI.setUniform2fv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform2fv(location, v);
return true;
};
publicAPI.setUniform2i = function (name, v1, v2) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
if (v2 === undefined) {
throw new RangeError('Invalid number of values for array');
}
model.context.uniform2i(location, v1, v2);
return true;
};
publicAPI.setUniform2iv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform2iv(location, v);
return true;
};
publicAPI.setUniform3f = function (name, a1, a2, a3) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
if (a3 === undefined) {
throw new RangeError('Invalid number of values for array');
}
model.context.uniform3f(location, a1, a2, a3);
return true;
};
publicAPI.setUniform3fArray = function (name, a) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
if (!Array.isArray(a) || a.length !== 3) {
throw new RangeError('Invalid number of values for array');
}
model.context.uniform3f(location, a[0], a[1], a[2]);
return true;
};
publicAPI.setUniform3fv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform3fv(location, v);
return true;
};
publicAPI.setUniform3i = function (name) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
var array = args;
// allow an array passed as a single argument
if (array.length === 1 && Array.isArray(array[0])) {
array = array[0];
}
if (array.length !== 3) {
throw new RangeError('Invalid number of values for array');
}
model.context.uniform3i(location, array[0], array[1], array[2]);
return true;
};
publicAPI.setUniform3iv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform3iv(location, v);
return true;
};
publicAPI.setUniform4f = function (name) {
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
var array = args;
// allow an array passed as a single argument
if (array.length === 1 && Array.isArray(array[0])) {
array = array[0];
}
if (array.length !== 4) {
throw new RangeError('Invalid number of values for array');
}
model.context.uniform4f(location, array[0], array[1], array[2], array[3]);
return true;
};
publicAPI.setUniform4fv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform4fv(location, v);
return true;
};
publicAPI.setUniform4i = function (name) {
for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
var array = args;
// allow an array passed as a single argument
if (array.length === 1 && Array.isArray(array[0])) {
array = array[0];
}
if (array.length !== 4) {
throw new RangeError('Invalid number of values for array');
}
model.context.uniform4i(location, array[0], array[1], array[2], array[3]);
return true;
};
publicAPI.setUniform4iv = function (name, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform4iv(location, v);
return true;
};
publicAPI.setUniform4fv = function (name, count, v) {
var location = publicAPI.findUniform(name);
if (location === -1) {
model.error = 'Could not set uniform ' + name + ' . No such uniform.';
return false;
}
model.context.uniform4fv(location, v);
return true;
};
publicAPI.findUniform = function (name) {
if (!name || !model.linked) {
return -1;
}
// see if we have cached the result
var loc = model.uniformLocs[name];
if (loc !== undefined) {
return loc;
}
loc = model.context.getUniformLocation(model.handle, name);
if (loc === null) {
model.error = 'Uniform ' + name + ' not found in current shader program.';
model.uniformLocs[name] = -1;
return -1;
}
model.uniformLocs[name] = loc;
return loc;
};
publicAPI.isUniformUsed = function (name) {
if (!name) {
return false;
}
// see if we have cached the result
var loc = model.uniformLocs[name];
if (loc !== undefined) {
return loc !== null;
}
if (!model.linked) {
vtkErrorMacro('attempt to find uniform when the shader program is not linked');
return false;
}
loc = model.context.getUniformLocation(model.handle, name);
model.uniformLocs[name] = loc;
if (loc === null) {
return false;
}
return true;
};
publicAPI.isAttributeUsed = function (name) {
if (!name) {
return false;
}
// see if we have cached the result
var loc = Object.keys(model.attributeLocs).indexOf(name);
if (loc !== -1) {
return true;
}
if (!model.linked) {
vtkErrorMacro('attempt to find uniform when the shader program is not linked');
return false;
}
loc = model.context.getAttribLocation(model.handle, name);
if (loc === -1) {
return false;
}
model.attributeLocs[name] = loc;
return true;
};
publicAPI.attachShader = function (shader) {
if (shader.getHandle() === 0) {
model.error = 'Shader object was not initialized, cannot attach it.';
return false;
}
if (shader.getShaderType() === 'Unknown') {
model.error = 'Shader object is of type Unknown and cannot be used.';
return false;
}
if (model.handle === 0) {
var thandle = model.context.createProgram();
if (thandle === 0) {
model.error = 'Could not create shader program.';
return false;
}
model.handle = thandle;
model.linked = false;
}
if (shader.getShaderType() === 'Vertex') {
if (model.vertexShaderHandle !== 0) {
model.comntext.detachShader(model.handle, model.vertexShaderHandle);
}
model.vertexShaderHandle = shader.getHandle();
}
if (shader.getShaderType() === 'Fragment') {
if (model.fragmentShaderHandle !== 0) {
model.context.detachShader(model.handle, model.fragmentShaderHandle);
}
model.fragmentShaderHandle = shader.getHandle();
}
model.context.attachShader(model.handle, shader.getHandle());
publicAPI.setLinked(false);
return true;
};
publicAPI.detachShader = function (shader) {
if (shader.getHandle() === 0) {
model.error = 'shader object was not initialized, cannot attach it.';
return false;
}
if (shader.getShaderType() === 'Unknown') {
model.error = 'Shader object is of type Unknown and cannot be used.';
return false;
}
if (model.handle === 0) {
model.errror = 'This shader prorgram has not been initialized yet.';
}
switch (shader.getShaderType()) {
case 'Vertex':
if (model.vertexShaderHandle !== shader.getHandle()) {
model.error = 'The supplied shader was not attached to this program.';
return false;
}
model.context.detachShader(model.handle, shader.getHandle());
model.vertexShaderHandle = 0;
model.linked = false;
return true;
case 'Fragment':
if (model.fragmentShaderHandle !== shader.getHandle()) {
model.error = 'The supplied shader was not attached to this program.';
return false;
}
model.context.detachShader(model.handle, shader.getHandle());
model.fragmentShaderHandle = 0;
model.linked = false;
return true;
default:
return false;
}
};
publicAPI.setContext = function (ctx) {
model.context = ctx;
model.vertexShader.setContext(ctx);
model.fragmentShader.setContext(ctx);
model.geometryShader.setContext(ctx);
};
publicAPI.setLastCameraMTime = function (mtime) {
model.lastCameraMTime = mtime;
};
// publicAPI.enableAttributeArray = (name) => {
// const location = publicAPI.findAttributeArray(name);
// if (location === -1) {
// model.error = `Could not enable attribute ${name} No such attribute.`;
// return false;
// }
// model.context.enableVertexAttribArray(location);
// return true;
// };
// publicAPI.disableAttributeArray = (name) => {
// const location = publicAPI.findAttributeArray(name);
// if (location === -1) {
// model.error = `Could not enable attribute ${name} No such attribute.`;
// return false;
// }
// model.context.disableVertexAttribArray(location);
// return true;
// };
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
vertexShaderHandle: 0,
fragmentShaderHandle: 0,
geometryShaderHandle: 0,
vertexShader: null,
fragmentShader: null,
geometryShader: null,
linked: false,
bound: false,
compiled: false,
error: '',
handle: 0,
numberOfOutputs: 0,
attributesLocs: null,
uniformLocs: null,
md5Hash: 0,
context: null,
lastCameraMTime: null
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Instanciate internal objects
model.attributesLocs = {};
model.uniformLocs = {};
model.vertexShader = _Shader2.default.newInstance();
model.vertexShader.setShaderType('Vertex');
model.fragmentShader = _Shader2.default.newInstance();
model.fragmentShader.setShaderType('Fragment');
model.geometryShader = _Shader2.default.newInstance();
model.geometryShader.setShaderType('Geometry');
// Build VTK API
_macro2.default.obj(publicAPI, model);
_macro2.default.get(publicAPI, model, ['lastCameraMTime']);
_macro2.default.setGet(publicAPI, model, ['error', 'handle', 'compiled', 'bound', 'md5Hash', 'vertexShader', 'fragmentShader', 'geometryShader', 'linked']);
// Object methods
vtkShaderProgram(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = _macro2.default.newInstance(extend, 'vtkShaderProgram');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend, substitute: substitute };
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
function _has(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (_has(source, p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function (chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i = 0, l = chunks.length; i < l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function (chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
exports.base64 = true;
exports.array = true;
exports.string = true;
exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
exports.nodebuffer = typeof Buffer !== "undefined";
// contains true if JSZip can read/generate Uint8Array, false otherwise.
exports.uint8array = typeof Uint8Array !== "undefined";
if (typeof ArrayBuffer === "undefined") {
exports.blob = false;
}
else {
var buffer = new ArrayBuffer(0);
try {
exports.blob = new Blob([buffer], {
type: "application/zip"
}).size === 0;
}
catch (e) {
try {
var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var builder = new Builder();
builder.append(buffer);
exports.blob = builder.getBlob('application/zip').size === 0;
}
catch (e) {
exports.blob = false;
}
}
}
try {
exports.nodestream = !!__webpack_require__(290).Readable;
} catch(e) {
exports.nodestream = false;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(89).Buffer))
/***/ }),
/* 45 */,
/* 46 */,
/* 47 */,
/* 48 */,
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// removed by extract-text-webpack-plugin
/***/ }),
/* 50 */,
/* 51 */,
/* 52 */,
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
/**/
var processNextTick = __webpack_require__(109);
/**/
/**/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/**/
module.exports = Duplex;
/**/
var util = __webpack_require__(90);
util.inherits = __webpack_require__(70);
/**/
var Readable = __webpack_require__(291);
var Writable = __webpack_require__(177);
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
processNextTick(cb, err);
};
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
/***/ }),
/* 54 */,
/* 55 */,
/* 56 */,
/* 57 */,
/* 58 */,
/* 59 */,
/* 60 */,
/* 61 */,
/* 62 */,
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = vtk;
var factoryMapping = {
vtkObject: function vtkObject() {
return null;
}
};
function vtk(obj) {
if (obj === null || obj === undefined) {
return obj;
}
if (obj.isA) {
return obj;
}
if (!obj.vtkClass) {
if (global.console && global.console.error) {
global.console.error('Invalid VTK object');
}
return null;
}
var constructor = factoryMapping[obj.vtkClass];
if (!constructor) {
if (global.console && global.console.error) {
global.console.error('No vtk class found for Object of type ' + obj.vtkClass);
}
return null;
}
// Shallow copy object
var model = Object.assign({}, obj);
// Convert into vtkObject any nested key
Object.keys(model).forEach(function (keyName) {
if (model[keyName] && _typeof(model[keyName]) === 'object' && model[keyName].vtkClass) {
model[keyName] = vtk(model[keyName]);
}
});
// Return the root
var newInst = constructor(model);
if (newInst && newInst.modified) {
newInst.modified();
}
return newInst;
}
function register(vtkClassName, constructor) {
factoryMapping[vtkClassName] = constructor;
}
// Nest register method under the vtk function
vtk.register = register;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25)))
/***/ }),
/* 64 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 65 */
/***/ (function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var Shading = exports.Shading = {
FLAT: 0,
GOURAUD: 1,
PHONG: 2
};
var Representation = exports.Representation = {
POINTS: 0,
WIREFRAME: 1,
SURFACE: 2
};
var Interpolation = exports.Interpolation = Shading;
exports.default = {
Shading: Shading,
Representation: Representation,
Interpolation: Interpolation
};
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _webworkerPromise = __webpack_require__(548);
var _webworkerPromise2 = _interopRequireDefault(_webworkerPromise);
var _Constants = __webpack_require__(103);
var _Constants2 = _interopRequireDefault(_Constants);
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _DataArray = __webpack_require__(16);
var _DataArray2 = _interopRequireDefault(_DataArray);
var _Math = __webpack_require__(10);
var _Math2 = _interopRequireDefault(_Math);
var _ViewNode = __webpack_require__(24);
var _ViewNode2 = _interopRequireDefault(_ViewNode);
var _ComputeGradients = __webpack_require__(549);
var _ComputeGradients2 = _interopRequireDefault(_ComputeGradients);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Wrap = _Constants2.default.Wrap,
Filter = _Constants2.default.Filter;
var VtkDataTypes = _DataArray2.default.VtkDataTypes;
var vtkDebugMacro = _macro2.default.vtkDebugMacro,
vtkErrorMacro = _macro2.default.vtkErrorMacro,
vtkWarningMacro = _macro2.default.vtkWarningMacro;
// ----------------------------------------------------------------------------
// vtkOpenGLTexture methods
// ----------------------------------------------------------------------------
function vtkOpenGLTexture(publicAPI, model) {
var _this = this;
// Set our className
model.classHierarchy.push('vtkOpenGLTexture');
// Renders myself
publicAPI.render = function () {
var renWin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
if (renWin) {
model.openGLRenderWindow = renWin;
} else {
model.openGLRenderer = publicAPI.getFirstAncestorOfType('vtkOpenGLRenderer');
// sync renderable properties
model.openGLRenderWindow = model.openGLRenderer.getParent();
}
model.context = model.openGLRenderWindow.getContext();
if (model.renderable.getInterpolate()) {
if (model.generateMipmap) {
publicAPI.setMinificationFilter(Filter.LINEAR_MIPMAP_LINEAR);
} else {
publicAPI.setMinificationFilter(Filter.LINEAR);
}
publicAPI.setMagnificationFilter(Filter.LINEAR);
} else {
publicAPI.setMinificationFilter(Filter.NEAREST);
publicAPI.setMagnificationFilter(Filter.NEAREST);
}
if (model.renderable.getRepeat()) {
publicAPI.setWrapR(Wrap.REPEAT);
publicAPI.setWrapS(Wrap.REPEAT);
publicAPI.setWrapT(Wrap.REPEAT);
}
// clear image if input data is set
if (model.renderable.getInputData()) {
model.renderable.setImage(null);
}
// create the texture if it is not done already
if (!model.handle || model.renderable.getMTime() > model.textureBuildTime.getMTime()) {
// if we have an Image
if (model.renderable.getImage() !== null) {
if (model.renderable.getInterpolate()) {
model.generateMipmap = true;
publicAPI.setMinificationFilter(Filter.LINEAR_MIPMAP_LINEAR);
}
// Have an Image which may not be complete
if (model.renderable.getImage() && model.renderable.getImageLoaded()) {
publicAPI.create2DFromImage(model.renderable.getImage());
publicAPI.activate();
publicAPI.sendParameters();
model.textureBuildTime.modified();
}
}
// if we have Inputdata
var input = model.renderable.getInputData(0);
if (input && input.getPointData().getScalars()) {
var ext = input.getExtent();
var inScalars = input.getPointData().getScalars();
// do we have a cube map? Six inputs
var data = [];
for (var i = 0; i < model.renderable.getNumberOfInputPorts(); ++i) {
var indata = model.renderable.getInputData(i);
var scalars = indata ? indata.getPointData().getScalars().getData() : null;
if (scalars) {
data.push(scalars);
}
}
if (model.renderable.getInterpolate() && inScalars.getNumberOfComponents() === 4) {
model.generateMipmap = true;
publicAPI.setMinificationFilter(Filter.LINEAR_MIPMAP_LINEAR);
}
if (data.length % 6 === 0) {
publicAPI.createCubeFromRaw(ext[1] - ext[0] + 1, ext[3] - ext[2] + 1, inScalars.getNumberOfComponents(), inScalars.getDataType(), data);
} else {
publicAPI.create2DFromRaw(ext[1] - ext[0] + 1, ext[3] - ext[2] + 1, inScalars.getNumberOfComponents(), inScalars.getDataType(), inScalars.getData());
}
publicAPI.activate();
publicAPI.sendParameters();
model.textureBuildTime.modified();
}
}
if (model.handle) {
publicAPI.activate();
}
};
//----------------------------------------------------------------------------
publicAPI.destroyTexture = function () {
// deactivate it first
publicAPI.deactivate();
if (model.context && model.handle) {
model.context.deleteTexture(model.handle);
}
model.handle = 0;
model.numberOfDimensions = 0;
model.target = 0;
model.components = 0;
model.width = 0;
model.height = 0;
model.depth = 0;
publicAPI.resetFormatAndType();
};
//----------------------------------------------------------------------------
publicAPI.createTexture = function () {
// reuse the existing handle if we have one
if (!model.handle) {
model.handle = model.context.createTexture();
if (model.target) {
model.context.bindTexture(model.target, model.handle);
// See: http://www.openmodel.context..org/wiki/Common_Mistakes#Creating_a_complete_texture
// turn off mip map filter or set the base and max level correctly. here
// both are done.
model.context.texParameteri(model.target, model.context.TEXTURE_MIN_FILTER, publicAPI.getOpenGLFilterMode(model.minificationFilter));
model.context.texParameteri(model.target, model.context.TEXTURE_MAG_FILTER, publicAPI.getOpenGLFilterMode(model.magnificationFilter));
model.context.texParameteri(model.target, model.context.TEXTURE_WRAP_S, publicAPI.getOpenGLWrapMode(model.wrapS));
model.context.texParameteri(model.target, model.context.TEXTURE_WRAP_T, publicAPI.getOpenGLWrapMode(model.wrapT));
model.context.bindTexture(model.target, null);
}
}
};
//---------------------------------------------------------------------------
publicAPI.getTextureUnit = function () {
if (model.openGLRenderWindow) {
return model.openGLRenderWindow.getTextureUnitForTexture(publicAPI);
}
return -1;
};
//---------------------------------------------------------------------------
publicAPI.activate = function () {
// activate a free texture unit for this texture
model.openGLRenderWindow.activateTexture(publicAPI);
publicAPI.bind();
};
//---------------------------------------------------------------------------
publicAPI.deactivate = function () {
if (model.openGLRenderWindow) {
model.openGLRenderWindow.deactivateTexture(publicAPI);
}
};
//---------------------------------------------------------------------------
publicAPI.releaseGraphicsResources = function (rwin) {
if (rwin && model.handle) {
rwin.activateTexture(publicAPI);
rwin.deactivateTexture(publicAPI);
model.context.deleteTexture(model.handle);
model.handle = 0;
model.numberOfDimensions = 0;
model.target = 0;
model.internalFormat = 0;
model.format = 0;
model.openGLDataType = 0;
model.components = 0;
model.width = 0;
model.height = 0;
model.depth = 0;
}
if (model.shaderProgram) {
model.shaderProgram.releaseGraphicsResources(rwin);
model.shaderProgram = null;
}
};
//----------------------------------------------------------------------------
publicAPI.bind = function () {
model.context.bindTexture(model.target, model.handle);
if (model.autoParameters && publicAPI.getMTime() > model.sendParametersTime.getMTime()) {
publicAPI.sendParameters();
}
};
//----------------------------------------------------------------------------
publicAPI.isBound = function () {
var result = false;
if (model.context && model.handle) {
var target = 0;
switch (model.target) {
case model.context.TEXTURE_2D:
target = model.context.TEXTURE_BINDING_2D;
break;
default:
vtkWarningMacro('impossible case');
break;
}
var oid = model.context.getIntegerv(target);
result = oid === model.handle;
}
return result;
};
//----------------------------------------------------------------------------
publicAPI.sendParameters = function () {
model.context.texParameteri(model.target, model.context.TEXTURE_WRAP_S, publicAPI.getOpenGLWrapMode(model.wrapS));
model.context.texParameteri(model.target, model.context.TEXTURE_WRAP_T, publicAPI.getOpenGLWrapMode(model.wrapT));
if (model.openGLRenderWindow.getWebgl2()) {
model.context.texParameteri(model.target, model.context.TEXTURE_WRAP_R, publicAPI.getOpenGLWrapMode(model.wrapR));
}
model.context.texParameteri(model.target, model.context.TEXTURE_MIN_FILTER, publicAPI.getOpenGLFilterMode(model.minificationFilter));
model.context.texParameteri(model.target, model.context.TEXTURE_MAG_FILTER, publicAPI.getOpenGLFilterMode(model.magnificationFilter));
model.context.texParameteri(model.target, model.context.TEXTURE_BASE_LEVEL, model.baseLevel);
model.context.texParameteri(model.target, model.context.TEXTURE_MAX_LEVEL, model.maxLevel);
// model.context.texParameterf(model.target, model.context.TEXTURE_MIN_LOD, model.minLOD);
// model.context.texParameterf(model.target, model.context.TEXTURE_MAX_LOD, model.maxLOD);
model.sendParametersTime.modified();
};
//----------------------------------------------------------------------------
publicAPI.getInternalFormat = function (vtktype, numComps) {
if (model.internalFormat) {
return model.internalFormat;
}
model.internalFormat = publicAPI.getDefaultInternalFormat(vtktype, numComps);
if (!model.internalFormat) {
vtkDebugMacro('Unable to find suitable internal format for T=' + vtktype + ' NC= ' + numComps);
}
return model.internalFormat;
};
//----------------------------------------------------------------------------
publicAPI.getDefaultInternalFormat = function (vtktype, numComps) {
var result = 0;
// try default next
result = model.openGLRenderWindow.getDefaultTextureInternalFormat(vtktype, numComps, false);
if (result) {
return result;
}
// try floating point
result = _this.openGLRenderWindow.getDefaultTextureInternalFormat(vtktype, numComps, true);
if (!result) {
vtkDebugMacro('Unsupported internal texture type!');
vtkDebugMacro('Unable to find suitable internal format for T=' + vtktype + ' NC= ' + numComps);
}
return result;
};
//----------------------------------------------------------------------------
publicAPI.setInternalFormat = function (iFormat) {
if (iFormat !== model.context.InternalFormat) {
model.internalFormat = iFormat;
publicAPI.modified();
}
};
//----------------------------------------------------------------------------
publicAPI.getFormat = function (vtktype, numComps) {
if (!model.format) {
model.format = publicAPI.getDefaultFormat(vtktype, numComps);
}
return model.format;
};
//----------------------------------------------------------------------------
publicAPI.getDefaultFormat = function (vtktype, numComps) {
if (model.openGLRenderWindow.getWebgl2()) {
switch (numComps) {
case 1:
return model.context.RED;
case 2:
return model.context.RG;
case 3:
return model.context.RGB;
case 4:
return model.context.RGBA;
default:
return model.context.RGB;
}
} else {
switch (numComps) {
case 1:
return model.context.LUMINANCE;
case 2:
return model.context.LUMINANCE_ALPHA;
case 3:
return model.context.RGB;
case 4:
return model.context.RGBA;
default:
return model.context.RGB;
}
}
};
//----------------------------------------------------------------------------
publicAPI.resetFormatAndType = function () {
model.format = 0;
model.internalFormat = 0;
model.openGLDataType = 0;
};
//----------------------------------------------------------------------------
publicAPI.getDefaultDataType = function (vtkScalarType) {
// DON'T DEAL with VTK_CHAR as this is platform dependent.
if (model.openGLRenderWindow.getWebgl2()) {
switch (vtkScalarType) {
// case VtkDataTypes.SIGNED_CHAR:
// return model.context.BYTE;
case VtkDataTypes.UNSIGNED_CHAR:
return model.context.UNSIGNED_BYTE;
// case VtkDataTypes.SHORT:
// return model.context.SHORT;
// case VtkDataTypes.UNSIGNED_SHORT:
// return model.context.UNSIGNED_SHORT;
// case VtkDataTypes.INT:
// return model.context.INT;
// case VtkDataTypes.UNSIGNED_INT:
// return model.context.UNSIGNED_INT;
case VtkDataTypes.FLOAT:
case VtkDataTypes.VOID: // used for depth component textures.
default:
return model.context.FLOAT;
}
}
switch (vtkScalarType) {
// case VtkDataTypes.SIGNED_CHAR:
// return model.context.BYTE;
case VtkDataTypes.UNSIGNED_CHAR:
return model.context.UNSIGNED_BYTE;
// case VtkDataTypes.SHORT:
// return model.context.SHORT;
// case VtkDataTypes.UNSIGNED_SHORT:
// return model.context.UNSIGNED_SHORT;
// case VtkDataTypes.INT:
// return model.context.INT;
// case VtkDataTypes.UNSIGNED_INT:
// return model.context.UNSIGNED_INT;
case VtkDataTypes.FLOAT:
case VtkDataTypes.VOID: // used for depth component textures.
default:
if (model.context.getExtension('OES_texture_float') && model.context.getExtension('OES_texture_float_linear')) {
return model.context.FLOAT;
}
return model.context.UNSIGNED_BYTE;
}
};
//----------------------------------------------------------------------------
publicAPI.getOpenGLDataType = function (vtkScalarType) {
if (!model.openGLDataType) {
model.openGLDataType = publicAPI.getDefaultDataType(vtkScalarType);
}
return model.openGLDataType;
};
publicAPI.getShiftAndScale = function () {
var shift = 0.0;
var scale = 1.0;
// for all float type internal formats
switch (model.openGLDataType) {
case model.context.BYTE:
scale = 127.5;
shift = scale - 128.0;
break;
case model.context.UNSIGNED_BYTE:
scale = 255.0;
shift = 0.0;
break;
case model.context.SHORT:
scale = 32767.5;
shift = scale - 32768.0;
break;
case model.context.UNSIGNED_SHORT:
scale = 65536.0;
shift = 0.0;
break;
case model.context.INT:
scale = 2147483647.5;
shift = scale - 2147483648.0;
break;
case model.context.UNSIGNED_INT:
scale = 4294967295.0;
shift = 0.0;
break;
case model.context.FLOAT:
default:
break;
}
return { shift: shift, scale: scale };
};
//----------------------------------------------------------------------------
publicAPI.getOpenGLFilterMode = function (emode) {
switch (emode) {
case Filter.NEAREST:
return model.context.NEAREST;
case Filter.LINEAR:
return model.context.LINEAR;
case Filter.NEAREST_MIPMAP_NEAREST:
return model.context.NEAREST_MIPMAP_NEAREST;
case Filter.NEAREST_MIPMAP_LINEAR:
return model.context.NEAREST_MIPMAP_LINEAR;
case Filter.LINEAR_MIPMAP_NEAREST:
return model.context.LINEAR_MIPMAP_NEAREST;
case Filter.LINEAR_MIPMAP_LINEAR:
return model.context.LINEAR_MIPMAP_LINEAR;
default:
return model.context.NEAREST;
}
};
//----------------------------------------------------------------------------
publicAPI.getOpenGLWrapMode = function (vtktype) {
switch (vtktype) {
case Wrap.CLAMP_TO_EDGE:
return model.context.CLAMP_TO_EDGE;
case Wrap.REPEAT:
return model.context.REPEAT;
case Wrap.MIRRORED_REPEAT:
return model.context.MIRRORED_REPEAT;
default:
return model.context.CLAMP_TO_EDGE;
}
};
//----------------------------------------------------------------------------
function updateArrayDataType(dataType, data) {
var pixData = [];
// if the opengl data type is float
// then the data array must be float
if (dataType !== VtkDataTypes.FLOAT && model.openGLDataType === model.context.FLOAT) {
var pixCount = model.width * model.height * model.components;
for (var idx = 0; idx < data.length; idx++) {
var newArray = new Float32Array(pixCount);
for (var i = 0; i < pixCount; i++) {
newArray[i] = data[idx][i];
}
pixData.push(newArray);
}
}
// if the opengl data type is ubyte
// then the data array must be u8, we currently simply truncate the data
if (dataType !== VtkDataTypes.UNSIGNED_CHAR && model.openGLDataType === model.context.UNSIGNED_BYTE) {
var _pixCount = model.width * model.height * model.components;
for (var _idx = 0; _idx < data.length; _idx++) {
var _newArray = new Uint8Array(_pixCount);
for (var _i = 0; _i < _pixCount; _i++) {
_newArray[_i] = data[_idx][_i];
}
pixData.push(_newArray);
}
}
// The output has to be filled
if (pixData.length === 0) {
for (var _i2 = 0; _i2 < data.length; _i2++) {
pixData.push(data[_i2]);
}
}
return pixData;
}
//----------------------------------------------------------------------------
function scaleTextureToHighestPowerOfTwo(data) {
if (model.openGLRenderWindow.getWebgl2()) {
// No need if webGL2
return data;
}
var pixData = [];
var width = model.width;
var height = model.height;
var numComps = model.components;
if (data && (!_Math2.default.isPowerOfTwo(width) || !_Math2.default.isPowerOfTwo(height))) {
// Scale up the texture to the next highest power of two dimensions.
var newWidth = _Math2.default.nearestPowerOfTwo(width);
var newHeight = _Math2.default.nearestPowerOfTwo(height);
var pixCount = newWidth * newHeight * model.components;
for (var idx = 0; idx < data.length; idx++) {
if (data[idx] !== null) {
var newArray = null;
switch (model.openGLDataType) {
case model.context.FLOAT:
newArray = new Float32Array(pixCount);
break;
default:
case model.context.UNSIGNED_BYTE:
newArray = new Uint8Array(pixCount);
break;
}
var jFactor = height / newHeight;
var iFactor = width / newWidth;
for (var j = 0; j < newHeight; j++) {
var joff = j * newWidth * numComps;
var jidx = j * jFactor;
var jlow = Math.floor(jidx);
var jhi = Math.ceil(jidx);
if (jhi >= height) {
jhi = height - 1;
}
var jmix = jidx - jlow;
var jmix1 = 1.0 - jmix;
jlow = jlow * width * numComps;
jhi = jhi * width * numComps;
for (var i = 0; i < newWidth; i++) {
var ioff = i * numComps;
var iidx = i * iFactor;
var ilow = Math.floor(iidx);
var ihi = Math.ceil(iidx);
if (ihi >= width) {
ihi = width - 1;
}
var imix = iidx - ilow;
ilow *= numComps;
ihi *= numComps;
for (var c = 0; c < numComps; c++) {
newArray[joff + ioff + c] = data[idx][jlow + ilow + c] * jmix1 * (1.0 - imix) + data[idx][jlow + ihi + c] * jmix1 * imix + data[idx][jhi + ilow + c] * jmix * (1.0 - imix) + data[idx][jhi + ihi + c] * jmix * imix;
}
}
}
pixData.push(newArray);
model.width = newWidth;
model.height = newHeight;
} else {
pixData.push(null);
}
}
}
// The output has to be filled
if (pixData.length === 0) {
for (var _i3 = 0; _i3 < data.length; _i3++) {
pixData.push(data[_i3]);
}
}
return pixData;
}
//----------------------------------------------------------------------------
publicAPI.create2DFromRaw = function (width, height, numComps, dataType, data) {
// Now determine the texture parameters using the arguments.
publicAPI.getOpenGLDataType(dataType);
publicAPI.getInternalFormat(dataType, numComps);
publicAPI.getFormat(dataType, numComps);
if (!model.internalFormat || !model.format || !model.openGLDataType) {
vtkErrorMacro('Failed to determine texture parameters.');
return false;
}
model.target = model.context.TEXTURE_2D;
model.components = numComps;
model.width = width;
model.height = height;
model.depth = 1;
model.numberOfDimensions = 2;
model.openGLRenderWindow.activateTexture(publicAPI);
publicAPI.createTexture();
publicAPI.bind();
// Create an array of texture with one texture
var dataArray = [data];
var pixData = updateArrayDataType(dataType, dataArray);
var scaledData = scaleTextureToHighestPowerOfTwo(pixData);
// Source texture data from the PBO.
// model.context.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
model.context.pixelStorei(model.context.UNPACK_ALIGNMENT, 1);
model.context.texImage2D(model.target, 0, model.internalFormat, model.width, model.height, 0, model.format, model.openGLDataType, scaledData[0]);
if (model.generateMipmap) {
model.context.generateMipmap(model.target);
}
publicAPI.deactivate();
return true;
};
//----------------------------------------------------------------------------
publicAPI.createCubeFromRaw = function (width, height, numComps, dataType, data) {
// Now determine the texture parameters using the arguments.
publicAPI.getOpenGLDataType(dataType);
publicAPI.getInternalFormat(dataType, numComps);
publicAPI.getFormat(dataType, numComps);
if (!model.internalFormat || !model.format || !model.openGLDataType) {
vtkErrorMacro('Failed to determine texture parameters.');
return false;
}
model.target = model.context.TEXTURE_CUBE_MAP;
model.components = numComps;
model.width = width;
model.height = height;
model.depth = 1;
model.numberOfDimensions = 2;
model.openGLRenderWindow.activateTexture(publicAPI);
model.maxLevel = data.length / 6 - 1;
publicAPI.createTexture();
publicAPI.bind();
var pixData = updateArrayDataType(dataType, data);
var scaledData = scaleTextureToHighestPowerOfTwo(pixData);
// invert the data because opengl is messed up with cube maps
// and uses the old renderman standard with Y going down
// even though it is completely at odds with OpenGL standards
var invertedData = [];
var widthLevel = model.width;
var heightLevel = model.height;
for (var i = 0; i < scaledData.length; i++) {
if (i % 6 === 0 && i !== 0) {
widthLevel /= 2;
heightLevel /= 2;
}
invertedData[i] = new window[dataType](heightLevel * widthLevel * model.components);
for (var y = 0; y < heightLevel; ++y) {
var row1 = y * widthLevel * model.components;
var row2 = (heightLevel - y - 1) * widthLevel * model.components;
invertedData[i].set(scaledData[i].slice(row2, row2 + widthLevel * model.components), row1);
}
}
// Source texture data from the PBO.
model.context.pixelStorei(model.context.UNPACK_ALIGNMENT, 1);
// We get the 6 images
for (var _i4 = 0; _i4 < 6; _i4++) {
// For each mipmap level
for (var j = 0; j <= model.maxLevel; j++) {
if (invertedData[6 * j + _i4]) {
var w = model.width / Math.pow(2, j);
var h = model.height / Math.pow(2, j);
model.context.texImage2D(model.context.TEXTURE_CUBE_MAP_POSITIVE_X + _i4, j, model.internalFormat, w, h, 0, model.format, model.openGLDataType, invertedData[6 * j + _i4]);
}
}
}
// generateMipmap must not be called here because we manually upload all levels
// if it is called, all levels will be overwritten
publicAPI.deactivate();
return true;
};
//----------------------------------------------------------------------------
publicAPI.createDepthFromRaw = function (width, height, dataType, data) {
// Now determine the texture parameters using the arguments.
publicAPI.getOpenGLDataType(dataType);
model.format = model.context.DEPTH_COMPONENT;
model.internalFormat = model.context.DEPTH_COMPONENT;
if (!model.internalFormat || !model.format || !model.openGLDataType) {
vtkErrorMacro('Failed to determine texture parameters.');
return false;
}
model.target = model.context.TEXTURE_2D;
model.components = 1;
model.width = width;
model.height = height;
model.depth = 1;
model.numberOfDimensions = 2;
model.openGLRenderWindow.activateTexture(publicAPI);
publicAPI.createTexture();
publicAPI.bind();
// Source texture data from the PBO.
// model.context.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
model.context.pixelStorei(model.context.UNPACK_ALIGNMENT, 1);
model.context.texImage2D(model.target, 0, model.internalFormat, model.width, model.height, 0, model.format, model.openGLDataType, data);
if (model.generateMipmap) {
model.context.generateMipmap(model.target);
}
publicAPI.deactivate();
return true;
};
//----------------------------------------------------------------------------
publicAPI.create2DFromImage = function (image) {
// Now determine the texture parameters using the arguments.
publicAPI.getOpenGLDataType(VtkDataTypes.UNSIGNED_CHAR);
publicAPI.getInternalFormat(VtkDataTypes.UNSIGNED_CHAR, 4);
publicAPI.getFormat(VtkDataTypes.UNSIGNED_CHAR, 4);
if (!model.internalFormat || !model.format || !model.openGLDataType) {
vtkErrorMacro('Failed to determine texture parameters.');
return false;
}
model.target = model.context.TEXTURE_2D;
model.components = 4;
model.width = image.width;
model.height = image.height;
model.depth = 1;
model.numberOfDimensions = 2;
model.openGLRenderWindow.activateTexture(publicAPI);
publicAPI.createTexture();
publicAPI.bind();
// Source texture data from the PBO.
// model.context.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
model.context.pixelStorei(model.context.UNPACK_ALIGNMENT, 1);
// Scale up the texture to the next highest power of two dimensions (if needed) and flip y.
var needNearestPowerOfTwo = !_Math2.default.isPowerOfTwo(image.width) || !_Math2.default.isPowerOfTwo(image.height);
var canvas = document.createElement('canvas');
canvas.width = needNearestPowerOfTwo ? _Math2.default.nearestPowerOfTwo(image.width) : image.width;
canvas.height = needNearestPowerOfTwo ? _Math2.default.nearestPowerOfTwo(image.height) : image.height;
var ctx = canvas.getContext('2d');
ctx.translate(0, canvas.height);
ctx.scale(1, -1);
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
var safeImage = canvas;
model.context.texImage2D(model.target, 0, model.internalFormat, model.format, model.openGLDataType, safeImage);
if (model.generateMipmap) {
model.context.generateMipmap(model.target);
}
publicAPI.deactivate();
return true;
};
//----------------------------------------------------------------------------
publicAPI.create3DFromRaw = function (width, height, depth, numComps, dataType, data) {
// Now determine the texture parameters using the arguments.
publicAPI.getOpenGLDataType(dataType);
publicAPI.getInternalFormat(dataType, numComps);
publicAPI.getFormat(dataType, numComps);
if (!model.internalFormat || !model.format || !model.openGLDataType) {
vtkErrorMacro('Failed to determine texture parameters.');
return false;
}
model.target = model.context.TEXTURE_3D;
model.components = numComps;
model.width = width;
model.height = height;
model.depth = depth;
model.numberOfDimensions = 3;
model.openGLRenderWindow.activateTexture(publicAPI);
publicAPI.createTexture();
publicAPI.bind();
// Source texture data from the PBO.
// model.context.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
// model.context.pixelStorei(model.context.UNPACK_ALIGNMENT, 1);
model.context.texImage3D(model.target, 0, model.internalFormat, model.width, model.height, model.depth, 0, model.format, model.openGLDataType, data);
if (model.generateMipmap) {
model.context.generateMipmap(model.target);
}
publicAPI.deactivate();
return true;
};
//----------------------------------------------------------------------------
// This method simulates a 3D texture using 2D
publicAPI.create3DOneComponentFromRaw = function (width, height, depth, dataType, data) {
var numPixelsIn = width * height * depth;
// compute min and max values
var min = _Math2.default.arrayMin(data);
var max = _Math2.default.arrayMax(data);
if (min === max) {
max = min + 1.0;
}
// store the information, we will need it later
model.volumeInfo = { min: min, max: max, width: width, height: height, depth: depth };
var volCopyData = function volCopyData(outArray, outIdx, inValue, smin, smax) {
outArray[outIdx] = inValue;
};
var dataTypeToUse = VtkDataTypes.UNSIGNED_CHAR;
var numCompsToUse = 1;
var encodedScalars = false;
if (dataType === VtkDataTypes.UNSIGNED_CHAR) {
model.volumeInfo.min = 0.0;
model.volumeInfo.max = 255.0;
} else if (model.openGLRenderWindow.getWebgl2() || model.context.getExtension('OES_texture_float') && model.context.getExtension('OES_texture_float_linear')) {
dataTypeToUse = VtkDataTypes.FLOAT;
volCopyData = function volCopyData(outArray, outIdx, inValue, smin, smax) {
outArray[outIdx] = (inValue - smin) / (smax - smin);
};
} else {
encodedScalars = true;
dataTypeToUse = VtkDataTypes.UNSIGNED_CHAR;
numCompsToUse = 4;
volCopyData = function volCopyData(outArray, outIdx, inValue, smin, smax) {
var fval = (inValue - smin) / (smax - smin);
var r = Math.floor(fval * 255.0);
fval = fval * 255.0 - r;
outArray[outIdx] = r;
var g = Math.floor(fval * 255.0);
fval = fval * 255.0 - g;
outArray[outIdx + 1] = g;
var b = Math.floor(fval * 255.0);
outArray[outIdx + 2] = b;
};
}
// WebGL2
if (model.openGLRenderWindow.getWebgl2()) {
if (dataType !== VtkDataTypes.UNSIGNED_CHAR) {
var _newArray2 = new Float32Array(numPixelsIn);
for (var i = 0; i < numPixelsIn; ++i) {
_newArray2[i] = (data[i] - min) / (max - min);
}
return publicAPI.create3DFromRaw(width, height, depth, 1, VtkDataTypes.FLOAT, _newArray2);
}
return publicAPI.create3DFromRaw(width, height, depth, 1, dataType, data);
}
// WebGL1
// Now determine the texture parameters using the arguments.
publicAPI.getOpenGLDataType(dataTypeToUse);
publicAPI.getInternalFormat(dataTypeToUse, numCompsToUse);
publicAPI.getFormat(dataTypeToUse, numCompsToUse);
if (!model.internalFormat || !model.format || !model.openGLDataType) {
vtkErrorMacro('Failed to determine texture parameters.');
return false;
}
// have to pack this 3D texture into pot 2D texture
model.target = model.context.TEXTURE_2D;
model.components = numCompsToUse;
model.depth = 1;
model.numberOfDimensions = 2;
// MAX_TEXTURE_SIZE gives the max dimensions that can be supported by the GPU,
// but it doesn't mean it will fit in memory. If we have to use a float data type
// or 4 components, there are good chances that the texture size will blow up
// and could not fit in the GPU memory. Use a smaller texture size in that case,
// which will force a downsampling of the dataset.
// That problem does not occur when using webGL2 since we can pack the data in
// denser textures based on our data type.
// TODO: try to fit in the biggest supported texture, catch the gl error if it
// does not fix (OUT_OF_MEMORY), then attempt with smaller texture
var maxTexDim = model.context.getParameter(model.context.MAX_TEXTURE_SIZE);
if (maxTexDim > 4096 && (dataTypeToUse === VtkDataTypes.FLOAT || numCompsToUse === 4)) {
maxTexDim = 4096;
}
// compute estimate for XY subsample
var xstride = 1;
var ystride = 1;
if (numPixelsIn > maxTexDim * maxTexDim) {
xstride = Math.ceil(Math.sqrt(numPixelsIn / (maxTexDim * maxTexDim)));
ystride = xstride;
}
var targetWidth = Math.sqrt(numPixelsIn) / xstride;
targetWidth = _Math2.default.nearestPowerOfTwo(targetWidth);
// determine X reps
var xreps = Math.floor(targetWidth * xstride / width);
var yreps = Math.ceil(depth / xreps);
var targetHeight = _Math2.default.nearestPowerOfTwo(height * yreps / ystride);
model.width = targetWidth;
model.height = targetHeight;
model.openGLRenderWindow.activateTexture(publicAPI);
publicAPI.createTexture();
publicAPI.bind();
// store the information, we will need it later
model.volumeInfo = {
encodedScalars: encodedScalars,
min: min,
max: max,
width: width,
height: height,
depth: depth,
xreps: xreps,
yreps: yreps,
xstride: xstride,
ystride: ystride
};
// OK stuff the data into the 2d TEXTURE
// first allocate the new texture
var newArray = void 0;
var pixCount = targetWidth * targetHeight * numCompsToUse;
if (dataTypeToUse === VtkDataTypes.FLOAT) {
newArray = new Float32Array(pixCount);
} else {
newArray = new Uint8Array(pixCount);
}
// then stuff the data into it, nothing fancy right now
// for stride
var outIdx = 0;
for (var yRep = 0; yRep < yreps; yRep++) {
var xrepsThisRow = Math.min(xreps, depth - yRep * xreps);
var outXContIncr = model.width - xrepsThisRow * Math.floor(width / xstride);
for (var inY = 0; inY < height; inY += ystride) {
for (var xRep = 0; xRep < xrepsThisRow; xRep++) {
var inOffset = (yRep * xreps + xRep) * width * height + inY * width;
for (var inX = 0; inX < width; inX += xstride) {
// copy value
volCopyData(newArray, outIdx, data[inOffset + inX], min, max);
outIdx += numCompsToUse;
}
}
outIdx += outXContIncr * numCompsToUse;
}
}
// Source texture data from the PBO.
// model.context.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
model.context.pixelStorei(model.context.UNPACK_ALIGNMENT, 1);
model.context.texImage2D(model.target, 0, model.internalFormat, model.width, model.height, 0, model.format, model.openGLDataType, newArray);
publicAPI.deactivate();
return true;
};
//----------------------------------------------------------------------------
// This method creates a normal/gradient texture for 3D volume
// rendering
publicAPI.create3DLighting = function (scalarTexture, data, spacing) {
model.computedGradients = false;
var vinfo = scalarTexture.getVolumeInfo();
var width = vinfo.width;
var height = vinfo.height;
var depth = vinfo.depth;
var haveWebgl2 = model.openGLRenderWindow.getWebgl2();
var reformatGradientsFunction = void 0;
if (haveWebgl2) {
reformatGradientsFunction = function reformatGradientsFunction(workerResults) {
var numVoxelsIn = width * height * depth;
var reformattedGradients = new Uint8Array(numVoxelsIn * 4);
var maxMag = model.volumeInfo.max;
workerResults.forEach(function (_ref) {
var subGradients = _ref.subGradients,
subMagnitudes = _ref.subMagnitudes,
subMinMag = _ref.subMinMag,
subMaxMag = _ref.subMaxMag,
subDepthStart = _ref.subDepthStart,
subDepthEnd = _ref.subDepthEnd;
var inIdx = 0;
var inMagIdx = 0;
var outIdx = subDepthStart * width * height * 4;
// start and end depths are inclusive
var numWorkerVoxels = width * height * (subDepthEnd - subDepthStart + 1);
for (var vp = 0; vp < numWorkerVoxels; ++vp) {
reformattedGradients[outIdx++] = subGradients[inIdx++];
reformattedGradients[outIdx++] = subGradients[inIdx++];
reformattedGradients[outIdx++] = subGradients[inIdx++];
reformattedGradients[outIdx++] = 255.0 * Math.sqrt(subMagnitudes[inMagIdx++] / maxMag);
}
});
return publicAPI.create3DFromRaw(width, height, depth, 4, VtkDataTypes.UNSIGNED_CHAR, reformattedGradients);
};
} else {
// Now determine the texture parameters using the arguments.
publicAPI.getOpenGLDataType(VtkDataTypes.UNSIGNED_CHAR);
publicAPI.getInternalFormat(VtkDataTypes.UNSIGNED_CHAR, 4);
publicAPI.getFormat(VtkDataTypes.UNSIGNED_CHAR, 4);
if (!model.internalFormat || !model.format || !model.openGLDataType) {
vtkErrorMacro('Failed to determine texture parameters.');
return;
}
model.target = model.context.TEXTURE_2D;
model.components = 4;
model.depth = 1;
model.numberOfDimensions = 2;
model.width = scalarTexture.getWidth();
model.height = scalarTexture.getHeight();
reformatGradientsFunction = function reformatGradientsFunction(workerResults) {
// now store the computed values into the packed 2D
// texture using the same packing as volumeInfo
var reformattedGradients = new Uint8Array(model.width * model.height * 4);
var maxMag = model.volumeInfo.max;
workerResults.forEach(function (_ref2) {
var subGradients = _ref2.subGradients,
subMagnitudes = _ref2.subMagnitudes,
subMinMag = _ref2.subMinMag,
subMaxMag = _ref2.subMaxMag,
subDepthStart = _ref2.subDepthStart,
subDepthEnd = _ref2.subDepthEnd;
// start and end depths are inclusive
for (var zpin = subDepthStart; zpin <= subDepthEnd; ++zpin) {
// map xyz to 2d x y
var zyout = Math.floor(zpin / vinfo.xreps); // y offset in reps
var zxout = zpin - zyout * vinfo.xreps; // x offset in reps
zxout *= Math.floor(width / vinfo.xstride); // in pixels
zyout *= Math.floor(height / vinfo.ystride); // in pixels
var ypout = zyout;
for (var ypin = 0; ypin < height; ypin += vinfo.ystride, ypout++) {
var outIdx = (ypout * model.width + zxout) * 4;
var inMagIdx = ((zpin - subDepthStart) * height + ypin) * width;
var inIdx = inMagIdx * 3;
for (var xpin = 0; xpin < width; xpin += vinfo.xstride) {
reformattedGradients[outIdx++] = subGradients[inIdx];
reformattedGradients[outIdx++] = subGradients[inIdx + 1];
reformattedGradients[outIdx++] = subGradients[inIdx + 2];
reformattedGradients[outIdx++] = 255.0 * Math.sqrt(subMagnitudes[inMagIdx] / maxMag);
inMagIdx += vinfo.xstride;
inIdx += 3 * vinfo.xstride;
}
}
}
});
model.openGLRenderWindow.activateTexture(publicAPI);
publicAPI.createTexture();
publicAPI.bind();
// Source texture data from the PBO.
// model.context.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
model.context.pixelStorei(model.context.UNPACK_ALIGNMENT, 1);
model.context.texImage2D(model.target, 0, model.internalFormat, model.width, model.height, 0, model.format, model.openGLDataType, reformattedGradients);
publicAPI.deactivate();
return true;
};
}
var maxNumberOfWorkers = 4;
var depthStride = Math.ceil(depth / maxNumberOfWorkers);
var workerPromises = [];
var workers = [];
var depthIndex = 0;
while (depthIndex < depth - 1) {
var worker = new _ComputeGradients2.default();
var workerPromise = new _webworkerPromise2.default(worker);
var depthStart = depthIndex;
var depthEnd = depthIndex + depthStride; // no -1 to include one more slice to compute gradient
depthEnd = Math.min(depthEnd, depth - 1);
var subData = new data.constructor(data.slice(depthStart * width * height, (depthEnd + 1) * width * height) // +1 to include data from slice at depthEnd
);
workers.push(worker);
workerPromises.push(workerPromise.postMessage({
width: width,
height: height,
depth: depth,
spacing: spacing,
data: subData,
haveWebgl2: haveWebgl2,
depthStart: depthStart,
depthEnd: depthEnd
}, [subData.buffer]));
depthIndex += depthStride;
}
Promise.all(workerPromises).then(function (workerResults) {
// close workers
workers.forEach(function (worker) {
return worker.terminate();
});
// compute min/max across all workers
var minMag = Infinity;
var maxMag = -Infinity;
workerResults.forEach(function (_ref3) {
var subGradients = _ref3.subGradients,
subMagnitudes = _ref3.subMagnitudes,
subMinMag = _ref3.subMinMag,
subMaxMag = _ref3.subMaxMag,
subDepthStart = _ref3.subDepthStart,
subDepthEnd = _ref3.subDepthEnd;
minMag = Math.min(subMinMag, minMag);
maxMag = Math.max(subMaxMag, maxMag);
});
// store the information, we will need it later
model.volumeInfo = { min: minMag, max: maxMag };
// copy the data and create the texture
model.computedGradients = reformatGradientsFunction(workerResults);
if (model.computedGradients) {
model.gradientsBuildTime.modified();
}
return model.computedGradients;
});
};
publicAPI.setOpenGLRenderWindow = function (rw) {
if (model.openGLRenderWindow === rw) {
return;
}
publicAPI.releaseGraphicsResources();
model.openGLRenderWindow = rw;
model.context = null;
if (rw) {
model.context = model.openGLRenderWindow.getContext();
}
};
//----------------------------------------------------------------------------
publicAPI.getMaximumTextureSize = function (ctx) {
if (ctx && ctx.isCurrent()) {
return ctx.getIntegerv(ctx.MAX_TEXTURE_SIZE);
}
return -1;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
openGLRenderWindow: null,
context: null,
handle: 0,
sendParametersTime: null,
textureBuildTime: null,
numberOfDimensions: 0,
target: 0,
format: 0,
openGLDataType: 0,
components: 0,
width: 0,
height: 0,
depth: 0,
autoParameters: true,
wrapS: Wrap.CLAMP_TO_EDGE,
wrapT: Wrap.CLAMP_TO_EDGE,
wrapR: Wrap.CLAMP_TO_EDGE,
minificationFilter: Filter.NEAREST,
magnificationFilter: Filter.NEAREST,
minLOD: -1000.0,
maxLOD: 1000.0,
baseLevel: 0,
maxLevel: 1000,
generateMipmap: false,
computedGradients: false
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
_ViewNode2.default.extend(publicAPI, model, initialValues);
model.sendParametersTime = {};
_macro2.default.obj(model.sendParametersTime, { mtime: 0 });
model.textureBuildTime = {};
_macro2.default.obj(model.textureBuildTime, { mtime: 0 });
model.gradientsBuildTime = {};
_macro2.default.obj(model.gradientsBuildTime, { mtime: 0 });
// Build VTK API
_macro2.default.set(publicAPI, model, ['format', 'openGLDataType']);
_macro2.default.setGet(publicAPI, model, ['keyMatrixTime', 'minificationFilter', 'magnificationFilter', 'wrapS', 'wrapT', 'wrapR', 'generateMipmap']);
_macro2.default.get(publicAPI, model, ['width', 'height', 'volumeInfo', 'components', 'handle', 'target', 'computedGradients', 'gradientsBuildTime']);
// Object methods
vtkOpenGLTexture(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkOpenGLTexture');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, _Constants2.default);
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _AbstractMapper3D = __webpack_require__(566);
var _AbstractMapper3D2 = _interopRequireDefault(_AbstractMapper3D);
var _DataArray = __webpack_require__(16);
var _DataArray2 = _interopRequireDefault(_DataArray);
var _ImageData = __webpack_require__(171);
var _ImageData2 = _interopRequireDefault(_ImageData);
var _LookupTable = __webpack_require__(569);
var _LookupTable2 = _interopRequireDefault(_LookupTable);
var _Math = __webpack_require__(10);
var _Math2 = _interopRequireDefault(_Math);
var _Constants = __webpack_require__(172);
var _Constants2 = _interopRequireDefault(_Constants);
var _CoincidentTopologyHelper = __webpack_require__(571);
var _CoincidentTopologyHelper2 = _interopRequireDefault(_CoincidentTopologyHelper);
var _Static = __webpack_require__(572);
var _Static2 = _interopRequireDefault(_Static);
var _Constants3 = __webpack_require__(278);
var _Constants4 = _interopRequireDefault(_Constants3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ColorMode = _Constants4.default.ColorMode,
ScalarMode = _Constants4.default.ScalarMode,
GetArray = _Constants4.default.GetArray; // Need to go inside Constants otherwise dependency loop
var VectorMode = _Constants2.default.VectorMode;
// ----------------------------------------------------------------------------
function notImplemented(method) {
return function () {
return _macro2.default.vtkErrorMacro('vtkMapper::' + method + ' - NOT IMPLEMENTED');
};
}
// CoincidentTopology static methods ------------------------------------------
/* eslint-disable arrow-body-style */
var staticOffsetModel = {
Polygon: { factor: 2, offset: 0 },
Line: { factor: 1, offset: -1 },
Point: { factor: 0, offset: -2 }
};
var staticOffsetAPI = {};
_CoincidentTopologyHelper2.default.addCoincidentTopologyMethods(staticOffsetAPI, staticOffsetModel, _CoincidentTopologyHelper2.default.CATEGORIES.map(function (key) {
return {
key: key,
method: 'ResolveCoincidentTopology' + key + 'OffsetParameters'
};
}));
// ----------------------------------------------------------------------------
// vtkMapper methods
// ----------------------------------------------------------------------------
function vtkMapper(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkMapper');
publicAPI.getBounds = function () {
var input = publicAPI.getInputData();
if (!input) {
model.bounds = _Math2.default.createUninitializedBounds();
} else {
if (!model.static) {
publicAPI.update();
}
model.bounds = input.getBounds();
}
return model.bounds;
};
publicAPI.setForceCompileOnly = function (v) {
model.forceCompileOnly = v;
// make sure we do NOT call modified()
};
publicAPI.createDefaultLookupTable = function () {
model.lookupTable = _LookupTable2.default.newInstance();
};
publicAPI.getColorModeAsString = function () {
return _macro2.default.enumToString(ColorMode, model.colorMode);
};
publicAPI.setColorModeToDefault = function () {
return publicAPI.setColorMode(0);
};
publicAPI.setColorModeToMapScalars = function () {
return publicAPI.setColorMode(1);
};
publicAPI.setColorModeToDirectScalars = function () {
return publicAPI.setColorMode(2);
};
publicAPI.getScalarModeAsString = function () {
return _macro2.default.enumToString(ScalarMode, model.scalarMode);
};
publicAPI.setScalarModeToDefault = function () {
return publicAPI.setScalarMode(0);
};
publicAPI.setScalarModeToUsePointData = function () {
return publicAPI.setScalarMode(1);
};
publicAPI.setScalarModeToUseCellData = function () {
return publicAPI.setScalarMode(2);
};
publicAPI.setScalarModeToUsePointFieldData = function () {
return publicAPI.setScalarMode(3);
};
publicAPI.setScalarModeToUseCellFieldData = function () {
return publicAPI.setScalarMode(4);
};
publicAPI.setScalarModeToUseFieldData = function () {
return publicAPI.setScalarMode(5);
};
// Add Static methods to our instance
Object.keys(_Static2.default).forEach(function (methodName) {
publicAPI[methodName] = _Static2.default[methodName];
});
Object.keys(staticOffsetAPI).forEach(function (methodName) {
publicAPI[methodName] = staticOffsetAPI[methodName];
});
// Relative metods
/* eslint-disable arrow-body-style */
model.topologyOffset = {
Polygon: { factor: 0, offset: 0 },
Line: { factor: 0, offset: 0 },
Point: { factor: 0, offset: 0 }
};
_CoincidentTopologyHelper2.default.addCoincidentTopologyMethods(publicAPI, model.topologyOffset, _CoincidentTopologyHelper2.default.CATEGORIES.map(function (key) {
return {
key: key,
method: 'RelativeCoincidentTopology' + key + 'OffsetParameters'
};
}));
/* eslint-enable arrow-body-style */
publicAPI.getCoincidentTopologyPolygonOffsetParameters = function () {
var globalValue = staticOffsetAPI.getResolveCoincidentTopologyPolygonOffsetParameters();
var localValue = publicAPI.getRelativeCoincidentTopologyPolygonOffsetParameters();
return {
factor: globalValue.factor + localValue.factor,
offset: globalValue.offset + localValue.offset
};
};
publicAPI.getCoincidentTopologyLineOffsetParameters = function () {
var globalValue = staticOffsetAPI.getResolveCoincidentTopologyLineOffsetParameters();
var localValue = publicAPI.getRelativeCoincidentTopologyLineOffsetParameters();
return {
factor: globalValue.factor + localValue.factor,
offset: globalValue.offset + localValue.offset
};
};
publicAPI.getCoincidentTopologyPointOffsetParameter = function () {
var globalValue = staticOffsetAPI.getResolveCoincidentTopologyPointOffsetParameters();
var localValue = publicAPI.getRelativeCoincidentTopologyPointOffsetParameters();
return {
factor: globalValue.factor + localValue.factor,
offset: globalValue.offset + localValue.offset
};
};
publicAPI.getAbstractScalars = function (input, scalarMode, arrayAccessMode, arrayId, arrayName) {
// make sure we have an input
if (!input || !model.scalarVisibility) {
return null;
}
var scalars = null;
// get and scalar data according to scalar mode
if (scalarMode === ScalarMode.DEFAULT) {
scalars = input.getPointData().getScalars();
if (!scalars) {
scalars = input.getCellData().getScalars();
}
} else if (scalarMode === ScalarMode.USE_POINT_DATA) {
scalars = input.getPointData().getScalars();
} else if (scalarMode === ScalarMode.USE_CELL_DATA) {
scalars = input.getCellData().getScalars();
} else if (scalarMode === ScalarMode.USE_POINT_FIELD_DATA) {
var pd = input.getPointData();
if (arrayAccessMode === GetArray.BY_ID) {
scalars = pd.getArrayByIndex(arrayId);
} else {
scalars = pd.getArrayByName(arrayName);
}
} else if (scalarMode === ScalarMode.USE_CELL_FIELD_DATA) {
var cd = input.getCellData();
if (arrayAccessMode === GetArray.BY_ID) {
scalars = cd.getArrayByIndex(arrayId);
} else {
scalars = cd.getArrayByName(arrayName);
}
} else if (scalarMode === ScalarMode.USE_FIELD_DATA) {
var fd = input.getFieldData();
if (arrayAccessMode === GetArray.BY_ID) {
scalars = fd.getArrayByIndex(arrayId);
} else {
scalars = fd.getArrayByName(arrayName);
}
}
return scalars;
};
publicAPI.mapScalars = function (input, alpha) {
var scalars = publicAPI.getAbstractScalars(input, model.scalarMode, model.arrayAccessMode, model.arrayId, model.colorByArrayName);
if (!scalars) {
model.colorCoordinates = null;
model.colorTextureMap = null;
model.colorMapColors = null;
return;
}
if (!model.useLookupTableScalarRange) {
publicAPI.getLookupTable().setRange(model.scalarRange[0], model.scalarRange[1]);
}
// Decide betweeen texture color or vertex color.
// Cell data always uses vertex color.
// Only point data can use both texture and vertex coloring.
if (publicAPI.canUseTextureMapForColoring(input)) {
publicAPI.mapScalarsToTexture(scalars, alpha);
return;
}
model.colorCoordinates = null;
model.colorTextureMap = null;
var lut = publicAPI.getLookupTable();
if (lut) {
// Ensure that the lookup table is built
lut.build();
model.colorMapColors = lut.mapScalars(scalars, model.colorMode, 0);
}
};
//-----------------------------------------------------------------------------
publicAPI.scalarToTextureCoordinate = function (scalarValue, // Input scalar
rangeMin, // range[0]
invRangeWidth) {
// 1/(range[1]-range[0])
var texCoordS = 0.5; // Scalar value is arbitrary when NaN
var texCoordT = 1.0; // 1.0 in t coordinate means NaN
if (!_Math2.default.isNan(scalarValue)) {
// 0.0 in t coordinate means not NaN. So why am I setting it to 0.49?
// Because when you are mapping scalars and you have a NaN adjacent to
// anything else, the interpolation everywhere should be NaN. Thus, I
// want the NaN color everywhere except right on the non-NaN neighbors.
// To simulate this, I set the t coord for the real numbers close to
// the threshold so that the interpolation almost immediately looks up
// the NaN value.
texCoordT = 0.49;
texCoordS = (scalarValue - rangeMin) * invRangeWidth;
// Some implementations apparently don't handle relatively large
// numbers (compared to the range [0.0, 1.0]) very well. In fact,
// values above 1122.0f appear to cause texture wrap-around on
// some systems even when edge clamping is enabled. Why 1122.0f? I
// don't know. For safety, we'll clamp at +/- 1000. This will
// result in incorrect images when the texture value should be
// above or below 1000, but I don't have a better solution.
if (texCoordS > 1000.0) {
texCoordS = 1000.0;
} else if (texCoordS < -1000.0) {
texCoordS = -1000.0;
}
}
return { texCoordS: texCoordS, texCoordT: texCoordT };
};
//-----------------------------------------------------------------------------
publicAPI.createColorTextureCoordinates = function (input, output, numScalars, numComps, component, range, tableRange, tableNumberOfColors, useLogScale) {
// We have to change the range used for computing texture
// coordinates slightly to accomodate the special above- and
// below-range colors that are the first and last texels,
// respectively.
var scalarTexelWidth = (range[1] - range[0]) / tableNumberOfColors;
var paddedRange = [];
paddedRange[0] = range[0] - scalarTexelWidth;
paddedRange[1] = range[1] + scalarTexelWidth;
var invRangeWidth = 1.0 / (paddedRange[1] - paddedRange[0]);
var outputV = output.getData();
var inputV = input.getData();
var count = 0;
var outputCount = 0;
if (component < 0 || component >= numComps) {
for (var scalarIdx = 0; scalarIdx < numScalars; ++scalarIdx) {
var sum = 0;
for (var compIdx = 0; compIdx < numComps; ++compIdx) {
sum += inputV[count] * inputV[count];
count++;
}
var magnitude = Math.sqrt(sum);
if (useLogScale) {
magnitude = _LookupTable2.default.applyLogScale(magnitude, tableRange, range);
}
var outputs = publicAPI.scalarToTextureCoordinate(magnitude, paddedRange[0], invRangeWidth);
outputV[outputCount] = outputs.texCoordS;
outputV[outputCount + 1] = outputs.texCoordT;
outputCount += 2;
}
} else {
count += component;
for (var _scalarIdx = 0; _scalarIdx < numScalars; ++_scalarIdx) {
var inputValue = inputV[count];
if (useLogScale) {
inputValue = _LookupTable2.default.applyLogScale(inputValue, tableRange, range);
}
var _outputs = publicAPI.scalarToTextureCoordinate(inputValue, paddedRange[0], invRangeWidth);
outputV[outputCount] = _outputs.texCoordS;
outputV[outputCount + 1] = _outputs.texCoordT;
outputCount += 2;
count += numComps;
}
}
};
publicAPI.mapScalarsToTexture = function (scalars, alpha) {
var range = model.lookupTable.getRange();
var useLogScale = model.lookupTable.usingLogScale();
if (useLogScale) {
// convert range to log.
_LookupTable2.default.getLogRange(range, range);
}
var origAlpha = model.lookupTable.getAlpha();
// Get rid of vertex color array. Only texture or vertex coloring
// can be active at one time. The existence of the array is the
// signal to use that technique.
model.colorMapColors = null;
// If the lookup table has changed, then recreate the color texture map.
// Set a new lookup table changes this->MTime.
if (model.colorTextureMap == null || publicAPI.getMTime() > model.colorTextureMap.getMTime() || model.lookupTable.getMTime() > model.colorTextureMap.getMTime() || model.lookupTable.getAlpha() !== alpha) {
model.lookupTable.setAlpha(alpha);
model.colorTextureMap = null;
// Get the texture map from the lookup table.
// Create a dummy ramp of scalars.
// In the future, we could extend vtkScalarsToColors.
model.lookupTable.build();
var numberOfColors = model.lookupTable.getNumberOfAvailableColors();
if (numberOfColors > 4094) {
numberOfColors = 4094;
}
numberOfColors += 2;
var k = (range[1] - range[0]) / (numberOfColors - 1 - 2);
var newArray = new Float64Array(numberOfColors * 2);
for (var i = 0; i < numberOfColors; ++i) {
newArray[i] = range[0] + i * k - k; // minus k to start at below range color
if (useLogScale) {
newArray[i] = Math.pow(10.0, newArray[i]);
}
}
// Dimension on NaN.
for (var _i = 0; _i < numberOfColors; ++_i) {
newArray[_i + numberOfColors] = NaN;
}
model.colorTextureMap = _ImageData2.default.newInstance();
model.colorTextureMap.setExtent(0, numberOfColors - 1, 0, 1, 0, 0);
var tmp = _DataArray2.default.newInstance({
numberOfComponents: 1,
values: newArray
});
model.colorTextureMap.getPointData().setScalars(model.lookupTable.mapScalars(tmp, model.colorMode, 0));
model.lookupTable.setAlpha(origAlpha);
}
// Create new coordinates if necessary.
// Need to compare lookup table incase the range has changed.
if (!model.colorCoordinates || publicAPI.getMTime() > model.colorCoordinates.getMTime() || publicAPI.getInputData(0).getMTime() > model.colorCoordinates.getMTime() || model.lookupTable.getMTime() > model.colorCoordinates.getMTime()) {
// Get rid of old colors
model.colorCoordinates = null;
// Now create the color texture coordinates.
var numComps = scalars.getNumberOfComponents();
var num = scalars.getNumberOfTuples();
// const fArray = new FloatArray(num * 2);
model.colorCoordinates = _DataArray2.default.newInstance({
numberOfComponents: 2,
values: new Float32Array(num * 2)
});
var scalarComponent = model.lookupTable.getVectorComponent();
// Although I like the feature of applying magnitude to single component
// scalars, it is not how the old MapScalars for vertex coloring works.
if (model.lookupTable.getVectorMode() === VectorMode.MAGNITUDE && scalars.getNumberOfComponents() > 1) {
scalarComponent = -1;
}
publicAPI.createColorTextureCoordinates(scalars, model.colorCoordinates, num, numComps, scalarComponent, range, model.lookupTable.getRange(), model.colorTextureMap.getPointData().getScalars().getNumberOfTuples() / 2 - 2, useLogScale);
}
};
publicAPI.getIsOpaque = function () {
var lut = publicAPI.getLookupTable();
if (lut) {
// Ensure that the lookup table is built
lut.build();
return lut.isOpaque();
}
return true;
};
publicAPI.canUseTextureMapForColoring = function (input) {
if (!model.interpolateScalarsBeforeMapping) {
return false; // user doesn't want us to use texture maps at all.
}
// index color does not use textures
if (model.lookupTable && model.lookupTable.getIndexedLookup()) {
return false;
}
return true;
};
publicAPI.clearColorArrays = function () {
model.colorMapColors = null;
model.colorCoordinates = null;
model.colorTextureMap = null;
};
publicAPI.getLookupTable = function () {
if (!model.lookupTable) {
publicAPI.createDefaultLookupTable();
}
return model.lookupTable;
};
publicAPI.getMTime = function () {
var mt = model.mtime;
if (model.lookupTable !== null) {
var time = model.lookupTable.getMTime();
mt = time > mt ? time : mt;
}
return mt;
};
publicAPI.getPrimitiveCount = function () {
var input = publicAPI.getInputData();
var pcount = {
points: input.getPoints().getNumberOfValues() / 3,
verts: input.getVerts().getNumberOfValues() - input.getVerts().getNumberOfCells(),
lines: input.getLines().getNumberOfValues() - 2 * input.getLines().getNumberOfCells(),
triangles: input.getPolys().getNumberOfValues() - 3 * input.getLines().getNumberOfCells()
};
return pcount;
};
publicAPI.acquireInvertibleLookupTable = notImplemented('AcquireInvertibleLookupTable');
publicAPI.valueToColor = notImplemented('ValueToColor');
publicAPI.colorToValue = notImplemented('ColorToValue');
publicAPI.useInvertibleColorFor = notImplemented('UseInvertibleColorFor');
publicAPI.clearInvertibleColor = notImplemented('ClearInvertibleColor');
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
colorMapColors: null, // Same as this->Colors
static: false,
lookupTable: null,
scalarVisibility: true,
scalarRange: [0, 1],
useLookupTableScalarRange: false,
colorMode: 0,
scalarMode: 0,
arrayAccessMode: 1, // By_NAME
renderTime: 0,
colorByArrayName: null,
fieldDataTupleId: -1,
interpolateScalarsBeforeMapping: false,
colorCoordinates: null,
colorTextureMap: null,
forceCompileOnly: 0,
useInvertibleColors: false,
invertibleScalars: null,
resolveCoincidentTopology: false,
viewSpecificProperties: null
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
_AbstractMapper3D2.default.extend(publicAPI, model, initialValues);
_macro2.default.get(publicAPI, model, ['colorCoordinates', 'colorMapColors', 'colorTextureMap']);
_macro2.default.setGet(publicAPI, model, ['colorByArrayName', 'arrayAccessMode', 'colorMode', 'fieldDataTupleId', 'interpolateScalarsBeforeMapping', 'lookupTable', 'renderTime', 'resolveCoincidentTopology', 'scalarMode', 'scalarVisibility', 'static', 'useLookupTableScalarRange', 'viewSpecificProperties']);
_macro2.default.setGetArray(publicAPI, model, ['scalarRange'], 2);
if (!model.viewSpecificProperties) {
model.viewSpecificProperties = {};
}
// Object methods
vtkMapper(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkMapper');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, staticOffsetAPI, _Static2.default, _Constants4.default);
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(11);
var support = __webpack_require__(44);
var nodejsUtils = __webpack_require__(111);
var GenericWorker = __webpack_require__(29);
/**
* The following functions come from pako, from pako/lib/utils/strings
* released under the MIT license, see pako https://github.com/nodeca/pako/
*/
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new Array(256);
for (var i=0; i<256; i++) {
_utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
var string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
if (support.uint8array) {
buf = new Uint8Array(buf_len);
} else {
buf = new Array(buf_len);
}
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
var utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
// convert array to string
var buf2string = function (buf) {
var str, i, out, c, c_len;
var len = buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
// shrinkBuf(utf16buf, out)
if (utf16buf.length !== out) {
if(utf16buf.subarray) {
utf16buf = utf16buf.subarray(0, out);
} else {
utf16buf.length = out;
}
}
// return String.fromCharCode.apply(null, utf16buf);
return utils.applyFromCharCode(utf16buf);
};
// That's all for the pako functions.
/**
* Transform a javascript string into an array (typed if possible) of bytes,
* UTF-8 encoded.
* @param {String} str the string to encode
* @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
*/
exports.utf8encode = function utf8encode(str) {
if (support.nodebuffer) {
return nodejsUtils.newBuffer(str, "utf-8");
}
return string2buf(str);
};
/**
* Transform a bytes array (or a representation) representing an UTF-8 encoded
* string into a javascript string.
* @param {Array|Uint8Array|Buffer} buf the data de decode
* @return {String} the decoded string.
*/
exports.utf8decode = function utf8decode(buf) {
if (support.nodebuffer) {
return utils.transformTo("nodebuffer", buf).toString("utf-8");
}
buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
return buf2string(buf);
};
/**
* A worker to decode utf8 encoded binary chunks into string chunks.
* @constructor
*/
function Utf8DecodeWorker() {
GenericWorker.call(this, "utf-8 decode");
// the last bytes if a chunk didn't end with a complete codepoint.
this.leftOver = null;
}
utils.inherits(Utf8DecodeWorker, GenericWorker);
/**
* @see GenericWorker.processChunk
*/
Utf8DecodeWorker.prototype.processChunk = function (chunk) {
var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
// 1st step, re-use what's left of the previous chunk
if (this.leftOver && this.leftOver.length) {
if(support.uint8array) {
var previousData = data;
data = new Uint8Array(previousData.length + this.leftOver.length);
data.set(this.leftOver, 0);
data.set(previousData, this.leftOver.length);
} else {
data = this.leftOver.concat(data);
}
this.leftOver = null;
}
var nextBoundary = utf8border(data);
var usableData = data;
if (nextBoundary !== data.length) {
if (support.uint8array) {
usableData = data.subarray(0, nextBoundary);
this.leftOver = data.subarray(nextBoundary, data.length);
} else {
usableData = data.slice(0, nextBoundary);
this.leftOver = data.slice(nextBoundary, data.length);
}
}
this.push({
data : exports.utf8decode(usableData),
meta : chunk.meta
});
};
/**
* @see GenericWorker.flush
*/
Utf8DecodeWorker.prototype.flush = function () {
if(this.leftOver && this.leftOver.length) {
this.push({
data : exports.utf8decode(this.leftOver),
meta : {}
});
this.leftOver = null;
}
};
exports.Utf8DecodeWorker = Utf8DecodeWorker;
/**
* A worker to endcode string chunks into utf8 encoded binary chunks.
* @constructor
*/
function Utf8EncodeWorker() {
GenericWorker.call(this, "utf-8 encode");
}
utils.inherits(Utf8EncodeWorker, GenericWorker);
/**
* @see GenericWorker.processChunk
*/
Utf8EncodeWorker.prototype.processChunk = function (chunk) {
this.push({
data : exports.utf8encode(chunk.data),
meta : chunk.meta
});
};
exports.Utf8EncodeWorker = Utf8EncodeWorker;
/***/ }),
/* 70 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 71 */,
/* 72 */,
/* 73 */,
/* 74 */,
/* 75 */,
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ensure = ensure;
exports.end = end;
var _jquery = __webpack_require__(6);
var _jquery2 = _interopRequireDefault(_jquery);
__webpack_require__(48);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*require.resolve*/(49);
function ensure(dlg, do_show, immediate, hide_func) {
(0, _jquery2.default)(dlg).on('hidden.bs.modal', function (event) {
var body = (0, _jquery2.default)('body');
(0, _jquery2.default)(this).removeClass('fv-modal-stack');
body.data('fv_open_modals', body.data('fv_open_modals') - 1);
});
(0, _jquery2.default)(dlg).on('shown.bs.modal', function (event) {
var body = (0, _jquery2.default)('body');
if (typeof body.data('fv_open_modals') == 'undefined') body.data('fv_open_modals', 0);
if ((0, _jquery2.default)(this).hasClass('fv-modal-stack')) return;
(0, _jquery2.default)(this).addClass('fv-modal-stack');
body.data('fv_open_modals', body.data('fv_open_modals') + 1);
(0, _jquery2.default)(this).css('z-index', 1040 + 10 * body.data('fv_open_modals'));
(0, _jquery2.default)('.modal-backdrop').not('.fv-modal-stack').css('z-index', 1039 + 10 * body.data('fv_open_modals')).addClass('fv-modal-stack');
});
var delay = immediate ? 0 : 500;
dlg.data('timed-dialog', setTimeout(function () {
do_show();
}, delay));
dlg.data('multi-hide-function', function () {
if (hide_func) hide_func();else dlg.modal('hide');
});
}
function end(dlg) {
clearTimeout(dlg.data('timed-dialog'));
dlg.data('multi-hide-function')();
}
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.show = show;
exports.hide = hide;
var _jquery = __webpack_require__(6);
var _jquery2 = _interopRequireDefault(_jquery);
__webpack_require__(48);
var _multimodal = __webpack_require__(76);
var multi = _interopRequireWildcard(_multimodal);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*require.resolve*/(49);
var code = [''].join('');
var errorDialog = (0, _jquery2.default)(code);
function show(msg) {
console.log('Show error dialog with ' + msg);
(0, _jquery2.default)('.modal-body', errorDialog).text(msg);
multi.ensure(errorDialog, function () {
errorDialog.modal();
});
}
function hide() {
multi.end(errorDialog);
errorDialog.modal('hide');
}
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = (function ($) {
var self = this;
self.queryString = function (paramsArray) {
var params = {};
for (var i = 0; i < paramsArray.length; ++i) {
var param = paramsArray[i].split('=', 2);
if (param.length !== 2) continue;
params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, ' '));
}
return params;
}(window.location.search.substr(1).split('&'));
self.addNewState = function () {
console.log(self.queryString);
history.pushState({}, '', '?' + $.param(self.queryString));
};
return self;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }),
/* 79 */,
/* 80 */,
/* 81 */,
/* 82 */,
/* 83 */,
/* 84 */,
/* 85 */,
/* 86 */,
/* 87 */,
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ObjectType = exports.ObjectType = {
ARRAY_BUFFER: 0,
ELEMENT_ARRAY_BUFFER: 1,
TEXTURE_BUFFER: 2
};
exports.default = {
ObjectType: ObjectType
};
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(619)
var ieee754 = __webpack_require__(620)
var isArray = __webpack_require__(289)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return ''
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25)))
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(89).Buffer))
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* global Promise */
// load the global object first:
// - it should be better integrated in the system (unhandledRejection in node)
// - the environment may have a custom Promise implementation (see zone.js)
var ES6Promise = null;
if (typeof Promise !== "undefined") {
ES6Promise = Promise;
} else {
ES6Promise = __webpack_require__(644);
}
/**
* Let the user use/change some implementations.
*/
module.exports = {
Promise: ES6Promise
};
/***/ }),
/* 92 */,
/* 93 */,
/* 94 */,
/* 95 */,
/* 96 */,
/* 97 */,
/* 98 */,
/* 99 */,
/* 100 */,
/* 101 */,
/* 102 */,
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var Wrap = exports.Wrap = {
CLAMP_TO_EDGE: 0,
REPEAT: 1,
MIRRORED_REPEAT: 2
};
var Filter = exports.Filter = {
NEAREST: 0,
LINEAR: 1,
NEAREST_MIPMAP_NEAREST: 2,
NEAREST_MIPMAP_LINEAR: 3,
LINEAR_MIPMAP_NEAREST: 4,
LINEAR_MIPMAP_LINEAR: 5
};
exports.default = {
Wrap: Wrap,
Filter: Filter
};
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = exports.STATIC = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Constants = __webpack_require__(88);
var _Constants2 = _interopRequireDefault(_Constants);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ObjectType = _Constants2.default.ObjectType;
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Static API
// ----------------------------------------------------------------------------
var STATIC = exports.STATIC = {};
// ----------------------------------------------------------------------------
// vtkOpenGLBufferObject methods
// ----------------------------------------------------------------------------
function vtkOpenGLBufferObject(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLBufferObject');
// Class-specific private functions
function convertType(type) {
switch (type) {
case ObjectType.ELEMENT_ARRAY_BUFFER:
return model.context.ELEMENT_ARRAY_BUFFER;
case ObjectType.TEXTURE_BUFFER:
if ('TEXTURE_BUFFER' in model.context) {
return model.context.TEXTURE_BUFFER;
}
/* eslint-disable no-fallthrough */
// Intentional fallthrough in case there is no TEXTURE_BUFFER in WebGL
default:
/* eslint-enable no-fallthrough */
case ObjectType.ARRAY_BUFFER:
return model.context.ARRAY_BUFFER;
}
}
var internalType = null;
var internalHandle = null;
var dirty = true;
var error = '';
// Public API methods
publicAPI.getType = function () {
return internalType;
};
publicAPI.setType = function (value) {
internalType = value;
};
publicAPI.getHandle = function () {
return internalHandle;
};
publicAPI.isReady = function () {
return dirty === false;
};
publicAPI.generateBuffer = function (type) {
var objectTypeGL = convertType(type);
if (internalHandle === null) {
internalHandle = model.context.createBuffer();
internalType = type;
}
return convertType(internalType) === objectTypeGL;
};
publicAPI.upload = function (data, type) {
// buffer, size, type
var alreadyGenerated = publicAPI.generateBuffer(type);
if (!alreadyGenerated) {
error = 'Trying to upload array buffer to incompatible buffer.';
return false;
}
model.context.bindBuffer(convertType(internalType), internalHandle);
model.context.bufferData(convertType(internalType), data, model.context.STATIC_DRAW);
dirty = false;
return true;
};
publicAPI.bind = function () {
if (!internalHandle) {
return false;
}
model.context.bindBuffer(convertType(internalType), internalHandle);
return true;
};
publicAPI.release = function () {
if (!internalHandle) {
return false;
}
model.context.bindBuffer(convertType(internalType), null);
return true;
};
publicAPI.releaseGraphicsResources = function () {
if (internalHandle !== null) {
model.context.bindBuffer(convertType(internalType), null);
model.context.deleteBuffer(internalHandle);
internalHandle = null;
}
};
publicAPI.setOpenGLRenderWindow = function (rw) {
if (model.openGLRenderWindow === rw) {
return;
}
publicAPI.releaseGraphicsResources();
model.openGLRenderWindow = rw;
model.context = null;
if (rw) {
model.context = model.openGLRenderWindow.getContext();
}
};
publicAPI.getError = function () {
return error;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
objectType: ObjectType.ARRAY_BUFFER,
openGLRenderWindow: null,
context: null
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Object methods
_macro2.default.obj(publicAPI, model);
_macro2.default.get(publicAPI, model, ['openGLRenderWindow']);
vtkOpenGLBufferObject(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend);
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, STATIC, _Constants2.default);
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _glMatrix = __webpack_require__(13);
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _HardwareSelector = __webpack_require__(274);
var _HardwareSelector2 = _interopRequireDefault(_HardwareSelector);
var _Helper = __webpack_require__(106);
var _Helper2 = _interopRequireDefault(_Helper);
var _Mapper = __webpack_require__(68);
var _Mapper2 = _interopRequireDefault(_Mapper);
var _Math = __webpack_require__(10);
var _Math2 = _interopRequireDefault(_Math);
var _Texture = __webpack_require__(67);
var _Texture2 = _interopRequireDefault(_Texture);
var _Property = __webpack_require__(168);
var _Property2 = _interopRequireDefault(_Property);
var _ShaderProgram = __webpack_require__(42);
var _ShaderProgram2 = _interopRequireDefault(_ShaderProgram);
var _ViewNode = __webpack_require__(24);
var _ViewNode2 = _interopRequireDefault(_ViewNode);
var _vtkPolyDataVS = __webpack_require__(279);
var _vtkPolyDataVS2 = _interopRequireDefault(_vtkPolyDataVS);
var _vtkPolyDataFS = __webpack_require__(107);
var _vtkPolyDataFS2 = _interopRequireDefault(_vtkPolyDataFS);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-lonely-if */
var primTypes = {
Start: 0,
Points: 0,
Lines: 1,
Tris: 2,
TriStrips: 3,
TrisEdges: 4,
TriStripsEdges: 5,
End: 6
};
var Representation = _Property2.default.Representation,
Shading = _Property2.default.Shading;
var ScalarMode = _Mapper2.default.ScalarMode;
var Filter = _Texture2.default.Filter,
Wrap = _Texture2.default.Wrap;
var PassTypes = _HardwareSelector2.default.PassTypes;
var vtkErrorMacro = _macro2.default.vtkErrorMacro;
var StartEvent = { type: 'StartEvent' };
var EndEvent = { type: 'EndEvent' };
// ----------------------------------------------------------------------------
// vtkOpenGLPolyDataMapper methods
// ----------------------------------------------------------------------------
function vtkOpenGLPolyDataMapper(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLPolyDataMapper');
publicAPI.buildPass = function (prepass) {
if (prepass) {
model.openGLActor = publicAPI.getFirstAncestorOfType('vtkOpenGLActor');
model.openGLRenderer = model.openGLActor.getFirstAncestorOfType('vtkOpenGLRenderer');
model.openGLRenderWindow = model.openGLRenderer.getParent();
model.openGLCamera = model.openGLRenderer.getViewNodeFor(model.openGLRenderer.getRenderable().getActiveCamera());
}
};
// Renders myself
publicAPI.translucentPass = function (prepass) {
if (prepass) {
publicAPI.render();
}
};
publicAPI.opaqueZBufferPass = function (prepass) {
if (prepass) {
model.haveSeenDepthRequest = true;
model.renderDepth = true;
publicAPI.render();
model.renderDepth = false;
}
};
publicAPI.opaquePass = function (prepass) {
if (prepass) {
publicAPI.render();
}
};
publicAPI.render = function () {
var ctx = model.openGLRenderWindow.getContext();
if (model.context !== ctx) {
model.context = ctx;
for (var i = primTypes.Start; i < primTypes.End; i++) {
model.primitives[i].setOpenGLRenderWindow(model.openGLRenderWindow);
}
}
var actor = model.openGLActor.getRenderable();
var ren = model.openGLRenderer.getRenderable();
publicAPI.renderPiece(ren, actor);
};
publicAPI.buildShaders = function (shaders, ren, actor) {
publicAPI.getShaderTemplate(shaders, ren, actor);
// user specified pre replacements
var openGLSpec = model.renderable.getViewSpecificProperties().OpenGL;
var shaderReplacements = null;
if (openGLSpec) {
shaderReplacements = openGLSpec.ShaderReplacements;
}
if (shaderReplacements) {
for (var i = 0; i < shaderReplacements.length; i++) {
var currReplacement = shaderReplacements[i];
if (currReplacement.replaceFirst) {
var shaderType = currReplacement.shaderType;
var ssrc = shaders[shaderType];
var substituteRes = _ShaderProgram2.default.substitute(ssrc, currReplacement.originalValue, currReplacement.replacementValue, currReplacement.replaceAll);
shaders[shaderType] = substituteRes.result;
}
}
}
publicAPI.replaceShaderValues(shaders, ren, actor);
// user specified post replacements
if (shaderReplacements) {
for (var _i = 0; _i < shaderReplacements.length; _i++) {
var _currReplacement = shaderReplacements[_i];
if (!_currReplacement.replaceFirst) {
var _shaderType = _currReplacement.shaderType;
var _ssrc = shaders[_shaderType];
var _substituteRes = _ShaderProgram2.default.substitute(_ssrc, _currReplacement.originalValue, _currReplacement.replacementValue, _currReplacement.replaceAll);
shaders[_shaderType] = _substituteRes.result;
}
}
}
};
publicAPI.getShaderTemplate = function (shaders, ren, actor) {
var openGLSpecProp = model.renderable.getViewSpecificProperties().OpenGL;
var vertexShaderCode = _vtkPolyDataVS2.default;
if (openGLSpecProp) {
var vertexSpecProp = openGLSpecProp.VertexShaderCode;
if (vertexSpecProp !== undefined && vertexSpecProp !== '') {
vertexShaderCode = vertexSpecProp;
}
}
shaders.Vertex = vertexShaderCode;
var fragmentShaderCode = _vtkPolyDataFS2.default;
if (openGLSpecProp) {
var fragmentSpecProp = openGLSpecProp.FragmentShaderCode;
if (fragmentSpecProp !== undefined && fragmentSpecProp !== '') {
fragmentShaderCode = fragmentSpecProp;
}
}
shaders.Fragment = fragmentShaderCode;
var geometryShaderCode = '';
if (openGLSpecProp) {
var geometrySpecProp = openGLSpecProp.GeometryShaderCode;
if (geometrySpecProp !== undefined) {
geometryShaderCode = geometrySpecProp;
}
}
shaders.Geometry = geometryShaderCode;
};
publicAPI.replaceShaderColor = function (shaders, ren, actor) {
var VSSource = shaders.Vertex;
var GSSource = shaders.Geometry;
var FSSource = shaders.Fragment;
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
// create the material/color property declarations, and VS implementation
// these are always defined
var colorDec = ['uniform float ambient;', 'uniform float diffuse;', 'uniform float specular;', 'uniform float opacityUniform; // the fragment opacity', 'uniform vec3 ambientColorUniform;', 'uniform vec3 diffuseColorUniform;'];
// add more for specular
if (lastLightComplexity) {
colorDec = colorDec.concat(['uniform vec3 specularColorUniform;', 'uniform float specularPowerUniform;']);
}
// now handle the more complex fragment shader implementation
// the following are always defined variables. We start
// by assiging a default value from the uniform
var colorImpl = ['vec3 ambientColor;', ' vec3 diffuseColor;', ' float opacity;'];
if (lastLightComplexity) {
colorImpl = colorImpl.concat([' vec3 specularColor;', ' float specularPower;']);
}
colorImpl = colorImpl.concat([' ambientColor = ambientColorUniform;', ' diffuseColor = diffuseColorUniform;', ' opacity = opacityUniform;']);
if (lastLightComplexity) {
colorImpl = colorImpl.concat([' specularColor = specularColorUniform;', ' specularPower = specularPowerUniform;']);
}
// add scalar vertex coloring
if (model.lastBoundBO.getCABO().getColorComponents() !== 0 && !model.drawingEdges) {
colorDec = colorDec.concat(['varying vec4 vertexColorVSOutput;']);
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Color::Dec', ['attribute vec4 scalarColor;', 'varying vec4 vertexColorVSOutput;']).result;
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Color::Impl', ['vertexColorVSOutput = scalarColor;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::Color::Dec', ['in vec4 vertexColorVSOutput[];', 'out vec4 vertexColorGSOutput;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::Color::Impl', ['vertexColorGSOutput = vertexColorVSOutput[i];']).result;
}
if (model.lastBoundBO.getCABO().getColorComponents() !== 0 && !model.drawingEdges) {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Color::Impl', colorImpl.concat([' diffuseColor = vertexColorVSOutput.rgb;', ' ambientColor = vertexColorVSOutput.rgb;', ' opacity = opacity*vertexColorVSOutput.a;'])).result;
} else {
if (model.renderable.getInterpolateScalarsBeforeMapping() && model.renderable.getColorCoordinates() && !model.drawingEdges) {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Color::Impl', colorImpl.concat([' vec4 texColor = texture2D(texture1, tcoordVCVSOutput.st);', ' diffuseColor = texColor.rgb;', ' ambientColor = texColor.rgb;', ' opacity = opacity*texColor.a;'])).result;
} else {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Color::Impl', colorImpl).result;
}
}
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Color::Dec', colorDec).result;
shaders.Vertex = VSSource;
shaders.Geometry = GSSource;
shaders.Fragment = FSSource;
};
publicAPI.replaceShaderLight = function (shaders, ren, actor) {
var FSSource = shaders.Fragment;
// check for shadow maps
var shadowFactor = '';
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
var lastLightCount = model.lastBoundBO.getReferenceByName('lastLightCount');
var sstring = [];
switch (lastLightComplexity) {
case 0:
// no lighting or RENDER_VALUES
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Light::Impl', [' gl_FragData[0] = vec4(ambientColor * ambient + diffuseColor * diffuse, opacity);', ' //VTK::Light::Impl'], false).result;
break;
case 1:
// headlight
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Light::Impl', [' float df = max(0.0, normalVCVSOutput.z);', ' float sf = pow(df, specularPower);', ' vec3 diffuseL = df * diffuseColor;', ' vec3 specularL = sf * specularColor;', ' gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);', ' //VTK::Light::Impl'], false).result;
break;
case 2:
// light kit
for (var lc = 0; lc < lastLightCount; ++lc) {
sstring = sstring.concat(['uniform vec3 lightColor' + lc + ';', 'uniform vec3 lightDirectionVC' + lc + '; // normalized', 'uniform vec3 lightHalfAngleVC' + lc + '; // normalized']);
}
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Light::Dec', sstring).result;
sstring = ['vec3 diffuseL = vec3(0,0,0);', ' vec3 specularL = vec3(0,0,0);', ' float df;'];
for (var _lc = 0; _lc < lastLightCount; ++_lc) {
sstring = sstring.concat([' df = max(0.0, dot(normalVCVSOutput, -lightDirectionVC' + _lc + '));', ' diffuseL += ((df' + shadowFactor + ') * lightColor' + _lc + ');', ' if (dot(normalVCVSOutput, lightDirectionVC' + _lc + ') < 0.0)', ' {', ' float sf = pow( max(0.0, dot(lightHalfAngleVC' + _lc + ',normalVCVSOutput)), specularPower);', ' specularL += ((sf' + shadowFactor + ') * lightColor' + _lc + ');', ' }']);
}
sstring = sstring.concat([' diffuseL = diffuseL * diffuseColor;', ' specularL = specularL * specularColor;', ' gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);', ' //VTK::Light::Impl']);
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Light::Impl', sstring, false).result;
break;
case 3:
// positional
for (var _lc2 = 0; _lc2 < lastLightCount; ++_lc2) {
sstring = sstring.concat(['uniform vec3 lightColor' + _lc2 + ';', 'uniform vec3 lightDirectionVC' + _lc2 + '; // normalized', 'uniform vec3 lightHalfAngleVC' + _lc2 + '; // normalized', 'uniform vec3 lightPositionVC' + _lc2 + ';', 'uniform vec3 lightAttenuation' + _lc2 + ';', 'uniform float lightConeAngle' + _lc2 + ';', 'uniform float lightExponent' + _lc2 + ';', 'uniform int lightPositional' + _lc2 + ';']);
}
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Light::Dec', sstring).result;
sstring = ['vec3 diffuseL = vec3(0,0,0);', ' vec3 specularL = vec3(0,0,0);', ' vec3 vertLightDirectionVC;', ' float attenuation;', ' float df;'];
for (var _lc3 = 0; _lc3 < lastLightCount; ++_lc3) {
sstring = sstring.concat([' attenuation = 1.0;', ' if (lightPositional' + _lc3 + ' == 0)', ' {', ' vertLightDirectionVC = lightDirectionVC' + _lc3 + ';', ' }', ' else', ' {', ' vertLightDirectionVC = vertexVC.xyz - lightPositionVC' + _lc3 + ';', ' float distanceVC = length(vertLightDirectionVC);', ' vertLightDirectionVC = normalize(vertLightDirectionVC);', ' attenuation = 1.0 /', ' (lightAttenuation' + _lc3 + '.x', ' + lightAttenuation' + _lc3 + '.y * distanceVC', ' + lightAttenuation' + _lc3 + '.z * distanceVC * distanceVC);', ' // per OpenGL standard cone angle is 90 or less for a spot light', ' if (lightConeAngle' + _lc3 + ' <= 90.0)', ' {', ' float coneDot = dot(vertLightDirectionVC, lightDirectionVC' + _lc3 + ');', ' // if inside the cone', ' if (coneDot >= cos(radians(lightConeAngle' + _lc3 + ')))', ' {', ' attenuation = attenuation * pow(coneDot, lightExponent' + _lc3 + ');', ' }', ' else', ' {', ' attenuation = 0.0;', ' }', ' }', ' }', ' df = max(0.0, attenuation*dot(normalVCVSOutput, -vertLightDirectionVC));', ' diffuseL += ((df' + shadowFactor + ') * lightColor' + _lc3 + ');', ' if (dot(normalVCVSOutput, vertLightDirectionVC) < 0.0)', ' {', ' float sf = attenuation*pow( max(0.0, dot(lightHalfAngleVC' + _lc3 + ',normalVCVSOutput)), specularPower);', ' specularL += ((sf' + shadowFactor + ') * lightColor' + _lc3 + ');', ' }']);
}
sstring = sstring.concat([' diffuseL = diffuseL * diffuseColor;', ' specularL = specularL * specularColor;', ' gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);', ' //VTK::Light::Impl']);
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Light::Impl', sstring, false).result;
break;
default:
vtkErrorMacro('bad light complexity');
}
shaders.Fragment = FSSource;
};
publicAPI.replaceShaderNormal = function (shaders, ren, actor) {
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
if (lastLightComplexity > 0) {
var VSSource = shaders.Vertex;
var GSSource = shaders.Geometry;
var FSSource = shaders.Fragment;
if (model.lastBoundBO.getCABO().getNormalOffset()) {
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Normal::Dec', ['attribute vec3 normalMC;', 'uniform mat3 normalMatrix;', 'varying vec3 normalVCVSOutput;']).result;
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Normal::Impl', ['normalVCVSOutput = normalMatrix * normalMC;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::Normal::Dec', ['in vec3 normalVCVSOutput[];', 'out vec3 normalVCGSOutput;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::Normal::Impl', ['normalVCGSOutput = normalVCVSOutput[i];']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Normal::Dec', ['varying vec3 normalVCVSOutput;']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Normal::Impl', ['vec3 normalVCVSOutput = normalize(normalVCVSOutput);',
// if (!gl_FrontFacing) does not work in intel hd4000 mac
// if (int(gl_FrontFacing) == 0) does not work on mesa
' if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }']).result;
} else {
if (model.haveCellNormals) {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Normal::Dec', ['uniform mat3 normalMatrix;', 'uniform samplerBuffer textureN;']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Normal::Impl', ['vec3 normalVCVSOutput = normalize(normalMatrix *', ' texelFetchBuffer(textureN, gl_PrimitiveID + PrimitiveIDOffset).xyz);', ' if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }']).result;
} else {
if (publicAPI.getOpenGLMode(actor.getProperty().getRepresentation(), model.lastBoundBO.getPrimitiveType()) === model.context.LINES) {
// generate a normal for lines, it will be perpendicular to the line
// and maximally aligned with the camera view direction
// no clue if this is the best way to do this.
// the code below has been optimized a bit so what follows is
// an explanation of the basic approach. Compute the gradient of the line
// with respect to x and y, the the larger of the two
// cross that with the camera view direction. That gives a vector
// orthogonal to the camera view and the line. Note that the line and the camera
// view are probably not orthogonal. Which is why when we cross result that with
// the line gradient again we get a reasonable normal. It will be othogonal to
// the line (which is a plane but maximally aligned with the camera view.
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::UniformFlow::Impl', [' vec3 fdx = vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z));', ' vec3 fdy = vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z));', ' //VTK::UniformFlow::Impl'] // For further replacements
).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Normal::Impl', ['vec3 normalVCVSOutput;', ' fdx = normalize(fdx);', ' fdy = normalize(fdy);', ' if (abs(fdx.x) > 0.0)', ' { normalVCVSOutput = normalize(cross(vec3(fdx.y, -fdx.x, 0.0), fdx)); }', ' else { normalVCVSOutput = normalize(cross(vec3(fdy.y, -fdy.x, 0.0), fdy));}']).result;
} else {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Normal::Dec', ['uniform int cameraParallel;']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::UniformFlow::Impl', [
// ' vec3 fdx = vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z));',
// ' vec3 fdy = vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z));',
' vec3 fdx = dFdx(vertexVC.xyz);', ' vec3 fdy = dFdy(vertexVC.xyz);', ' //VTK::UniformFlow::Impl'] // For further replacements
).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Normal::Impl', [' fdx = normalize(fdx);', ' fdy = normalize(fdy);', ' vec3 normalVCVSOutput = normalize(cross(fdx,fdy));',
// the code below is faster, but does not work on some devices
// 'vec3 normalVC = normalize(cross(dFdx(vertexVC.xyz), dFdy(vertexVC.xyz)));',
' if (cameraParallel == 1 && normalVCVSOutput.z < 0.0) { normalVCVSOutput = -1.0*normalVCVSOutput; }', ' if (cameraParallel == 0 && dot(normalVCVSOutput,vertexVC.xyz) > 0.0) { normalVCVSOutput = -1.0*normalVCVSOutput; }']).result;
}
}
}
shaders.Vertex = VSSource;
shaders.Geometry = GSSource;
shaders.Fragment = FSSource;
}
};
publicAPI.replaceShaderPositionVC = function (shaders, ren, actor) {
var VSSource = shaders.Vertex;
var GSSource = shaders.Geometry;
var FSSource = shaders.Fragment;
// for points make sure to add in the point size
if (actor.getProperty().getRepresentation() === Representation.POINTS || model.lastBoundBO.getPrimitiveType() === primTypes.Points) {
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::PositionVC::Impl', ['//VTK::PositionVC::Impl', ' gl_PointSize = ' + actor.getProperty().getPointSize() + '.0;'], false).result;
}
// do we need the vertex in the shader in View Coordinates
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
if (lastLightComplexity > 0) {
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::PositionVC::Dec', ['varying vec4 vertexVCVSOutput;']).result;
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::PositionVC::Impl', ['vertexVCVSOutput = MCVCMatrix * vertexMC;', ' gl_Position = MCDCMatrix * vertexMC;']).result;
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Camera::Dec', ['uniform mat4 MCDCMatrix;', 'uniform mat4 MCVCMatrix;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::PositionVC::Dec', ['in vec4 vertexVCVSOutput[];', 'out vec4 vertexVCGSOutput;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::PositionVC::Impl', ['vertexVCGSOutput = vertexVCVSOutput[i];']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::PositionVC::Dec', ['varying vec4 vertexVCVSOutput;']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::PositionVC::Impl', ['vec4 vertexVC = vertexVCVSOutput;']).result;
} else {
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Camera::Dec', ['uniform mat4 MCDCMatrix;']).result;
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::PositionVC::Impl', [' gl_Position = MCDCMatrix * vertexMC;']).result;
}
shaders.Vertex = VSSource;
shaders.Geometry = GSSource;
shaders.Fragment = FSSource;
};
publicAPI.replaceShaderTCoord = function (shaders, ren, actor) {
if (model.lastBoundBO.getCABO().getTCoordOffset()) {
var VSSource = shaders.Vertex;
var GSSource = shaders.Geometry;
var FSSource = shaders.Fragment;
if (model.drawingEdges) {
return;
}
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::TCoord::Impl', 'tcoordVCVSOutput = tcoordMC;').result;
// we only handle the first texture by default
// additional textures are activated and we set the uniform
// for the texture unit they are assigned to, but you have to
// add in the shader code to do something with them
var tus = model.openGLActor.getActiveTextures();
var tNumComp = 2;
var tcdim = 2;
if (tus && tus.length > 0) {
tNumComp = tus[0].getComponents();
if (tus[0].getTarget() === model.context.TEXTURE_CUBE_MAP) {
tcdim = 3;
}
}
if (model.renderable.getColorTextureMap()) {
tNumComp = model.renderable.getColorTextureMap().getPointData().getScalars().getNumberOfComponents();
tcdim = 2;
}
if (tcdim === 2) {
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::TCoord::Dec', 'attribute vec2 tcoordMC; varying vec2 tcoordVCVSOutput;').result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::TCoord::Dec', ['in vec2 tcoordVCVSOutput[];', 'out vec2 tcoordVCGSOutput;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::TCoord::Impl', 'tcoordVCGSOutput = tcoordVCVSOutput[i];').result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Dec', ['varying vec2 tcoordVCVSOutput;', 'uniform sampler2D texture1;']).result;
switch (tNumComp) {
case 1:
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Impl', ['vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);', 'gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*', ' vec4(tcolor.r,tcolor.r,tcolor.r,1.0);']).result;
break;
case 2:
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Impl', ['vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);', 'gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*', ' vec4(tcolor.r,tcolor.r,tcolor.r,tcolor.g);']).result;
break;
default:
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Impl', 'gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*texture2D(texture1, tcoordVCVSOutput.st);').result;
}
} else {
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::TCoord::Dec', 'attribute vec3 tcoordMC; varying vec3 tcoordVCVSOutput;').result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::TCoord::Dec', ['in vec3 tcoordVCVSOutput[];', 'out vec3 tcoordVCGSOutput;']).result;
GSSource = _ShaderProgram2.default.substitute(GSSource, '//VTK::TCoord::Impl', 'tcoordVCGSOutput = tcoordVCVSOutput[i];').result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Dec', ['varying vec3 tcoordVCVSOutput;', 'uniform samplerCube texture1;']).result;
switch (tNumComp) {
case 1:
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Impl', ['vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);', 'gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*', ' vec4(tcolor.r,tcolor.r,tcolor.r,1.0);']).result;
break;
case 2:
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Impl', ['vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);', 'gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*', ' vec4(tcolor.r,tcolor.r,tcolor.r,tcolor.g);']).result;
break;
default:
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::TCoord::Impl', 'gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*textureCube(texture1, tcoordVCVSOutput);').result;
}
}
shaders.Vertex = VSSource;
shaders.Geometry = GSSource;
shaders.Fragment = FSSource;
}
};
publicAPI.replaceShaderClip = function (shaders, ren, actor) {
var VSSource = shaders.Vertex;
var FSSource = shaders.Fragment;
if (model.renderable.getNumberOfClippingPlanes()) {
var numClipPlanes = model.renderable.getNumberOfClippingPlanes();
if (numClipPlanes > 6) {
_macro2.default.vtkErrorMacro('OpenGL has a limit of 6 clipping planes');
numClipPlanes = 6;
}
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Clip::Dec', ['uniform int numClipPlanes;', 'uniform vec4 clipPlanes[6];', 'varying float clipDistancesVSOutput[6];']).result;
VSSource = _ShaderProgram2.default.substitute(VSSource, '//VTK::Clip::Impl', ['for (int planeNum = 0; planeNum < 6; planeNum++)', ' {', ' if (planeNum >= numClipPlanes)', ' {', ' break;', ' }', ' clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);', ' }']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Clip::Dec', ['uniform int numClipPlanes;', 'varying float clipDistancesVSOutput[6];']).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Clip::Impl', ['for (int planeNum = 0; planeNum < 6; planeNum++)', ' {', ' if (planeNum >= numClipPlanes)', ' {', ' break;', ' }', ' if (clipDistancesVSOutput[planeNum] < 0.0) discard;', ' }']).result;
}
shaders.Vertex = VSSource;
shaders.Fragment = FSSource;
};
publicAPI.getCoincidentParameters = function (ren, actor) {
// 1. ResolveCoincidentTopology is On and non zero for this primitive
// type
var cp = null;
var prop = actor.getProperty();
if (model.renderable.getResolveCoincidentTopology() || prop.getEdgeVisibility() && prop.getRepresentation() === Representation.SURFACE) {
var primType = model.lastBoundBO.getPrimitiveType();
if (primType === primTypes.Points || prop.getRepresentation() === Representation.POINTS) {
cp = model.renderable.getCoincidentTopologyPointOffsetParameter();
} else if (primType === primTypes.Lines || prop.getRepresentation() === Representation.WIREFRAME) {
cp = model.renderable.getCoincidentTopologyLineOffsetParameters();
} else if (primType === primTypes.Tris || primType === primTypes.TriStrips) {
cp = model.renderable.getCoincidentTopologyPolygonOffsetParameters();
}
if (primType === primTypes.TrisEdges || primType === primTypes.TriStripsEdges) {
cp = model.renderable.getCoincidentTopologyPolygonOffsetParameters();
cp.factor /= 2.0;
cp.offset /= 2.0;
}
}
// hardware picking always offset due to saved zbuffer
// This gets you above the saved surface depth buffer.
// vtkHardwareSelector* selector = ren->GetSelector();
// if (selector &&
// selector->GetFieldAssociation() == vtkDataObject::FIELD_ASSOCIATION_POINTS)
// {
// offset -= 2.0;
// return;
// }
return cp;
};
publicAPI.replaceShaderCoincidentOffset = function (shaders, ren, actor) {
var cp = publicAPI.getCoincidentParameters(ren, actor);
// if we need an offset handle it here
// The value of .000016 is suitable for depth buffers
// of at least 16 bit depth. We do not query the depth
// right now because we would need some mechanism to
// cache the result taking into account FBO changes etc.
if (cp && (cp.factor !== 0.0 || cp.offset !== 0.0)) {
var FSSource = shaders.Fragment;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Coincident::Dec', ['uniform float cfactor;', 'uniform float coffset;']).result;
if (model.context.getExtension('EXT_frag_depth')) {
if (cp.factor !== 0.0) {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::UniformFlow::Impl', ['float cscale = length(vec2(dFdx(gl_FragCoord.z),dFdy(gl_FragCoord.z)));', '//VTK::UniformFlow::Impl'], false).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Depth::Impl', 'gl_FragDepthEXT = gl_FragCoord.z + cfactor*cscale + 0.000016*coffset;').result;
} else {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Depth::Impl', 'gl_FragDepthEXT = gl_FragCoord.z + 0.000016*coffset;').result;
}
}
if (model.openGLRenderWindow.getWebgl2()) {
if (cp.factor !== 0.0) {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::UniformFlow::Impl', ['float cscale = length(vec2(dFdx(gl_FragCoord.z),dFdy(gl_FragCoord.z)));', '//VTK::UniformFlow::Impl'], false).result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Depth::Impl', 'gl_FragDepth = gl_FragCoord.z + cfactor*cscale + 0.000016*coffset;').result;
} else {
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Depth::Impl', 'gl_FragDepth = gl_FragCoord.z + 0.000016*coffset;').result;
}
}
shaders.Fragment = FSSource;
}
};
publicAPI.replaceShaderPicking = function (shaders, ren, actor) {
if (model.openGLRenderer.getSelector()) {
var FSSource = shaders.Fragment;
switch (model.openGLRenderer.getSelector().getCurrentPass()) {
case PassTypes.ID_LOW24:
// FSSource = vtkShaderProgram.substitute(FSSource,
// '//VTK::Picking::Impl', [
// ' int idx = gl_PrimitiveID + 1 + PrimitiveIDOffset;',
// ' gl_FragData[0] = vec4(float(idx%256)/255.0, float((idx/256)%256)/255.0, float((idx/65536)%256)/255.0, 1.0);',
// ], false).result;
break;
default:
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Picking::Dec', 'uniform vec3 mapperIndex;').result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::Picking::Impl', ' gl_FragData[0] = vec4(mapperIndex,1.0);').result;
}
shaders.Fragment = FSSource;
}
};
publicAPI.replaceShaderValues = function (shaders, ren, actor) {
publicAPI.replaceShaderColor(shaders, ren, actor);
publicAPI.replaceShaderNormal(shaders, ren, actor);
publicAPI.replaceShaderLight(shaders, ren, actor);
publicAPI.replaceShaderTCoord(shaders, ren, actor);
publicAPI.replaceShaderPicking(shaders, ren, actor);
publicAPI.replaceShaderClip(shaders, ren, actor);
publicAPI.replaceShaderCoincidentOffset(shaders, ren, actor);
publicAPI.replaceShaderPositionVC(shaders, ren, actor);
if (model.haveSeenDepthRequest) {
var FSSource = shaders.Fragment;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::ZBuffer::Dec', 'uniform int depthRequest;').result;
FSSource = _ShaderProgram2.default.substitute(FSSource, '//VTK::ZBuffer::Impl', ['if (depthRequest == 1) {', 'float iz = floor(gl_FragCoord.z*65535.0 + 0.1);', 'float rf = floor(iz/256.0)/255.0;', 'float gf = mod(iz,256.0)/255.0;', 'gl_FragData[0] = vec4(rf, gf, 0.0, 1.0); }']).result;
shaders.Fragment = FSSource;
}
};
publicAPI.getNeedToRebuildShaders = function (cellBO, ren, actor) {
var lightComplexity = 0;
var numberOfLights = 0;
var primType = cellBO.getPrimitiveType();
var needLighting = true;
var poly = model.currentInput;
var n = actor.getProperty().getInterpolation() !== Shading.FLAT ? poly.getPointData().getNormals() : null;
if (n === null && poly.getCellData().getNormals()) {
n = poly.getCellData().getNormals();
}
var haveNormals = n !== null;
if (actor.getProperty().getRepresentation() === Representation.POINTS || primType === primTypes.Points) {
needLighting = haveNormals;
}
// do we need lighting?
if (actor.getProperty().getLighting() && needLighting) {
// consider the lighting complexity to determine which case applies
// simple headlight, Light Kit, the whole feature set of VTK
lightComplexity = 0;
var lights = ren.getLightsByReference();
for (var index = 0; index < lights.length; ++index) {
var light = lights[index];
var status = light.getSwitch();
if (status > 0) {
numberOfLights++;
if (lightComplexity === 0) {
lightComplexity = 1;
}
}
if (lightComplexity === 1 && (numberOfLights > 1 || light.getIntensity() !== 1.0 || !light.lightTypeIsHeadLight())) {
lightComplexity = 2;
}
if (lightComplexity < 3 && light.getPositional()) {
lightComplexity = 3;
}
}
}
var needRebuild = false;
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
var lastLightCount = model.lastBoundBO.getReferenceByName('lastLightCount');
if (lastLightComplexity !== lightComplexity || lastLightCount !== numberOfLights) {
model.lastBoundBO.set({ lastLightComplexity: lightComplexity }, true);
model.lastBoundBO.set({ lastLightCount: numberOfLights }, true);
needRebuild = true;
}
var selector = model.openGLRenderer.getSelector();
var selectionPass = selector === null ? -1 : selector.getCurrentPass();
if (model.lastBoundBO.getReferenceByName('lastSelectionPass') !== selectionPass) {
model.lastBoundBO.set({ lastSelectionPass: selectionPass }, true);
needRebuild = true;
}
// has something changed that would require us to recreate the shader?
// candidates are
// property modified (representation interpolation and lighting)
// input modified
// light complexity changed
if (model.lastHaveSeenDepthRequest !== model.haveSeenDepthRequest || cellBO.getProgram() === 0 || cellBO.getShaderSourceTime().getMTime() < publicAPI.getMTime() || cellBO.getShaderSourceTime().getMTime() < actor.getMTime() || cellBO.getShaderSourceTime().getMTime() < model.renderable.getMTime() || cellBO.getShaderSourceTime().getMTime() < model.currentInput.getMTime() || needRebuild) {
model.lastHaveSeenDepthRequest = model.haveSeenDepthRequest;
return true;
}
return false;
};
publicAPI.updateShaders = function (cellBO, ren, actor) {
model.lastBoundBO = cellBO;
// has something changed that would require us to recreate the shader?
if (publicAPI.getNeedToRebuildShaders(cellBO, ren, actor)) {
var shaders = { Vertex: null, Fragment: null, Geometry: null };
publicAPI.buildShaders(shaders, ren, actor);
// compile and bind the program if needed
var newShader = model.openGLRenderWindow.getShaderCache().readyShaderProgramArray(shaders.Vertex, shaders.Fragment, shaders.Geometry);
// if the shader changed reinitialize the VAO
if (newShader !== cellBO.getProgram()) {
cellBO.setProgram(newShader);
// reset the VAO as the shader has changed
cellBO.getVAO().releaseGraphicsResources();
}
cellBO.getShaderSourceTime().modified();
} else {
model.openGLRenderWindow.getShaderCache().readyShaderProgram(cellBO.getProgram());
}
cellBO.getVAO().bind();
publicAPI.setMapperShaderParameters(cellBO, ren, actor);
publicAPI.setPropertyShaderParameters(cellBO, ren, actor);
publicAPI.setCameraShaderParameters(cellBO, ren, actor);
publicAPI.setLightingShaderParameters(cellBO, ren, actor);
var listCallbacks = model.renderable.getViewSpecificProperties().ShadersCallbacks;
if (listCallbacks) {
listCallbacks.forEach(function (object) {
object.callback(object.userData, cellBO, ren, actor);
});
}
};
publicAPI.setMapperShaderParameters = function (cellBO, ren, actor) {
// Now to update the VAO too, if necessary.
if (cellBO.getProgram().isUniformUsed('PrimitiveIDOffset')) {
cellBO.getProgram().setUniformi('PrimitiveIDOffset', model.primitiveIDOffset);
}
if (cellBO.getCABO().getElementCount() && (model.VBOBuildTime.getMTime() > cellBO.getAttributeUpdateTime().getMTime() || cellBO.getShaderSourceTime().getMTime() > cellBO.getAttributeUpdateTime().getMTime())) {
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
if (cellBO.getProgram().isAttributeUsed('vertexMC')) {
if (!cellBO.getVAO().addAttributeArray(cellBO.getProgram(), cellBO.getCABO(), 'vertexMC', cellBO.getCABO().getVertexOffset(), cellBO.getCABO().getStride(), model.context.FLOAT, 3, false)) {
vtkErrorMacro('Error setting vertexMC in shader VAO.');
}
}
if (cellBO.getProgram().isAttributeUsed('normalMC') && cellBO.getCABO().getNormalOffset() && lastLightComplexity > 0) {
if (!cellBO.getVAO().addAttributeArray(cellBO.getProgram(), cellBO.getCABO(), 'normalMC', cellBO.getCABO().getNormalOffset(), cellBO.getCABO().getStride(), model.context.FLOAT, 3, false)) {
vtkErrorMacro('Error setting normalMC in shader VAO.');
}
} else {
cellBO.getVAO().removeAttributeArray('normalMC');
}
if (cellBO.getProgram().isAttributeUsed('tcoordMC') && cellBO.getCABO().getTCoordOffset()) {
if (!cellBO.getVAO().addAttributeArray(cellBO.getProgram(), cellBO.getCABO(), 'tcoordMC', cellBO.getCABO().getTCoordOffset(), cellBO.getCABO().getStride(), model.context.FLOAT, cellBO.getCABO().getTCoordComponents(), false)) {
vtkErrorMacro('Error setting tcoordMC in shader VAO.');
}
} else {
cellBO.getVAO().removeAttributeArray('tcoordMC');
}
if (cellBO.getProgram().isAttributeUsed('scalarColor') && cellBO.getCABO().getColorComponents()) {
if (!cellBO.getVAO().addAttributeArray(cellBO.getProgram(), cellBO.getCABO().getColorBO(), 'scalarColor', cellBO.getCABO().getColorOffset(), cellBO.getCABO().getColorBOStride(), model.context.UNSIGNED_BYTE, 4, true)) {
vtkErrorMacro('Error setting scalarColor in shader VAO.');
}
} else {
cellBO.getVAO().removeAttributeArray('scalarColor');
}
cellBO.getAttributeUpdateTime().modified();
}
if (model.renderable.getNumberOfClippingPlanes()) {
// add all the clipping planes
var numClipPlanes = model.renderable.getNumberOfClippingPlanes();
if (numClipPlanes > 6) {
_macro2.default.vtkErrorMacro('OpenGL has a limit of 6 clipping planes');
numClipPlanes = 6;
}
var planeEquations = [];
for (var i = 0; i < numClipPlanes; i++) {
var planeEquation = [];
model.renderable.getClippingPlaneInDataCoords(actor.getMatrix(), i, planeEquation);
for (var j = 0; j < 4; j++) {
planeEquations.push(planeEquation[j]);
}
}
cellBO.getProgram().setUniformi('numClipPlanes', numClipPlanes);
cellBO.getProgram().setUniform4fv('clipPlanes', 6, planeEquations);
}
if (model.internalColorTexture && cellBO.getProgram().isUniformUsed('texture1')) {
cellBO.getProgram().setUniformi('texture1', model.internalColorTexture.getTextureUnit());
}
var tus = model.openGLActor.getActiveTextures();
if (tus) {
for (var index = 0; index < tus.length; ++index) {
var tex = tus[index];
var texUnit = tex.getTextureUnit();
var tname = 'texture' + (texUnit + 1);
if (cellBO.getProgram().isUniformUsed(tname)) {
cellBO.getProgram().setUniformi(tname, texUnit);
}
}
}
// handle depth requests
if (model.haveSeenDepthRequest) {
cellBO.getProgram().setUniformi('depthRequest', model.renderDepth ? 1 : 0);
}
// handle coincident
if (cellBO.getProgram().isUniformUsed('coffset')) {
var cp = publicAPI.getCoincidentParameters(ren, actor);
cellBO.getProgram().setUniformf('coffset', cp.offset);
// cfactor isn't always used when coffset is.
if (cellBO.getProgram().isUniformUsed('cfactor')) {
cellBO.getProgram().setUniformf('cfactor', cp.factor);
}
}
var selector = model.openGLRenderer.getSelector();
if (selector && cellBO.getProgram().isUniformUsed('mapperIndex')) {
if (selector.getCurrentPass() < PassTypes.ID_LOW24) {
cellBO.getProgram().setUniform3fArray('mapperIndex', selector.getPropColorValue());
}
}
};
publicAPI.setLightingShaderParameters = function (cellBO, ren, actor) {
// for unlit and headlight there are no lighting parameters
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
if (lastLightComplexity < 2) {
return;
}
var program = cellBO.getProgram();
// bind some light settings
var numberOfLights = 0;
var lights = ren.getLightsByReference();
for (var index = 0; index < lights.length; ++index) {
var light = lights[index];
var status = light.getSwitch();
if (status > 0.0) {
var dColor = light.getColorByReference();
var intensity = light.getIntensity();
model.lightColor[0] = dColor[0] * intensity;
model.lightColor[1] = dColor[1] * intensity;
model.lightColor[2] = dColor[2] * intensity;
// get required info from light
var ld = light.getDirection();
model.lightDirection[0] = ld[0];
model.lightDirection[1] = ld[1];
model.lightDirection[2] = ld[2];
model.lightHalfAngle[0] = -model.lightDirection[0];
model.lightHalfAngle[1] = -model.lightDirection[1];
model.lightHalfAngle[2] = -model.lightDirection[2] + 1.0;
_Math2.default.normalize(model.lightDirection);
program.setUniform3fArray('lightColor' + numberOfLights, model.lightColor);
program.setUniform3fArray('lightDirectionVC' + numberOfLights, model.lightDirection);
program.setUniform3fArray('lightHalfAngleVC' + numberOfLights, model.lightHalfAngle);
numberOfLights++;
}
}
// we are done unless we have positional lights
if (lastLightComplexity < 3) {
return;
}
// for lightkit case there are some parameters to set
var cam = ren.getActiveCamera();
var viewTF = cam.getViewMatrix();
_glMatrix.mat4.transpose(viewTF, viewTF);
numberOfLights = 0;
for (var _index = 0; _index < lights.length; ++_index) {
var _light = lights[_index];
var _status = _light.getSwitch();
if (_status > 0.0) {
var lp = _light.getTransformedPosition();
var np = _glMatrix.vec3.fromValues(lp[0], lp[1], lp[2]);
_glMatrix.vec3.transformMat4(np, np, viewTF);
program.setUniform3fArray('lightAttenuation' + numberOfLights, _light.getAttenuationValuesByReference());
program.setUniformi('lightPositional' + numberOfLights, _light.getPositional());
program.setUniformf('lightExponent' + numberOfLights, _light.getExponent());
program.setUniformf('lightConeAngle' + numberOfLights, _light.getConeAngle());
program.setUniform3fArray('lightPositionVC' + numberOfLights, [np[0], np[1], np[2]]);
numberOfLights++;
}
}
};
publicAPI.setCameraShaderParameters = function (cellBO, ren, actor) {
var program = cellBO.getProgram();
// // [WMVD]C == {world, model, view, display} coordinates
// // E.g., WCDC == world to display coordinate transformation
var keyMats = model.openGLCamera.getKeyMatrices(ren);
var cam = ren.getActiveCamera();
var camm = model.openGLCamera.getKeyMatrixTime().getMTime();
var progm = program.getLastCameraMTime();
if (progm !== camm) {
if (actor.getIsIdentity()) {
program.setUniformMatrix('MCDCMatrix', keyMats.wcdc);
if (program.isUniformUsed('MCVCMatrix')) {
program.setUniformMatrix('MCVCMatrix', keyMats.wcvc);
}
if (program.isUniformUsed('normalMatrix')) {
program.setUniformMatrix3x3('normalMatrix', keyMats.normalMatrix);
}
}
if (program.isUniformUsed('cameraParallel')) {
program.setUniformi('cameraParallel', cam.getParallelProjection());
}
program.setLastCameraMTime(camm);
}
if (!actor.getIsIdentity()) {
var actMats = model.openGLActor.getKeyMatrices();
if (program.isUniformUsed('normalMatrix')) {
var anorms = _glMatrix.mat3.create();
_glMatrix.mat3.multiply(anorms, keyMats.normalMatrix, actMats.normalMatrix);
program.setUniformMatrix3x3('normalMatrix', anorms);
}
_glMatrix.mat4.identity(model.tmpMat4);
_glMatrix.mat4.multiply(model.tmpMat4, keyMats.wcdc, actMats.mcwc);
program.setUniformMatrix('MCDCMatrix', model.tmpMat4);
if (program.isUniformUsed('MCVCMatrix')) {
_glMatrix.mat4.multiply(model.tmpMat4, keyMats.wcvc, actMats.mcwc);
program.setUniformMatrix('MCVCMatrix', model.tmpMat4);
}
// reset the cam mtime as actor modified the shader values
program.setLastCameraMTime(0);
}
};
publicAPI.setPropertyShaderParameters = function (cellBO, ren, actor) {
var program = cellBO.getProgram();
var ppty = actor.getProperty();
var opacity = ppty.getOpacity();
program.setUniformf('opacityUniform', opacity);
var aColor = model.drawingEdges ? ppty.getEdgeColorByReference() : ppty.getAmbientColorByReference();
program.setUniform3fArray('ambientColorUniform', aColor);
program.setUniformf('ambient', ppty.getAmbient());
var dColor = model.drawingEdges ? ppty.getEdgeColorByReference() : ppty.getDiffuseColorByReference();
program.setUniform3fArray('diffuseColorUniform', dColor);
program.setUniformf('diffuse', ppty.getDiffuse());
// we are done unless we have lighting
var lastLightComplexity = model.lastBoundBO.getReferenceByName('lastLightComplexity');
if (lastLightComplexity < 1) {
return;
}
var sColor = ppty.getSpecularColorByReference();
program.setUniform3fArray('specularColorUniform', sColor);
program.setUniformf('specular', ppty.getSpecular());
program.setUniformf('specularPowerUniform', ppty.getSpecularPower());
// // now set the backface properties if we have them
// if (actor.getBackfaceProperty() && !model.DrawingEdges)
// {
// ppty = actor.getBackfaceProperty();
// let opacity = static_cast(ppty.getOpacity());
// double *aColor = ppty.getAmbientColor();
// double aIntensity = ppty.getAmbient(); // ignoring renderer ambient
// let ambientColor[3] = {static_cast(aColor[0] * aIntensity),
// static_cast(aColor[1] * aIntensity),
// static_cast(aColor[2] * aIntensity)};
// double *dColor = ppty.getDiffuseColor();
// double dIntensity = ppty.getDiffuse();
// let diffuseColor[3] = {static_cast(dColor[0] * dIntensity),
// static_cast(dColor[1] * dIntensity),
// static_cast(dColor[2] * dIntensity)};
// double *sColor = ppty.getSpecularColor();
// double sIntensity = ppty.getSpecular();
// let specularColor[3] = {static_cast(sColor[0] * sIntensity),
// static_cast(sColor[1] * sIntensity),
// static_cast(sColor[2] * sIntensity)};
// double specularPower = ppty.getSpecularPower();
// program.SetUniformf('opacityUniformBF', opacity);
// program.SetUniform3f('ambientColorUniformBF', ambientColor);
// program.SetUniform3f('diffuseColorUniformBF', diffuseColor);
// // we are done unless we have lighting
// if (model.LastLightComplexity[&cellBO] < 1)
// {
// return;
// }
// program.SetUniform3f('specularColorUniformBF', specularColor);
// program.SetUniformf('specularPowerUniformBF', specularPower);
// }
};
publicAPI.renderPieceStart = function (ren, actor) {
model.primitiveIDOffset = 0;
if (model.openGLRenderer.getSelector()) {
switch (model.openGLRenderer.getSelector().getCurrentPass()) {
default:
model.openGLRenderer.getSelector().renderProp(actor);
}
}
// make sure the BOs are up to date
publicAPI.updateBufferObjects(ren, actor);
// If we are coloring by texture, then load the texture map.
// Use Map as indicator, because texture hangs around.
if (model.renderable.getColorTextureMap()) {
model.internalColorTexture.activate();
}
// Bind the OpenGL, this is shared between the different primitive/cell types.
model.lastBoundBO = null;
};
publicAPI.renderPieceDraw = function (ren, actor) {
var representation = actor.getProperty().getRepresentation();
var gl = model.context;
var drawSurfaceWithEdges = actor.getProperty().getEdgeVisibility() && representation === Representation.SURFACE;
// for every primitive type
for (var i = primTypes.Start; i < primTypes.End; i++) {
// if there are entries
var cabo = model.primitives[i].getCABO();
if (cabo.getElementCount()) {
// are we drawing edges
model.drawingEdges = drawSurfaceWithEdges && (i === primTypes.TrisEdges || i === primTypes.TriStripsEdges);
publicAPI.updateShaders(model.primitives[i], ren, actor);
var mode = publicAPI.getOpenGLMode(representation, i);
gl.drawArrays(mode, 0, cabo.getElementCount());
var stride = (mode === gl.POINTS ? 1 : 0) || (mode === gl.LINES ? 2 : 3);
model.primitiveIDOffset += cabo.getElementCount() / stride;
}
}
};
publicAPI.getOpenGLMode = function (rep, type) {
if (rep === Representation.POINTS || type === primTypes.Points) {
return model.context.POINTS;
}
if (rep === Representation.WIREFRAME || type === primTypes.Lines || type === primTypes.TrisEdges || type === primTypes.TriStripsEdges) {
return model.context.LINES;
}
return model.context.TRIANGLES;
};
publicAPI.renderPieceFinish = function (ren, actor) {
if (model.LastBoundBO) {
model.LastBoundBO.getVAO().release();
}
if (model.renderable.getColorTextureMap()) {
model.internalColorTexture.deactivate();
}
};
publicAPI.renderPiece = function (ren, actor) {
// Make sure that we have been properly initialized.
// if (ren.getRenderWindow().checkAbortStatus()) {
// return;
// }
publicAPI.invokeEvent(StartEvent);
if (!model.renderable.getStatic()) {
model.renderable.update();
}
model.currentInput = model.renderable.getInputData();
publicAPI.invokeEvent(EndEvent);
if (!model.currentInput) {
vtkErrorMacro('No input!');
return;
}
// if there are no points then we are done
if (!model.currentInput.getPoints || !model.currentInput.getPoints().getNumberOfValues()) {
return;
}
// apply faceCulling
var gl = model.context;
var backfaceCulling = actor.getProperty().getBackfaceCulling();
var frontfaceCulling = actor.getProperty().getFrontfaceCulling();
if (!backfaceCulling && !frontfaceCulling) {
model.openGLRenderWindow.disableCullFace();
} else if (frontfaceCulling) {
model.openGLRenderWindow.enableCullFace();
gl.cullFace(gl.FRONT);
} else {
model.openGLRenderWindow.enableCullFace();
gl.cullFace(gl.BACK);
}
publicAPI.renderPieceStart(ren, actor);
publicAPI.renderPieceDraw(ren, actor);
publicAPI.renderPieceFinish(ren, actor);
};
publicAPI.computeBounds = function (ren, actor) {
if (!publicAPI.getInput()) {
_Math2.default.uninitializeBounds(model.bounds);
return;
}
model.bounds = publicAPI.getInput().getBounds();
};
publicAPI.updateBufferObjects = function (ren, actor) {
// Rebuild buffers if needed
if (publicAPI.getNeedToRebuildBufferObjects(ren, actor)) {
publicAPI.buildBufferObjects(ren, actor);
}
};
publicAPI.getNeedToRebuildBufferObjects = function (ren, actor) {
// first do a coarse check
// Note that the actor's mtime includes it's properties mtime
var vmtime = model.VBOBuildTime.getMTime();
if (vmtime < publicAPI.getMTime() || vmtime < model.renderable.getMTime() || vmtime < actor.getMTime() || vmtime < model.currentInput.getMTime()) {
return true;
}
return false;
};
publicAPI.buildBufferObjects = function (ren, actor) {
var poly = model.currentInput;
if (poly === null) {
return;
}
model.renderable.mapScalars(poly, 1.0);
var c = model.renderable.getColorMapColors();
model.haveCellScalars = false;
var scalarMode = model.renderable.getScalarMode();
if (model.renderable.getScalarVisibility()) {
// We must figure out how the scalars should be mapped to the polydata.
if ((scalarMode === ScalarMode.USE_CELL_DATA || scalarMode === ScalarMode.USE_CELL_FIELD_DATA || scalarMode === ScalarMode.USE_FIELD_DATA || !poly.getPointData().getScalars()) && scalarMode !== ScalarMode.USE_POINT_FIELD_DATA && c) {
model.haveCellScalars = true;
}
}
// Do we have normals?
var n = actor.getProperty().getInterpolation() !== Shading.FLAT ? poly.getPointData().getNormals() : null;
if (n === null && poly.getCellData().getNormals()) {
model.haveCellNormals = true;
n = poly.getCellData().getNormals();
}
// rebuild the VBO if the data has changed we create a string for the VBO what
// can change the VBO? points normals tcoords colors so what can change those?
// the input data is clearly one as it can change all four items tcoords may
// haveTextures or not colors may change based on quite a few mapping
// parameters in the mapper
var representation = actor.getProperty().getRepresentation();
var tcoords = poly.getPointData().getTCoords();
if (!model.openGLActor.getActiveTextures()) {
tcoords = null;
}
// handle color mapping via texture
if (model.renderable.getColorCoordinates()) {
tcoords = model.renderable.getColorCoordinates();
if (!model.internalColorTexture) {
model.internalColorTexture = _Texture2.default.newInstance();
}
var tex = model.internalColorTexture;
// the following 4 lines allow for NPOT textures
tex.setMinificationFilter(Filter.NEAREST);
tex.setMagnificationFilter(Filter.NEAREST);
tex.setWrapS(Wrap.CLAMP_TO_EDGE);
tex.setWrapT(Wrap.CLAMP_TO_EDGE);
tex.setOpenGLRenderWindow(model.openGLRenderWindow);
var input = model.renderable.getColorTextureMap();
var ext = input.getExtent();
var inScalars = input.getPointData().getScalars();
tex.create2DFromRaw(ext[1] - ext[0] + 1, ext[3] - ext[2] + 1, inScalars.getNumberOfComponents(), inScalars.getDataType(), inScalars.getData());
tex.activate();
tex.sendParameters();
tex.deactivate();
}
var toString = poly.getMTime() + 'A' + representation + 'B' + poly.getMTime() + ('C' + (n ? n.getMTime() : 1) + 'D' + (c ? c.getMTime() : 1)) + ('E' + actor.getProperty().getEdgeVisibility()) + ('F' + (tcoords ? tcoords.getMTime() : 1));
if (model.VBOBuildString !== toString) {
// Build the VBOs
var points = poly.getPoints();
var options = {
points: points,
normals: n,
tcoords: tcoords,
colors: c,
cellOffset: 0,
haveCellScalars: model.haveCellScalars,
haveCellNormals: model.haveCellNormals
};
options.cellOffset += model.primitives[primTypes.Points].getCABO().createVBO(poly.getVerts(), 'verts', representation, options);
options.cellOffset += model.primitives[primTypes.Lines].getCABO().createVBO(poly.getLines(), 'lines', representation, options);
options.cellOffset += model.primitives[primTypes.Tris].getCABO().createVBO(poly.getPolys(), 'polys', representation, options);
options.cellOffset += model.primitives[primTypes.TriStrips].getCABO().createVBO(poly.getStrips(), 'strips', representation, options);
var drawSurfaceWithEdges = actor.getProperty().getEdgeVisibility() && representation === Representation.SURFACE;
// if we have edge visibility build the edge VBOs
if (drawSurfaceWithEdges) {
model.primitives[primTypes.TrisEdges].getCABO().createVBO(poly.getPolys(), 'polys', Representation.WIREFRAME, {
points: points,
normals: n,
tcoords: null,
colors: null,
cellOffset: 0,
haveCellScalars: false,
haveCellNormals: false
});
model.primitives[primTypes.TriStripsEdges].getCABO().createVBO(poly.getStrips(), 'strips', Representation.WIREFRAME, {
points: points,
normals: n,
tcoords: null,
colors: null,
cellOffset: 0,
haveCellScalars: false,
haveCellNormals: false
});
} else {
// otherwise free them
model.primitives[primTypes.TrisEdges].releaseGraphicsResources(model.openGLRenderWindow);
model.primitives[primTypes.TriStripsEdges].releaseGraphicsResources(model.openGLRenderWindow);
}
model.VBOBuildTime.modified();
model.VBOBuildString = toString;
}
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
context: null,
VBOBuildTime: 0,
VBOBuildString: null,
primitives: null,
primTypes: null,
shaderRebuildString: null,
tmpMat4: null,
ambientColor: [], // used internally
diffuseColor: [], // used internally
specularColor: [], // used internally
lightColor: [], // used internally
lightHalfAngle: [], // used internally
lightDirection: [], // used internally
lastHaveSeenDepthRequest: false,
haveSeenDepthRequest: false
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
_ViewNode2.default.extend(publicAPI, model, initialValues);
model.primitives = [];
model.primTypes = primTypes;
model.tmpMat4 = _glMatrix.mat4.create();
for (var i = primTypes.Start; i < primTypes.End; i++) {
model.primitives[i] = _Helper2.default.newInstance();
model.primitives[i].setPrimitiveType(i);
model.primitives[i].set({ lastLightComplexity: 0, lastLightCount: 0, lastSelectionPass: -1 }, true);
}
// Build VTK API
_macro2.default.setGet(publicAPI, model, ['context']);
model.VBOBuildTime = {};
_macro2.default.obj(model.VBOBuildTime, { mtime: 0 });
// Object methods
vtkOpenGLPolyDataMapper(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkOpenGLPolyDataMapper');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _CellArrayBufferObject = __webpack_require__(564);
var _CellArrayBufferObject2 = _interopRequireDefault(_CellArrayBufferObject);
var _ShaderProgram = __webpack_require__(42);
var _ShaderProgram2 = _interopRequireDefault(_ShaderProgram);
var _VertexArrayObject = __webpack_require__(276);
var _VertexArrayObject2 = _interopRequireDefault(_VertexArrayObject);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// ----------------------------------------------------------------------------
// vtkOpenGLHelper methods
// ----------------------------------------------------------------------------
function vtkOpenGLHelper(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLHelper');
publicAPI.setOpenGLRenderWindow = function (win) {
model.program.setContext(win.getContext());
model.VAO.setOpenGLRenderWindow(win);
model.CABO.setOpenGLRenderWindow(win);
};
publicAPI.releaseGraphicsResources = function (oglwin) {
model.VAO.releaseGraphicsResources();
model.CABO.releaseGraphicsResources();
model.CABO.setElementCount(0);
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
program: null,
shaderSourceTime: null,
VAO: null,
attributeUpdateTime: null,
CABO: null,
primitiveType: 0
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
_macro2.default.obj(publicAPI, model);
model.shaderSourceTime = {};
_macro2.default.obj(model.shaderSourceTime);
model.attributeUpdateTime = {};
_macro2.default.obj(model.attributeUpdateTime);
_macro2.default.setGet(publicAPI, model, ['program', 'shaderSourceTime', 'VAO', 'attributeUpdateTime', 'CABO', 'primitiveType']);
model.program = _ShaderProgram2.default.newInstance();
model.VAO = _VertexArrayObject2.default.newInstance();
model.CABO = _CellArrayBufferObject2.default.newInstance();
// Object methods
vtkOpenGLHelper(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend);
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = "//VTK::System::Dec\n\n/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPolyDataFS.glsl\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*/\n// Template for the polydata mappers fragment shader\n\nuniform int PrimitiveIDOffset;\n\n// VC position of this fragment\n//VTK::PositionVC::Dec\n\n// optional color passed in from the vertex shader, vertexColor\n//VTK::Color::Dec\n\n// optional surface normal declaration\n//VTK::Normal::Dec\n\n// extra lighting parameters\n//VTK::Light::Dec\n\n// Texture coordinates\n//VTK::TCoord::Dec\n\n// picking support\n//VTK::Picking::Dec\n\n// Depth Peeling Support\n//VTK::DepthPeeling::Dec\n\n// clipping plane vars\n//VTK::Clip::Dec\n\n// the output of this shader\n//VTK::Output::Dec\n\n// Apple Bug\n//VTK::PrimID::Dec\n\n// handle coincident offsets\n//VTK::Coincident::Dec\n\n//VTK::ZBuffer::Dec\n\nvoid main()\n{\n // VC position of this fragment. This should not branch/return/discard.\n //VTK::PositionVC::Impl\n\n // Place any calls that require uniform flow (e.g. dFdx) here.\n //VTK::UniformFlow::Impl\n\n // Set gl_FragDepth here (gl_FragCoord.z by default)\n //VTK::Depth::Impl\n\n // Early depth peeling abort:\n //VTK::DepthPeeling::PreColor\n\n // Apple Bug\n //VTK::PrimID::Impl\n\n //VTK::Clip::Impl\n\n //VTK::Color::Impl\n\n // Generate the normal if we are not passed in one\n //VTK::Normal::Impl\n\n //VTK::Light::Impl\n\n //VTK::TCoord::Impl\n\n if (gl_FragData[0].a <= 0.0)\n {\n discard;\n }\n\n //VTK::DepthPeeling::Impl\n\n //VTK::Picking::Impl\n\n // handle coincident offsets\n //VTK::Coincident::Impl\n\n //VTK::ZBuffer::Impl\n}\n";
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Top level file is just a mixin of submodules & constants
var assign = __webpack_require__(43).assign;
var deflate = __webpack_require__(607);
var inflate = __webpack_require__(610);
var constants = __webpack_require__(288);
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
if (!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = nextTick;
} else {
module.exports = process.nextTick;
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(87)))
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(89)
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
module.exports = {
/**
* True if this is running in Nodejs, will be undefined in a browser.
* In a browser, browserify won't include this file and the whole module
* will be resolved an empty object.
*/
isNode : typeof Buffer !== "undefined",
/**
* Create a new nodejs Buffer.
* @param {Object} data the data to pass to the constructor.
* @param {String} encoding the encoding to use.
* @return {Buffer} a new Buffer.
*/
newBuffer : function(data, encoding){
return new Buffer(data, encoding);
},
/**
* Find out if an object is a Buffer.
* @param {Object} b the object to test.
* @return {Boolean} true if the object is a Buffer, false otherwise.
*/
isBuffer : function(b){
return Buffer.isBuffer(b);
},
isStream : function (obj) {
return obj &&
typeof obj.on === "function" &&
typeof obj.pause === "function" &&
typeof obj.resume === "function";
}
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(89).Buffer))
/***/ }),
/* 112 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ }),
/* 113 */,
/* 114 */,
/* 115 */,
/* 116 */,
/* 117 */,
/* 118 */,
/* 119 */,
/* 120 */,
/* 121 */,
/* 122 */,
/* 123 */,
/* 124 */,
/* 125 */,
/* 126 */,
/* 127 */,
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.request = request;
var _wait = __webpack_require__(129);
var wait = _interopRequireWildcard(_wait);
var _error = __webpack_require__(77);
var error = _interopRequireWildcard(_error);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function request(uri, method, data, options) {
var request = {
url: uri,
type: method,
contentType: 'application/json',
accepts: 'application/json',
cache: false,
dataType: 'json',
data: JSON.stringify(data)
};
var d = { cb: [], error_cb: [], fd: false, fe: false, d: null };
console.log(request);
if (options) {
if (options.cache) request.cache = options.cache;
}
function success(data) {
wait.hide();
if (data.error !== undefined && data.error != 'none') {
error.show(data.error);
return;
}
for (var i in d.cb) {
d.cb[i](data);
}
d.d = data;
}
function failure() {
d.fe = true;
console.log('Got a failure');
wait.hide();
console.log(d.error_cb);
for (var i in d.error_cb) {
d.error_cb[i]();
}
}
request.error = failure;
d.done = function (cb) {
if (d.fd) {
cb(d.d);
return;
}
d.cb.push(cb);
};
d.error = function (cb) {
if (d.fe) {
cb();
}
d.error_cb.push(cb);
};
wait.show();
var req = $.ajax(request);
req.done(success);
req.fail(failure);
return d;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6)))
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hideInit = exports.showInit = exports.hide = exports.show = undefined;
var _sprintf = __webpack_require__(130);
var _sprintf2 = _interopRequireDefault(_sprintf);
__webpack_require__(48);
var _multimodal = __webpack_require__(76);
var multi = _interopRequireWildcard(_multimodal);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*require.resolve*/(49);
var code = [''].join('');
code = (0, _sprintf2.default)(code, { process_msg: 'Processing...' });
var pleaseWaitDiv = $(code);
var pleaseWaitDivInit = $(code);
var recurse = 0;
function show(immediate) {
if (recurse > 0) {
recurse++;
return;
}
recurse = 1;
multi.ensure(pleaseWaitDiv, function () {
pleaseWaitDiv.modal();
}, immediate, function () {
pleaseWaitDiv.modal('hide');
recurse--;
});
}
function hide(force) {
multi.end(pleaseWaitDiv);
}
function showInit(immediate) {
multi.ensure(pleaseWaitDivInit, function () {
pleaseWaitDivInit.modal();
}, immediate);
}
function hideInit(force) {
multi.end(pleaseWaitDivInit);
}
exports.show = show;
exports.hide = hide;
exports.showInit = showInit;
exports.hideInit = hideInit;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6)))
/***/ }),
/* 130 */,
/* 131 */,
/* 132 */,
/* 133 */,
/* 134 */,
/* 135 */,
/* 136 */,
/* 137 */,
/* 138 */,
/* 139 */,
/* 140 */,
/* 141 */,
/* 142 */,
/* 143 */,
/* 144 */,
/* 145 */,
/* 146 */,
/* 147 */,
/* 148 */,
/* 149 */,
/* 150 */,
/* 151 */,
/* 152 */,
/* 153 */,
/* 154 */,
/* 155 */,
/* 156 */,
/* 157 */,
/* 158 */,
/* 159 */,
/* 160 */,
/* 161 */,
/* 162 */,
/* 163 */,
/* 164 */,
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(529);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25)))
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _glMatrix = __webpack_require__(13);
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Prop3D = __webpack_require__(543);
var _Prop3D2 = _interopRequireDefault(_Prop3D);
var _Property = __webpack_require__(168);
var _Property2 = _interopRequireDefault(_Property);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var vtkDebugMacro = _macro2.default.vtkDebugMacro;
// ----------------------------------------------------------------------------
// vtkActor methods
// ----------------------------------------------------------------------------
function vtkActor(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkActor');
// Capture 'parentClass' api for internal use
var superClass = Object.assign({}, publicAPI);
publicAPI.getActors = function () {
return publicAPI;
};
publicAPI.getIsOpaque = function () {
if (model.forceOpaque) {
return true;
}
if (model.forceTranslucent) {
return false;
}
// make sure we have a property
if (!model.property) {
// force creation of a property
publicAPI.getProperty();
}
var isOpaque = model.property.getOpacity() >= 1.0;
// are we using an opaque texture, if any?
isOpaque = isOpaque && (!model.texture || !model.texture.isTranslucent());
// are we using an opaque scalar array, if any?
isOpaque = isOpaque && (!model.mapper || model.mapper.getIsOpaque());
return isOpaque;
};
publicAPI.hasTranslucentPolygonalGeometry = function () {
if (model.mapper === null) {
return false;
}
// make sure we have a property
if (model.property === null) {
// force creation of a property
publicAPI.setProperty(publicAPI.makeProperty());
}
// is this actor opaque ?
return !publicAPI.getIsOpaque();
};
publicAPI.makeProperty = _Property2.default.newInstance;
publicAPI.getProperty = function () {
if (model.property === null) {
model.property = publicAPI.makeProperty();
}
return model.property;
};
publicAPI.getBounds = function () {
if (model.mapper === null) {
return model.bounds;
}
// Check for the special case when the mapper's bounds are unknown
var bds = model.mapper.getBounds();
if (!bds || bds.length !== 6) {
return bds;
}
// Check for the special case when the actor is empty.
if (bds[0] > bds[1]) {
model.mapperBounds = bds.concat(); // copy the mapper's bounds
model.bounds = [1, -1, 1, -1, 1, -1];
model.boundsMTime.modified();
return bds;
}
// Check if we have cached values for these bounds - we cache the
// values returned by model.mapper.getBounds() and we store the time
// of caching. If the values returned this time are different, or
// the modified time of this class is newer than the cached time,
// then we need to rebuild.
if (!model.mapperBounds || bds[0] !== model.mapperBounds[0] || bds[1] !== model.mapperBounds[1] || bds[2] !== model.mapperBounds[2] || bds[3] !== model.mapperBounds[3] || bds[4] !== model.mapperBounds[4] || bds[5] !== model.mapperBounds[5] || publicAPI.getMTime() > model.boundsMTime.getMTime()) {
vtkDebugMacro('Recomputing bounds...');
model.mapperBounds = bds.concat(); // copy the mapper's bounds
var bbox = [_glMatrix.vec3.fromValues(bds[1], bds[3], bds[5]), _glMatrix.vec3.fromValues(bds[1], bds[2], bds[5]), _glMatrix.vec3.fromValues(bds[0], bds[2], bds[5]), _glMatrix.vec3.fromValues(bds[0], bds[3], bds[5]), _glMatrix.vec3.fromValues(bds[1], bds[3], bds[4]), _glMatrix.vec3.fromValues(bds[1], bds[2], bds[4]), _glMatrix.vec3.fromValues(bds[0], bds[2], bds[4]), _glMatrix.vec3.fromValues(bds[0], bds[3], bds[4])];
publicAPI.computeMatrix();
var tmp4 = _glMatrix.mat4.create();
_glMatrix.mat4.transpose(tmp4, model.matrix);
bbox.forEach(function (pt) {
return _glMatrix.vec3.transformMat4(pt, pt, tmp4);
});
/* eslint-disable no-multi-assign */
model.bounds[0] = model.bounds[2] = model.bounds[4] = Number.MAX_VALUE;
model.bounds[1] = model.bounds[3] = model.bounds[5] = -Number.MAX_VALUE;
/* eslint-enable no-multi-assign */
model.bounds = model.bounds.map(function (d, i) {
return i % 2 === 0 ? bbox.reduce(function (a, b) {
return a > b[i / 2] ? b[i / 2] : a;
}, d) : bbox.reduce(function (a, b) {
return a < b[(i - 1) / 2] ? b[(i - 1) / 2] : a;
}, d);
});
model.boundsMTime.modified();
}
return model.bounds;
};
publicAPI.getMTime = function () {
var mt = superClass.getMTime();
if (model.property !== null) {
var time = model.property.getMTime();
mt = time > mt ? time : mt;
}
if (model.backfaceProperty !== null) {
var _time = model.backfaceProperty.getMTime();
mt = _time > mt ? _time : mt;
}
return mt;
};
publicAPI.getRedrawMTime = function () {
var mt = model.mtime;
if (model.mapper !== null) {
var time = model.mapper.getMTime();
mt = time > mt ? time : mt;
if (model.mapper.getInput() !== null) {
// FIXME !!! getInputAlgorithm / getInput
model.mapper.getInputAlgorithm().update();
time = model.mapper.getInput().getMTime();
mt = time > mt ? time : mt;
}
}
return mt;
};
publicAPI.getSupportsSelection = function () {
return model.mapper ? model.mapper.getSupportsSelection() : false;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
mapper: null,
property: null,
backfaceProperty: null,
forceOpaque: false,
forceTranslucent: false,
bounds: [1, -1, 1, -1, 1, -1]
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
_Prop3D2.default.extend(publicAPI, model, initialValues);
// vtkTimeStamp
model.boundsMTime = {};
_macro2.default.obj(model.boundsMTime);
// Build VTK API
_macro2.default.set(publicAPI, model, ['property']);
_macro2.default.setGet(publicAPI, model, ['backfaceProperty', 'forceOpaque', 'forceTranslucent', 'mapper']);
// Object methods
vtkActor(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkActor');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = exports.STATIC = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Plane = __webpack_require__(544);
var _Plane2 = _interopRequireDefault(_Plane);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(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 INIT_BOUNDS = [Number.MAX_VALUE, -Number.MAX_VALUE, // X
Number.MAX_VALUE, -Number.MAX_VALUE, // Y
Number.MAX_VALUE, -Number.MAX_VALUE];
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
function isValid(bounds) {
return bounds[0] <= bounds[1] && bounds[2] <= bounds[3] && bounds[4] <= bounds[5];
}
function getCenter(bounds) {
return [0.5 * (bounds[0] + bounds[1]), 0.5 * (bounds[2] + bounds[3]), 0.5 * (bounds[4] + bounds[5])];
}
function getLength(bounds, index) {
return bounds[index * 2 + 1] - bounds[index * 2];
}
function getLengths(bounds) {
return [getLength(bounds, 0), getLength(bounds, 1), getLength(bounds, 2)];
}
function getXRange(bounds) {
return bounds.slice(0, 2);
}
function getYRange(bounds) {
return bounds.slice(2, 4);
}
function getZRange(bounds) {
return bounds.slice(4, 6);
}
function getMaxLength(bounds) {
var l = getLengths(bounds);
if (l[0] > l[1]) {
if (l[0] > l[2]) {
return l[0];
}
return l[2];
} else if (l[1] > l[2]) {
return l[1];
}
return l[2];
}
function getDiagonalLength(bounds) {
if (isValid(bounds)) {
var l = getLengths(bounds);
return Math.sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]);
}
return null;
}
function oppositeSign(a, b) {
return a <= 0 && b >= 0 || a >= 0 && b <= 0;
}
function getCorners(bounds, corners) {
var count = 0;
for (var ix = 0; ix < 2; ix++) {
for (var iy = 2; iy < 4; iy++) {
for (var iz = 4; iz < 6; iz++) {
corners[count] = [bounds[ix], bounds[iy], bounds[iz]];
count++;
}
}
}
}
// ----------------------------------------------------------------------------
// Static API
// ----------------------------------------------------------------------------
var STATIC = exports.STATIC = {
isValid: isValid,
getCenter: getCenter,
getLength: getLength,
getLengths: getLengths,
getMaxLength: getMaxLength,
getDiagonalLength: getDiagonalLength,
getXRange: getXRange,
getYRange: getYRange,
getZRange: getZRange,
getCorners: getCorners,
INIT_BOUNDS: INIT_BOUNDS
};
// ----------------------------------------------------------------------------
// vtkBoundingBox methods
// ----------------------------------------------------------------------------
function vtkBoundingBox(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkBoundingBox');
publicAPI.clone = function () {
var bounds = [].concat(model.bounds);
/* eslint-disable no-use-before-define */
return newInstance({ bounds: bounds });
/* eslint-enable no-use-before-define */
};
publicAPI.equals = function (other) {
var a = model.bounds;
var b = other.getBounds();
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5];
};
publicAPI.setMinPoint = function (x, y, z) {
var _model$bounds = _slicedToArray(model.bounds, 6),
xMin = _model$bounds[0],
xMax = _model$bounds[1],
yMin = _model$bounds[2],
yMax = _model$bounds[3],
zMin = _model$bounds[4],
zMax = _model$bounds[5];
model.bounds = [x, x > xMax ? x : xMax, y, y > yMax ? y : yMax, z, z > zMax ? z : zMax];
return xMin !== x || yMin !== y || zMin !== z;
};
publicAPI.setMaxPoint = function (x, y, z) {
var _model$bounds2 = _slicedToArray(model.bounds, 6),
xMin = _model$bounds2[0],
xMax = _model$bounds2[1],
yMin = _model$bounds2[2],
yMax = _model$bounds2[3],
zMin = _model$bounds2[4],
zMax = _model$bounds2[5];
model.bounds = [x < xMin ? x : xMin, x, y < yMin ? y : yMin, y, z < zMin ? z : zMin, z];
return xMax !== x || yMax !== y || zMax !== z;
};
publicAPI.addPoint = function () {
for (var _len = arguments.length, xyz = Array(_len), _key = 0; _key < _len; _key++) {
xyz[_key] = arguments[_key];
}
model.bounds = model.bounds.map(function (value, index) {
if (index % 2 === 0) {
var _idx = index / 2;
return value < xyz[_idx] ? value : xyz[_idx];
}
var idx = (index - 1) / 2;
return value > xyz[idx] ? value : xyz[idx];
});
};
publicAPI.addBounds = function (xMin, xMax, yMin, yMax, zMin, zMax) {
var _model$bounds3 = _slicedToArray(model.bounds, 6),
_xMin = _model$bounds3[0],
_xMax = _model$bounds3[1],
_yMin = _model$bounds3[2],
_yMax = _model$bounds3[3],
_zMin = _model$bounds3[4],
_zMax = _model$bounds3[5];
model.bounds = [Math.min(xMin, _xMin), Math.max(xMax, _xMax), Math.min(yMin, _yMin), Math.max(yMax, _yMax), Math.min(zMin, _zMin), Math.max(zMax, _zMax)];
};
publicAPI.addBox = function (other) {
publicAPI.addBounds.apply(publicAPI, _toConsumableArray(other.getBounds()));
};
publicAPI.isValid = function () {
return isValid(model.bounds);
};
publicAPI.intersect = function (bbox) {
if (!(publicAPI.isValid() && bbox.isValid())) {
return false;
}
var newBounds = [0, 0, 0, 0, 0, 0];
var bBounds = bbox.getBounds();
var intersects = void 0;
for (var i = 0; i < 3; i++) {
intersects = false;
if (bBounds[i * 2] >= model.bounds[i * 2] && bBounds[i * 2] <= model.bounds[i * 2 + 1]) {
intersects = true;
newBounds[i * 2] = bBounds[i * 2];
} else if (model.bounds[i * 2] >= bBounds[i * 2] && model.bounds[i * 2] <= bBounds[i * 2 + 1]) {
intersects = true;
newBounds[i * 2] = model.bounds[i * 2];
}
if (bBounds[i * 2 + 1] >= model.bounds[i * 2] && bBounds[i * 2 + 1] <= model.bounds[i * 2 + 1]) {
intersects = true;
newBounds[i * 2 + 1] = bbox.MaxPnt[i];
} else if (model.bounds[i * 2 + 1] >= bbox.MinPnt[i * 2] && model.bounds[i * 2 + 1] <= bbox.MaxPnt[i * 2 + 1]) {
intersects = true;
newBounds[i * 2 + 1] = model.bounds[i * 2 + 1];
}
if (!intersects) {
return false;
}
}
// OK they did intersect - set the box to be the result
model.bounds = newBounds;
return true;
};
publicAPI.intersects = function (bbox) {
if (!(publicAPI.isValid() && bbox.isValid())) {
return false;
}
var bBounds = bbox.getBounds();
/* eslint-disable no-continue */
for (var i = 0; i < 3; i++) {
if (bBounds[i * 2] >= model.bounds[i * 2] && bBounds[i * 2] <= model.bounds[i * 2 + 1]) {
continue;
} else if (model.bounds[i * 2] >= bBounds[i * 2] && model.bounds[i * 2] <= bBounds[i * 2 + 1]) {
continue;
}
if (bBounds[i * 2 + 1] >= model.bounds[i * 2] && bBounds[i * 2 + 1] <= model.bounds[i * 2 + 1]) {
continue;
} else if (model.bounds[i * 2 + 1] >= bbox.MinPnt[i * 2] && model.bounds[i * 2 + 1] <= bbox.MaxPnt[i * 2 + 1]) {
continue;
}
return false;
}
/* eslint-enable no-continue */
return true;
};
publicAPI.intersectPlane = function (origin, normal) {
// Index[0..2] represents the order of traversing the corners of a cube
// in (x,y,z), (y,x,z) and (z,x,y) ordering, respectively
var index = [[0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 4, 5, 2, 3, 6, 7], [0, 2, 4, 6, 1, 3, 5, 7]];
// stores the signed distance to a plane
var d = [0, 0, 0, 0, 0, 0, 0, 0];
var idx = 0;
for (var ix = 0; ix < 2; ix++) {
for (var iy = 2; iy < 4; iy++) {
for (var iz = 4; iz < 6; iz++) {
var x = [model.bounds[ix], model.bounds[iy], model.bounds[iz]];
d[idx++] = _Plane2.default.evaluate(normal, origin, x);
}
}
}
var dir = 2;
while (dir--) {
// in each direction, we test if the vertices of two orthogonal faces
// are on either side of the plane
if (oppositeSign(d[index[dir][0]], d[index[dir][4]]) && oppositeSign(d[index[dir][1]], d[index[dir][5]]) && oppositeSign(d[index[dir][2]], d[index[dir][6]]) && oppositeSign(d[index[dir][3]], d[index[dir][7]])) {
break;
}
}
if (dir < 0) {
return false;
}
var sign = Math.sign(normal[dir]);
var size = Math.abs((model.bounds[dir * 2 + 1] - model.bounds[dir * 2]) * normal[dir]);
var t = sign > 0 ? 1 : 0;
/* eslint-disable no-continue */
for (var i = 0; i < 4; i++) {
if (size === 0) {
continue; // shouldn't happen
}
var ti = Math.abs(d[index[dir][i]]) / size;
if (sign > 0 && ti < t) {
t = ti;
}
if (sign < 0 && ti > t) {
t = ti;
}
}
/* eslint-enable no-continue */
var bound = (1.0 - t) * model.bounds[dir * 2] + t * model.bounds[dir * 2 + 1];
if (sign > 0) {
model.bounds[dir * 2] = bound;
} else {
model.bounds[dir * 2 + 1] = bound;
}
return true;
};
publicAPI.containsPoint = function (x, y, z) {
if (x < model.bounds[0] || x > model.bounds[1]) {
return false;
}
if (y < model.bounds[2] || y > model.bounds[3]) {
return false;
}
if (z < model.bounds[4] || z > model.bounds[5]) {
return false;
}
return true;
};
publicAPI.getMinPoint = function () {
return [model.bounds[0], model.bounds[2], model.bounds[4]];
};
publicAPI.getMaxPoint = function () {
return [model.bounds[1], model.bounds[3], model.bounds[5]];
};
publicAPI.getBound = function (index) {
return model.bound[index];
};
publicAPI.contains = function (bbox) {
// if either box is not valid or they don't intersect
if (!publicAPI.intersects(bbox)) {
return false;
}
if (!publicAPI.containsPoint.apply(publicAPI, _toConsumableArray(bbox.getMinPoint()))) {
return false;
}
if (!publicAPI.containsPoint.apply(publicAPI, _toConsumableArray(bbox.getMaxPoint()))) {
return 0;
}
return true;
};
publicAPI.getCenter = function () {
return getCenter(model.bounds);
};
publicAPI.getLength = function (index) {
return getLength(model.bounds, index);
};
publicAPI.getLengths = function () {
return getLengths(model.bounds);
};
publicAPI.getMaxLength = function () {
return getMaxLength(model.bounds);
};
publicAPI.getDiagonalLength = function () {
return getDiagonalLength(model.bounds);
};
publicAPI.reset = function () {
return publicAPI.setBounds([].concat(INIT_BOUNDS));
};
publicAPI.inflate = function (delta) {
model.bounds = model.bounds.map(function (value, index) {
if (index % 2 === 0) {
return value - delta;
}
return value + delta;
});
};
publicAPI.getCorners = function () {
getCorners(model.bounds, model.corners);
return model.corners;
};
publicAPI.scale = function (sx, sy, sz) {
if (publicAPI.isValid()) {
var newBounds = [].concat(model.bounds);
if (sx >= 0.0) {
newBounds[0] *= sx;
newBounds[1] *= sx;
} else {
newBounds[0] = sx * model.bounds[1];
newBounds[1] = sx * model.bounds[0];
}
if (sy >= 0.0) {
newBounds[2] *= sy;
newBounds[3] *= sy;
} else {
newBounds[2] = sy * model.bounds[3];
newBounds[3] = sy * model.bounds[2];
}
if (sz >= 0.0) {
newBounds[4] *= sz;
newBounds[5] *= sz;
} else {
newBounds[4] = sz * model.bounds[5];
newBounds[5] = sz * model.bounds[4];
}
model.bounds = newBounds;
return true;
}
return false;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
type: 'vtkBoundingBox',
bounds: [].concat(INIT_BOUNDS),
corners: []
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Object methods
_macro2.default.obj(publicAPI, model);
_macro2.default.setGet(publicAPI, model, ['bounds']);
vtkBoundingBox(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkBoundingBox');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, STATIC);
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Constants = __webpack_require__(66);
var _Constants2 = _interopRequireDefault(_Constants);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Representation = _Constants2.default.Representation,
Interpolation = _Constants2.default.Interpolation;
function notImplemented(method) {
return function () {
return _macro2.default.vtkErrorMacro('vtkProperty::' + method + ' - NOT IMPLEMENTED');
};
}
// ----------------------------------------------------------------------------
// vtkProperty methods
// ----------------------------------------------------------------------------
function vtkProperty(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkProperty');
publicAPI.setColor = function (r, g, b) {
if (model.color[0] !== r || model.color[1] !== g || model.color[2] !== b) {
model.color[0] = r;
model.color[1] = g;
model.color[2] = b;
publicAPI.modified();
}
publicAPI.setDiffuseColor(model.color);
publicAPI.setAmbientColor(model.color);
publicAPI.setSpecularColor(model.color);
};
publicAPI.computeCompositeColor = notImplemented('ComputeCompositeColor');
publicAPI.getColor = function () {
// Inline computeCompositeColor
var norm = 0.0;
if (model.ambient + model.diffuse + model.specular > 0) {
norm = 1.0 / (model.ambient + model.diffuse + model.specular);
}
for (var i = 0; i < 3; i++) {
model.color[i] = norm * (model.ambient * model.ambientColor[i] + model.diffuse * model.diffuseColor[i] + model.specular * model.specularColor[i]);
}
return [].concat(model.color);
};
publicAPI.addShaderVariable = notImplemented('AddShaderVariable');
publicAPI.setInterpolationToFlat = function () {
return publicAPI.setInterpolation(Interpolation.FLAT);
};
publicAPI.setInterpolationToGouraud = function () {
return publicAPI.setInterpolation(Interpolation.GOURAUD);
};
publicAPI.setInterpolationToPhong = function () {
return publicAPI.setInterpolation(Interpolation.PHONG);
};
publicAPI.getInterpolationAsString = function () {
return _macro2.default.enumToString(Interpolation, model.interpolation);
};
publicAPI.setRepresentationToWireframe = function () {
return publicAPI.setRepresentation(Representation.WIREFRAME);
};
publicAPI.setRepresentationToSurface = function () {
return publicAPI.setRepresentation(Representation.SURFACE);
};
publicAPI.setRepresentationToPoints = function () {
return publicAPI.setRepresentation(Representation.POINTS);
};
publicAPI.getRepresentationAsString = function () {
return _macro2.default.enumToString(Representation, model.representation);
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
color: [1, 1, 1],
ambientColor: [1, 1, 1],
diffuseColor: [1, 1, 1],
specularColor: [1, 1, 1],
edgeColor: [0, 0, 0],
ambient: 0,
diffuse: 1,
specular: 0,
specularPower: 1,
opacity: 1,
interpolation: Interpolation.GOURAUD,
representation: Representation.SURFACE,
edgeVisibility: false,
backfaceCulling: false,
frontfaceCulling: false,
pointSize: 1,
lineWidth: 1,
lighting: true,
shading: false,
materialName: null
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
_macro2.default.obj(publicAPI, model);
_macro2.default.setGet(publicAPI, model, ['lighting', 'interpolation', 'ambient', 'diffuse', 'specular', 'specularPower', 'opacity', 'edgeVisibility', 'lineWidth', 'pointSize', 'backfaceCulling', 'frontfaceCulling', 'representation']);
_macro2.default.setGetArray(publicAPI, model, ['ambientColor', 'specularColor', 'diffuseColor', 'edgeColor'], 3);
// Object methods
vtkProperty(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkProperty');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, _Constants2.default);
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var macro = _interopRequireWildcard(_macro);
var _Texture = __webpack_require__(67);
var _Texture2 = _interopRequireDefault(_Texture);
var _Constants = __webpack_require__(32);
var _Constants2 = __webpack_require__(103);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
// ----------------------------------------------------------------------------
// vtkFramebuffer methods
// ----------------------------------------------------------------------------
function vtkFramebuffer(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkFramebuffer');
publicAPI.getBothMode = function () {
return model.context.FRAMEBUFFER;
};
// publicAPI.getDrawMode = () => model.context.DRAW_FRAMEBUFFER;
// publicAPI.getReadMode = () => model.context.READ_FRAMEBUFFER;
publicAPI.saveCurrentBindingsAndBuffers = function (modeIn) {
var mode = typeof modeIn !== 'undefined' ? modeIn : publicAPI.getBothMode();
publicAPI.saveCurrentBindings(mode);
publicAPI.saveCurrentBuffers(mode);
};
publicAPI.saveCurrentBindings = function (modeIn) {
var gl = model.context;
model.previousDrawBinding = gl.getParameter(model.context.FRAMEBUFFER_BINDING);
model.previousActiveFramebuffer = model.openGLRenderWindow.getActiveFramebuffer();
};
publicAPI.saveCurrentBuffers = function (modeIn) {
// noop on webgl 1
};
publicAPI.restorePreviousBindingsAndBuffers = function (modeIn) {
var mode = typeof modeIn !== 'undefined' ? modeIn : publicAPI.getBothMode();
publicAPI.restorePreviousBindings(mode);
publicAPI.restorePreviousBuffers(mode);
};
publicAPI.restorePreviousBindings = function (modeIn) {
var gl = model.context;
gl.bindFramebuffer(gl.FRAMEBUFFER, model.previousDrawBinding);
model.openGLRenderWindow.setActiveFramebuffer(model.previousActiveFramebuffer);
};
publicAPI.restorePreviousBuffers = function (modeIn) {
// currently a noop on webgl1
};
publicAPI.bind = function () {
model.context.bindFramebuffer(model.context.FRAMEBUFFER, model.glFramebuffer);
if (model.colorTexture) {
model.colorTexture.bind();
}
model.openGLRenderWindow.setActiveFramebuffer(publicAPI);
};
publicAPI.create = function (width, height) {
model.glFramebuffer = model.context.createFramebuffer();
model.glFramebuffer.width = width;
model.glFramebuffer.height = height;
};
publicAPI.setColorBuffer = function (texture, mode) {
var gl = model.context;
model.colorTexture = texture;
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture.getHandle(), 0);
};
// publicAPI.setDepthBuffer = (texture, mode) => {
// const gl = model.context;
// gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, texture.getHandle(), 0);
// };
publicAPI.getGLFramebuffer = function () {
return model.glFramebuffer;
};
publicAPI.setOpenGLRenderWindow = function (rw) {
if (model.openGLRenderWindow === rw) {
return;
}
publicAPI.releaseGraphicsResources();
model.openGLRenderWindow = rw;
model.context = null;
if (rw) {
model.context = model.openGLRenderWindow.getContext();
}
};
publicAPI.releaseGraphicsResources = function () {
if (model.glFramebuffer) {
model.context.deleteFramebuffer(model.glFramebuffer);
}
if (model.depthTexture) {
model.depthTexture.releaseGraphicsResources();
}
if (model.colorTexture) {
model.colorTexture.releaseGraphicsResources();
}
};
publicAPI.getSize = function () {
var size = [0, 0];
if (model.glFramebuffer !== null) {
size[0] = model.glFramebuffer.width;
size[1] = model.glFramebuffer.height;
}
return size;
};
publicAPI.populateFramebuffer = function () {
publicAPI.bind();
var gl = model.context;
var texture = _Texture2.default.newInstance();
texture.setOpenGLRenderWindow(model.openGLRenderWindow);
texture.setMinificationFilter(_Constants2.Filter.LINEAR);
texture.setMagnificationFilter(_Constants2.Filter.LINEAR);
texture.create2DFromRaw(model.glFramebuffer.width, model.glFramebuffer.height, 4, _Constants.VtkDataTypes.UNSIGNED_CHAR, null);
publicAPI.setColorBuffer(texture);
// for now do not count of having a depth buffer texture
// as they are not standard webgl 1
model.depthTexture = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, model.depthTexture);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, model.glFramebuffer.width, model.glFramebuffer.height);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, model.depthTexture);
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
openGLRenderWindow: null,
glFramebuffer: null,
colorTexture: null,
depthTexture: null,
previousDrawBinding: 0,
previousReadBinding: 0,
previousDrawBuffer: 0,
previousReadBuffer: 0,
previousActiveFramebuffer: null
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
macro.obj(publicAPI, model);
macro.setGet(publicAPI, model, ['colorTexture']);
// For more macro methods, see "Sources/macro.js"
// Object specific methods
vtkFramebuffer(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = macro.newInstance(extend, 'vtkFramebuffer');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend });
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _vtk = __webpack_require__(63);
var _vtk2 = _interopRequireDefault(_vtk);
var _DataSetAttributes = __webpack_require__(561);
var _DataSetAttributes2 = _interopRequireDefault(_DataSetAttributes);
var _Constants = __webpack_require__(563);
var _Constants2 = _interopRequireDefault(_Constants);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// import vtkBoundingBox from '../BoundingBox';
// import vtkMath from '../../Core/Math';
//
// function getBounds(dataset) {
// if (dataset.bounds) {
// return dataset.bounds;
// }
// if (dataset.type && dataset[dataset.type]) {
// const ds = dataset[dataset.type];
// if (ds.bounds) {
// return ds.bounds;
// }
// if (ds.Points && ds.Points.bounds) {
// return ds.Points.bounds;
// }
// if (ds.Points && ds.Points.values) {
// const array = ds.Points.values;
// const bbox = vtkBoundingBox.newInstance();
// const size = array.length;
// const delta = ds.Points.numberOfComponents ? ds.Points.numberOfComponents : 3;
// for (let idx = 0; idx < size; idx += delta) {
// bbox.addPoint(array[idx * delta], array[(idx * delta) + 1], array[(idx * delta) + 2]);
// }
// ds.Points.bounds = bbox.getBounds();
// return ds.Points.bounds;
// }
// }
// return vtkMath.createUninitializedBounds();
// }
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
var DATASET_FIELDS = ['pointData', 'cellData', 'fieldData'];
// ----------------------------------------------------------------------------
// vtkDataSet methods
// ----------------------------------------------------------------------------
function vtkDataSet(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkDataSet');
// Add dataset attributes
DATASET_FIELDS.forEach(function (fieldName) {
if (!model[fieldName]) {
model[fieldName] = _DataSetAttributes2.default.newInstance();
} else {
model[fieldName] = (0, _vtk2.default)(model[fieldName]);
}
});
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
// pointData: null,
// cellData: null,
// fieldData: null,
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Object methods
_macro2.default.obj(publicAPI, model);
_macro2.default.setGet(publicAPI, model, DATASET_FIELDS);
// Object specific methods
vtkDataSet(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkDataSet');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, _Constants2.default);
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _DataSet = __webpack_require__(170);
var _DataSet2 = _interopRequireDefault(_DataSet);
var _StructuredData = __webpack_require__(568);
var _StructuredData2 = _interopRequireDefault(_StructuredData);
var _Constants = __webpack_require__(277);
var _glMatrix = __webpack_require__(13);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var vtkErrorMacro = _macro2.default.vtkErrorMacro;
// ----------------------------------------------------------------------------
// vtkImageData methods
// ----------------------------------------------------------------------------
function vtkImageData(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkImageData');
publicAPI.setExtent = function () {
for (var _len = arguments.length, inExtent = Array(_len), _key = 0; _key < _len; _key++) {
inExtent[_key] = arguments[_key];
}
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
if (!inExtent || inExtent.length !== 6) {
return;
}
var changeDetected = false;
model.extent.forEach(function (item, index) {
if (item !== inExtent[index]) {
if (changeDetected) {
return;
}
changeDetected = true;
}
});
if (changeDetected) {
model.extent = [].concat(inExtent);
model.dataDescription = _StructuredData2.default.getDataDescriptionFromExtent(model.extent);
publicAPI.modified();
}
};
publicAPI.setDimensions = function () {
var i = void 0;
var j = void 0;
var k = void 0;
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return;
}
if (arguments.length === 1) {
var array = arguments.length <= 0 ? undefined : arguments[0];
i = array[0];
j = array[1];
k = array[2];
} else if (arguments.length === 3) {
i = arguments.length <= 0 ? undefined : arguments[0];
j = arguments.length <= 1 ? undefined : arguments[1];
k = arguments.length <= 2 ? undefined : arguments[2];
} else {
vtkErrorMacro('Bad dimension specification');
return;
}
publicAPI.setExtent(0, i - 1, 0, j - 1, 0, k - 1);
};
publicAPI.getDimensions = function () {
return [model.extent[1] - model.extent[0] + 1, model.extent[3] - model.extent[2] + 1, model.extent[5] - model.extent[4] + 1];
};
publicAPI.getNumberOfCells = function () {
var dims = publicAPI.getDimensions();
var nCells = 1;
for (var i = 0; i < 3; i++) {
if (dims[i] === 0) {
return 0;
}
if (dims[i] > 1) {
nCells *= dims[i] - 1;
}
}
return nCells;
};
publicAPI.getNumberOfPoints = function () {
var dims = publicAPI.getDimensions();
return dims[0] * dims[1] * dims[2];
};
publicAPI.getPoint = function (index) {
var dims = publicAPI.getDimensions();
var ijk = _glMatrix.vec3.fromValues(0, 0, 0);
var coords = [0, 0, 0];
if (dims[0] === 0 || dims[1] === 0 || dims[2] === 0) {
vtkErrorMacro('Requesting a point from an empty image.');
return null;
}
switch (model.dataDescription) {
case _Constants.StructuredType.EMPTY:
return null;
case _Constants.StructuredType.SINGLE_POINT:
break;
case _Constants.StructuredType.X_LINE:
ijk[0] = index;
break;
case _Constants.StructuredType.Y_LINE:
ijk[1] = index;
break;
case _Constants.StructuredType.Z_LINE:
ijk[2] = index;
break;
case _Constants.StructuredType.XY_PLANE:
ijk[0] = index % dims[0];
ijk[1] = index / dims[0];
break;
case _Constants.StructuredType.YZ_PLANE:
ijk[1] = index % dims[1];
ijk[2] = index / dims[1];
break;
case _Constants.StructuredType.XZ_PLANE:
ijk[0] = index % dims[0];
ijk[2] = index / dims[0];
break;
case _Constants.StructuredType.XYZ_GRID:
ijk[0] = index % dims[0];
ijk[1] = index / dims[0] % dims[1];
ijk[2] = index / (dims[0] * dims[1]);
break;
default:
vtkErrorMacro('Invalid dataDescription');
break;
}
var vout = _glMatrix.vec3.create();
publicAPI.indexToWorldVec3(ijk, vout);
_glMatrix.vec3.copy(coords, vout);
return coords;
};
// vtkCell *GetCell(vtkIdType cellId) VTK_OVERRIDE;
// void GetCell(vtkIdType cellId, vtkGenericCell *cell) VTK_OVERRIDE;
// void GetCellBounds(vtkIdType cellId, double bounds[6]) VTK_OVERRIDE;
// virtual vtkIdType FindPoint(double x, double y, double z)
// {
// return this->vtkDataSet::FindPoint(x, y, z);
// }
// vtkIdType FindPoint(double x[3]) VTK_OVERRIDE;
// vtkIdType FindCell(
// double x[3], vtkCell *cell, vtkIdType cellId, double tol2,
// int& subId, double pcoords[3], double *weights) VTK_OVERRIDE;
// vtkIdType FindCell(
// double x[3], vtkCell *cell, vtkGenericCell *gencell,
// vtkIdType cellId, double tol2, int& subId,
// double pcoords[3], double *weights) VTK_OVERRIDE;
// vtkCell *FindAndGetCell(double x[3], vtkCell *cell, vtkIdType cellId,
// double tol2, int& subId, double pcoords[3],
// double *weights) VTK_OVERRIDE;
// int GetCellType(vtkIdType cellId) VTK_OVERRIDE;
// void GetCellPoints(vtkIdType cellId, vtkIdList *ptIds) VTK_OVERRIDE
// {vtkStructuredData::GetCellPoints(cellId,ptIds,this->DataDescription,
// this->GetDimensions());}
// void GetPointCells(vtkIdType ptId, vtkIdList *cellIds) VTK_OVERRIDE
// {vtkStructuredData::GetPointCells(ptId,cellIds,this->GetDimensions());}
// void ComputeBounds() VTK_OVERRIDE;
// int GetMaxCellSize() VTK_OVERRIDE {return 8;}; //voxel is the largest
publicAPI.getBounds = function () {
return publicAPI.extentToBounds(model.extent);
};
publicAPI.extentToBounds = function (ex) {
// prettier-ignore
var corners = [ex[0], ex[2], ex[4], ex[1], ex[2], ex[4], ex[0], ex[3], ex[4], ex[1], ex[3], ex[4], ex[0], ex[2], ex[5], ex[1], ex[2], ex[5], ex[0], ex[3], ex[5], ex[1], ex[3], ex[5]];
var idx = _glMatrix.vec3.fromValues(corners[0], corners[1], corners[2]);
var vout = _glMatrix.vec3.create();
publicAPI.indexToWorldVec3(idx, vout);
var bounds = [vout[0], vout[0], vout[1], vout[1], vout[2], vout[2]];
for (var i = 3; i < 24; i += 3) {
_glMatrix.vec3.set(idx, corners[i], corners[i + 1], corners[i + 2]);
publicAPI.indexToWorldVec3(idx, vout);
if (vout[0] < bounds[0]) {
bounds[0] = vout[0];
}
if (vout[1] < bounds[2]) {
bounds[2] = vout[1];
}
if (vout[2] < bounds[4]) {
bounds[4] = vout[2];
}
if (vout[0] > bounds[1]) {
bounds[1] = vout[0];
}
if (vout[1] > bounds[3]) {
bounds[3] = vout[1];
}
if (vout[2] > bounds[5]) {
bounds[5] = vout[2];
}
}
return bounds;
};
publicAPI.computeTransforms = function () {
var rotq = _glMatrix.quat.create();
_glMatrix.quat.fromMat3(rotq, model.direction);
var trans = _glMatrix.vec3.fromValues(model.origin[0], model.origin[1], model.origin[2]);
var scale = _glMatrix.vec3.fromValues(model.spacing[0], model.spacing[1], model.spacing[2]);
_glMatrix.mat4.fromRotationTranslationScale(model.indexToWorld, rotq, trans, scale);
_glMatrix.mat4.invert(model.worldToIndex, model.indexToWorld);
};
//
// The direction matrix is a 3x3 basis for the I, J, K axes
// of the image. The rows of the matrix correspond to the
// axes directions in world coordinates. Direction must
// form an orthonormal basis, results are undefined if
// it is not.
//
publicAPI.setDirection = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (model.deleted) {
vtkErrorMacro('instance deleted - cannot call any method');
return false;
}
var array = args;
// allow an array passed as a single arg.
if (array.length === 1 && Array.isArray(array[0])) {
array = array[0];
}
if (array.length !== 9) {
throw new RangeError('Invalid number of values for array setter');
}
var changeDetected = false;
model.direction.forEach(function (item, index) {
if (item !== array[index]) {
if (changeDetected) {
return;
}
changeDetected = true;
}
});
if (changeDetected) {
for (var i = 0; i < 9; ++i) {
model.direction[i] = array[i];
}
publicAPI.modified();
}
return true;
};
// this is the fast version, requires vec3 arguments
publicAPI.indexToWorldVec3 = function (vin, vout) {
_glMatrix.vec3.transformMat4(vout, vin, model.indexToWorld);
};
// slow version for generic arrays
publicAPI.indexToWorld = function (ain, aout) {
var vin = _glMatrix.vec3.fromValues(ain[0], ain[1], ain[2]);
var vout = _glMatrix.vec3.create();
_glMatrix.vec3.transformMat4(vout, vin, model.indexToWorld);
_glMatrix.vec3.copy(aout, vout);
};
// this is the fast version, requires vec3 arguments
publicAPI.worldToIndexVec3 = function (vin, vout) {
_glMatrix.vec3.transformMat4(vout, vin, model.worldToIndex);
};
// slow version for generic arrays
publicAPI.worldToIndex = function (ain, aout) {
var vin = _glMatrix.vec3.fromValues(ain[0], ain[1], ain[2]);
var vout = _glMatrix.vec3.create();
_glMatrix.vec3.transformMat4(vout, vin, model.worldToIndex);
_glMatrix.vec3.copy(aout, vout);
};
// Make sure the transform is correct
publicAPI.onModified(publicAPI.computeTransforms);
publicAPI.computeTransforms();
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
direction: null, // a mat3
indexToWorld: null, // a mat4
worldToIndex: null, // a mat4
spacing: [1.0, 1.0, 1.0],
origin: [0.0, 0.0, 0.0],
extent: [0, -1, 0, -1, 0, -1],
dataDescription: _Constants.StructuredType.EMPTY
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
_DataSet2.default.extend(publicAPI, model, initialValues);
if (!model.direction) {
model.direction = _glMatrix.mat3.create();
} else if (Array.isArray(model.direction)) {
var dvals = model.direction.slice(0);
model.direction = _glMatrix.mat3.create();
for (var i = 0; i < 9; ++i) {
model.direction[i] = dvals[i];
}
}
model.indexToWorld = _glMatrix.mat4.create();
model.worldToIndex = _glMatrix.mat4.create();
// Set/Get methods
_macro2.default.get(publicAPI, model, ['direction', 'indexToWorld', 'worldToIndex']);
_macro2.default.setGetArray(publicAPI, model, ['origin', 'spacing'], 3);
_macro2.default.getArray(publicAPI, model, ['extent'], 6);
// Object specific methods
vtkImageData(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkImageData');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var VectorMode = exports.VectorMode = {
MAGNITUDE: 0,
COMPONENT: 1,
RGBCOLORS: 2
};
var ScalarMappingTarget = exports.ScalarMappingTarget = {
LUMINANCE: 1,
LUMINANCE_ALPHA: 2,
RGB: 3,
RGBA: 4
};
exports.default = {
VectorMode: VectorMode,
ScalarMappingTarget: ScalarMappingTarget
};
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _DataArray = __webpack_require__(16);
var _DataArray2 = _interopRequireDefault(_DataArray);
var _Constants = __webpack_require__(32);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var vtkErrorMacro = _macro2.default.vtkErrorMacro;
var INVALID_BOUNDS = [1, -1, 1, -1, 1, -1];
// ----------------------------------------------------------------------------
// vtkPoints methods
// ----------------------------------------------------------------------------
function vtkPoints(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkPoints');
// Forwarding methods
publicAPI.getNumberOfPoints = publicAPI.getNumberOfTuples;
publicAPI.setNumberOfPoints = function (nbPoints) {
var dimension = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
if (publicAPI.getNumberOfPoints() !== nbPoints) {
model.size = nbPoints * dimension;
model.values = new window[model.dataType](model.size);
publicAPI.setNumberOfComponents(dimension);
publicAPI.modified();
}
};
publicAPI.setPoint = function (idx) {
for (var _len = arguments.length, xyz = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
xyz[_key - 1] = arguments[_key];
}
var offset = idx * model.numberOfComponents;
for (var i = 0; i < model.numberOfComponents; i++) {
model.values[offset + i] = xyz[i];
}
};
publicAPI.getPoint = publicAPI.getTuple;
publicAPI.getBounds = function () {
if (publicAPI.getNumberOfComponents() === 3) {
var _xRange = publicAPI.getRange(0);
model.bounds[0] = _xRange[0];
model.bounds[1] = _xRange[1];
var _yRange = publicAPI.getRange(1);
model.bounds[2] = _yRange[0];
model.bounds[3] = _yRange[1];
var zRange = publicAPI.getRange(2);
model.bounds[4] = zRange[0];
model.bounds[5] = zRange[1];
return model.bounds;
}
if (publicAPI.getNumberOfComponents() !== 2) {
vtkErrorMacro('getBounds called on an array with components of\n ' + publicAPI.getNumberOfComponents());
return INVALID_BOUNDS;
}
var xRange = publicAPI.getRange(0);
model.bounds[0] = xRange[0];
model.bounds[1] = xRange[1];
var yRange = publicAPI.getRange(1);
model.bounds[2] = yRange[0];
model.bounds[3] = yRange[1];
model.bounds[4] = 0;
model.bounds[5] = 0;
return model.bounds;
};
// Trigger the computation of bounds
publicAPI.computeBounds = publicAPI.getBounds;
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
empty: true,
numberOfComponents: 3,
dataType: _Constants.VtkDataTypes.FLOAT,
bounds: [1, -1, 1, -1, 1, -1]
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
_DataArray2.default.extend(publicAPI, model, initialValues);
vtkPoints(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkPoints');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
module.exports = {
2: 'need dictionary', /* Z_NEED_DICT 2 */
1: 'stream end', /* Z_STREAM_END 1 */
0: '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getEndianness = getEndianness;
exports.swapBytes = swapBytes;
function getEndianness() {
var a = new ArrayBuffer(4);
var b = new Uint8Array(a);
var c = new Uint32Array(a);
b[0] = 0xa1;
b[1] = 0xb2;
b[2] = 0xc3;
b[3] = 0xd4;
if (c[0] === 0xd4c3b2a1) return 'LittleEndian';
if (c[0] === 0xa1b2c3d4) return 'BigEndian';
return null;
}
var ENDIANNESS = exports.ENDIANNESS = getEndianness();
function swapBytes(buffer, wordSize) {
if (wordSize < 2) {
return;
}
var bytes = new Int8Array(buffer);
var size = bytes.length;
var tempBuffer = [];
for (var i = 0; i < size; i += wordSize) {
for (var j = 0; j < wordSize; j++) {
tempBuffer.push(bytes[i + j]);
}
for (var _j = 0; _j < wordSize; _j++) {
bytes[i + _j] = tempBuffer.pop();
}
}
}
exports.default = {
ENDIANNESS: ENDIANNESS,
getEndianness: getEndianness,
swapBytes: swapBytes
};
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(291);
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __webpack_require__(177);
exports.Duplex = __webpack_require__(53);
exports.Transform = __webpack_require__(295);
exports.PassThrough = __webpack_require__(625);
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
/**/
var processNextTick = __webpack_require__(109);
/**/
module.exports = Writable;
/* */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* */
/**/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/**/
/**/
var Duplex;
/**/
Writable.WritableState = WritableState;
/**/
var util = __webpack_require__(90);
util.inherits = __webpack_require__(70);
/**/
/**/
var internalUtil = {
deprecate: __webpack_require__(624)
};
/**/
/**/
var Stream = __webpack_require__(292);
/**/
/**/
var Buffer = __webpack_require__(110).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/**/
var destroyImpl = __webpack_require__(293);
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || __webpack_require__(53);
options = options || {};
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || __webpack_require__(53);
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
processNextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
processNextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = _isUint8Array(chunk) && !state.objectMode;
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
processNextTick(cb, er);
// this can emit finish, and it will always happen
// after error
processNextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/**/
asyncWrite(afterWrite, stream, state, finished, cb);
/**/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequestCount = 0;
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
processNextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) processNextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(87), __webpack_require__(165).setImmediate, __webpack_require__(25)))
/***/ }),
/* 178 */
/***/ (function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(299)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var external = __webpack_require__(91);
var DataWorker = __webpack_require__(303);
var DataLengthProbe = __webpack_require__(304);
var Crc32Probe = __webpack_require__(305);
var DataLengthProbe = __webpack_require__(304);
/**
* Represent a compressed object, with everything needed to decompress it.
* @constructor
* @param {number} compressedSize the size of the data compressed.
* @param {number} uncompressedSize the size of the data after decompression.
* @param {number} crc32 the crc32 of the decompressed file.
* @param {object} compression the type of compression, see lib/compressions.js.
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
*/
function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
this.compressedSize = compressedSize;
this.uncompressedSize = uncompressedSize;
this.crc32 = crc32;
this.compression = compression;
this.compressedContent = data;
}
CompressedObject.prototype = {
/**
* Create a worker to get the uncompressed content.
* @return {GenericWorker} the worker.
*/
getContentWorker : function () {
var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
.pipe(this.compression.uncompressWorker())
.pipe(new DataLengthProbe("data_length"));
var that = this;
worker.on("end", function () {
if(this.streamInfo['data_length'] !== that.uncompressedSize) {
throw new Error("Bug : uncompressed data size mismatch");
}
});
return worker;
},
/**
* Create a worker to get the compressed content.
* @return {GenericWorker} the worker.
*/
getCompressedWorker : function () {
return new DataWorker(external.Promise.resolve(this.compressedContent))
.withStreamInfo("compressedSize", this.compressedSize)
.withStreamInfo("uncompressedSize", this.uncompressedSize)
.withStreamInfo("crc32", this.crc32)
.withStreamInfo("compression", this.compression)
;
}
};
/**
* Chain the given worker with other workers to compress the content with the
* given compresion.
* @param {GenericWorker} uncompressedWorker the worker to pipe.
* @param {Object} compression the compression object.
* @param {Object} compressionOptions the options to use when compressing.
* @return {GenericWorker} the new worker compressing the content.
*/
CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
return uncompressedWorker
.pipe(new Crc32Probe())
.pipe(new DataLengthProbe("uncompressedSize"))
.pipe(compression.compressWorker(compressionOptions))
.pipe(new DataLengthProbe("compressedSize"))
.withStreamInfo("compression", compression);
};
module.exports = CompressedObject;
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(11);
/**
* The following functions come from pako, from pako/lib/zlib/crc32.js
* released under the MIT license, see pako https://github.com/nodeca/pako/
*/
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for(var n =0; n < 256; n++){
c = n;
for(var k =0; k < 8; k++){
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable, end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++ ) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
// That's all for the pako functions.
/**
* Compute the crc32 of a string.
* This is almost the same as the function crc32, but for strings. Using the
* same function for the two use cases leads to horrible performances.
* @param {Number} crc the starting value of the crc.
* @param {String} str the string to use.
* @param {Number} len the length of the string.
* @param {Number} pos the starting position for the crc32 computation.
* @return {Number} the computed crc32.
*/
function crc32str(crc, str, len, pos) {
var t = crcTable, end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++ ) {
crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = function crc32wrapper(input, crc) {
if (typeof input === "undefined" || !input.length) {
return 0;
}
var isArray = utils.getTypeOf(input) !== "string";
if(isArray) {
return crc32(crc|0, input, input.length, 0);
} else {
return crc32str(crc|0, input, input.length, 0);
}
};
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _glMatrix = __webpack_require__(13);
function _toConsumableArray(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); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var NoOp = function NoOp(v) {
return v;
};
var IDENTITY = new Float64Array(16);
_glMatrix.mat4.identity(IDENTITY);
var Transform = function () {
function Transform() {
var useDegre = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
_classCallCheck(this, Transform);
this.matrix = new Float64Array(16);
_glMatrix.mat4.identity(this.matrix);
this.tmp = new Float64Array(3);
this.angleConv = useDegre ? _glMatrix.glMatrix.toRadian : NoOp;
}
_createClass(Transform, [{
key: 'rotateFromDirections',
value: function rotateFromDirections(originDirection, targetDirection) {
var src = new Float64Array(3);
var dst = new Float64Array(3);
var transf = new Float64Array(16);
_glMatrix.vec3.set(src, originDirection[0], originDirection[1], originDirection[2]);
_glMatrix.vec3.set(dst, targetDirection[0], targetDirection[1], targetDirection[2]);
_glMatrix.vec3.normalize(src, src);
_glMatrix.vec3.normalize(dst, dst);
var cosAlpha = _glMatrix.vec3.dot(src, dst);
if (cosAlpha >= 1) {
return this;
}
_glMatrix.vec3.cross(this.tmp, src, dst);
_glMatrix.mat4.fromRotation(transf, Math.acos(cosAlpha), this.tmp);
_glMatrix.mat4.multiply(this.matrix, this.matrix, transf);
return this;
}
}, {
key: 'rotate',
value: function rotate(angle, axis) {
_glMatrix.vec3.set.apply(_glMatrix.vec3, [this.tmp].concat(_toConsumableArray(axis)));
_glMatrix.vec3.normalize(this.tmp, this.tmp);
_glMatrix.mat4.rotate(this.matrix, this.matrix, this.angleConv(angle), this.tmp);
return this;
}
}, {
key: 'rotateX',
value: function rotateX(angle) {
_glMatrix.mat4.rotateX(this.matrix, this.matrix, this.angleConv(angle));
return this;
}
}, {
key: 'rotateY',
value: function rotateY(angle) {
_glMatrix.mat4.rotateY(this.matrix, this.matrix, this.angleConv(angle));
return this;
}
}, {
key: 'rotateZ',
value: function rotateZ(angle) {
_glMatrix.mat4.rotateZ(this.matrix, this.matrix, this.angleConv(angle));
return this;
}
}, {
key: 'translate',
value: function translate(x, y, z) {
_glMatrix.vec3.set(this.tmp, x, y, z);
_glMatrix.mat4.translate(this.matrix, this.matrix, this.tmp);
return this;
}
}, {
key: 'scale',
value: function scale(sx, sy, sz) {
_glMatrix.vec3.set(this.tmp, sx, sy, sz);
_glMatrix.mat4.scale(this.matrix, this.matrix, this.tmp);
return this;
}
}, {
key: 'apply',
value: function apply(typedArray) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var nbIterations = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;
if (IDENTITY[0] === this.matrix[0] && IDENTITY[1] === this.matrix[1] && IDENTITY[2] === this.matrix[2] && IDENTITY[3] === this.matrix[3] && IDENTITY[4] === this.matrix[4] && IDENTITY[5] === this.matrix[5] && IDENTITY[6] === this.matrix[6] && IDENTITY[7] === this.matrix[7] && IDENTITY[8] === this.matrix[8] && IDENTITY[9] === this.matrix[9] && IDENTITY[10] === this.matrix[10] && IDENTITY[11] === this.matrix[11] && IDENTITY[12] === this.matrix[12] && IDENTITY[13] === this.matrix[13] && IDENTITY[14] === this.matrix[14] && IDENTITY[15] === this.matrix[15]) {
// Make sure we can chain apply...
return this;
}
var size = nbIterations === -1 ? typedArray.length : offset + nbIterations * 3;
for (var i = offset; i < size; i += 3) {
_glMatrix.vec3.set(this.tmp, typedArray[i], typedArray[i + 1], typedArray[i + 2]);
_glMatrix.vec3.transformMat4(this.tmp, this.tmp, this.matrix);
typedArray[i] = this.tmp[0];
typedArray[i + 1] = this.tmp[1];
typedArray[i + 2] = this.tmp[2];
}
// Make sure we can chain apply...
return this;
}
}, {
key: 'getMatrix',
value: function getMatrix() {
return this.matrix;
}
}, {
key: 'setMatrix',
value: function setMatrix(mat4x4) {
if (!!mat4x4 && mat4x4.length === 16) {
this.matrix[0] = mat4x4[0];
this.matrix[1] = mat4x4[1];
this.matrix[2] = mat4x4[2];
this.matrix[3] = mat4x4[3];
this.matrix[4] = mat4x4[4];
this.matrix[5] = mat4x4[5];
this.matrix[6] = mat4x4[6];
this.matrix[7] = mat4x4[7];
this.matrix[8] = mat4x4[8];
this.matrix[9] = mat4x4[9];
this.matrix[10] = mat4x4[10];
this.matrix[11] = mat4x4[11];
this.matrix[12] = mat4x4[12];
this.matrix[13] = mat4x4[13];
this.matrix[14] = mat4x4[14];
this.matrix[15] = mat4x4[15];
}
return this;
}
}, {
key: 'identity',
value: function identity() {
_glMatrix.mat4.identity(this.matrix);
return this;
}
}]);
return Transform;
}();
function buildFromDegree() {
return new Transform(true);
}
function buildFromRadian() {
return new Transform(false);
}
exports.default = {
buildFromDegree: buildFromDegree,
buildFromRadian: buildFromRadian
};
/***/ }),
/* 183 */,
/* 184 */,
/* 185 */,
/* 186 */,
/* 187 */,
/* 188 */,
/* 189 */,
/* 190 */,
/* 191 */,
/* 192 */,
/* 193 */,
/* 194 */,
/* 195 */,
/* 196 */,
/* 197 */,
/* 198 */,
/* 199 */,
/* 200 */,
/* 201 */,
/* 202 */,
/* 203 */,
/* 204 */,
/* 205 */,
/* 206 */,
/* 207 */,
/* 208 */,
/* 209 */,
/* 210 */,
/* 211 */,
/* 212 */,
/* 213 */,
/* 214 */,
/* 215 */,
/* 216 */,
/* 217 */,
/* 218 */,
/* 219 */,
/* 220 */,
/* 221 */,
/* 222 */,
/* 223 */,
/* 224 */,
/* 225 */,
/* 226 */,
/* 227 */,
/* 228 */,
/* 229 */,
/* 230 */,
/* 231 */,
/* 232 */,
/* 233 */,
/* 234 */,
/* 235 */,
/* 236 */,
/* 237 */,
/* 238 */,
/* 239 */,
/* 240 */,
/* 241 */,
/* 242 */,
/* 243 */,
/* 244 */,
/* 245 */,
/* 246 */,
/* 247 */,
/* 248 */,
/* 249 */,
/* 250 */,
/* 251 */,
/* 252 */,
/* 253 */,
/* 254 */,
/* 255 */,
/* 256 */,
/* 257 */,
/* 258 */,
/* 259 */,
/* 260 */,
/* 261 */,
/* 262 */,
/* 263 */,
/* 264 */,
/* 265 */,
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sub = exports.mul = undefined;
exports.create = create;
exports.fromMat4 = fromMat4;
exports.clone = clone;
exports.copy = copy;
exports.fromValues = fromValues;
exports.set = set;
exports.identity = identity;
exports.transpose = transpose;
exports.invert = invert;
exports.adjoint = adjoint;
exports.determinant = determinant;
exports.multiply = multiply;
exports.translate = translate;
exports.rotate = rotate;
exports.scale = scale;
exports.fromTranslation = fromTranslation;
exports.fromRotation = fromRotation;
exports.fromScaling = fromScaling;
exports.fromMat2d = fromMat2d;
exports.fromQuat = fromQuat;
exports.normalFromMat4 = normalFromMat4;
exports.projection = projection;
exports.str = str;
exports.frob = frob;
exports.add = add;
exports.subtract = subtract;
exports.multiplyScalar = multiplyScalar;
exports.multiplyScalarAndAdd = multiplyScalarAndAdd;
exports.exactEquals = exactEquals;
exports.equals = equals;
var _common = __webpack_require__(36);
var glMatrix = _interopRequireWildcard(_common);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* 3x3 Matrix
* @module mat3
*/
/**
* Creates a new identity mat3
*
* @returns {mat3} a new 3x3 matrix
*/
function create() {
var out = new glMatrix.ARRAY_TYPE(9);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 1;
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 1;
return out;
}
/**
* Copies the upper-left 3x3 values into the given mat3.
*
* @param {mat3} out the receiving 3x3 matrix
* @param {mat4} a the source 4x4 matrix
* @returns {mat3} out
*/
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
function fromMat4(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[4];
out[4] = a[5];
out[5] = a[6];
out[6] = a[8];
out[7] = a[9];
out[8] = a[10];
return out;
}
/**
* Creates a new mat3 initialized with values from an existing matrix
*
* @param {mat3} a matrix to clone
* @returns {mat3} a new 3x3 matrix
*/
function clone(a) {
var out = new glMatrix.ARRAY_TYPE(9);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
return out;
}
/**
* Copy the values from one mat3 to another
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
return out;
}
/**
* Create a new mat3 with the given values
*
* @param {Number} m00 Component in column 0, row 0 position (index 0)
* @param {Number} m01 Component in column 0, row 1 position (index 1)
* @param {Number} m02 Component in column 0, row 2 position (index 2)
* @param {Number} m10 Component in column 1, row 0 position (index 3)
* @param {Number} m11 Component in column 1, row 1 position (index 4)
* @param {Number} m12 Component in column 1, row 2 position (index 5)
* @param {Number} m20 Component in column 2, row 0 position (index 6)
* @param {Number} m21 Component in column 2, row 1 position (index 7)
* @param {Number} m22 Component in column 2, row 2 position (index 8)
* @returns {mat3} A new mat3
*/
function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
var out = new glMatrix.ARRAY_TYPE(9);
out[0] = m00;
out[1] = m01;
out[2] = m02;
out[3] = m10;
out[4] = m11;
out[5] = m12;
out[6] = m20;
out[7] = m21;
out[8] = m22;
return out;
}
/**
* Set the components of a mat3 to the given values
*
* @param {mat3} out the receiving matrix
* @param {Number} m00 Component in column 0, row 0 position (index 0)
* @param {Number} m01 Component in column 0, row 1 position (index 1)
* @param {Number} m02 Component in column 0, row 2 position (index 2)
* @param {Number} m10 Component in column 1, row 0 position (index 3)
* @param {Number} m11 Component in column 1, row 1 position (index 4)
* @param {Number} m12 Component in column 1, row 2 position (index 5)
* @param {Number} m20 Component in column 2, row 0 position (index 6)
* @param {Number} m21 Component in column 2, row 1 position (index 7)
* @param {Number} m22 Component in column 2, row 2 position (index 8)
* @returns {mat3} out
*/
function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {
out[0] = m00;
out[1] = m01;
out[2] = m02;
out[3] = m10;
out[4] = m11;
out[5] = m12;
out[6] = m20;
out[7] = m21;
out[8] = m22;
return out;
}
/**
* Set a mat3 to the identity matrix
*
* @param {mat3} out the receiving matrix
* @returns {mat3} out
*/
function identity(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 1;
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 1;
return out;
}
/**
* Transpose the values of a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
function transpose(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a01 = a[1],
a02 = a[2],
a12 = a[5];
out[1] = a[3];
out[2] = a[6];
out[3] = a01;
out[5] = a[7];
out[6] = a02;
out[7] = a12;
} else {
out[0] = a[0];
out[1] = a[3];
out[2] = a[6];
out[3] = a[1];
out[4] = a[4];
out[5] = a[7];
out[6] = a[2];
out[7] = a[5];
out[8] = a[8];
}
return out;
}
/**
* Inverts a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
function invert(out, a) {
var a00 = a[0],
a01 = a[1],
a02 = a[2];
var a10 = a[3],
a11 = a[4],
a12 = a[5];
var a20 = a[6],
a21 = a[7],
a22 = a[8];
var b01 = a22 * a11 - a12 * a21;
var b11 = -a22 * a10 + a12 * a20;
var b21 = a21 * a10 - a11 * a20;
// Calculate the determinant
var det = a00 * b01 + a01 * b11 + a02 * b21;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = b01 * det;
out[1] = (-a22 * a01 + a02 * a21) * det;
out[2] = (a12 * a01 - a02 * a11) * det;
out[3] = b11 * det;
out[4] = (a22 * a00 - a02 * a20) * det;
out[5] = (-a12 * a00 + a02 * a10) * det;
out[6] = b21 * det;
out[7] = (-a21 * a00 + a01 * a20) * det;
out[8] = (a11 * a00 - a01 * a10) * det;
return out;
}
/**
* Calculates the adjugate of a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
function adjoint(out, a) {
var a00 = a[0],
a01 = a[1],
a02 = a[2];
var a10 = a[3],
a11 = a[4],
a12 = a[5];
var a20 = a[6],
a21 = a[7],
a22 = a[8];
out[0] = a11 * a22 - a12 * a21;
out[1] = a02 * a21 - a01 * a22;
out[2] = a01 * a12 - a02 * a11;
out[3] = a12 * a20 - a10 * a22;
out[4] = a00 * a22 - a02 * a20;
out[5] = a02 * a10 - a00 * a12;
out[6] = a10 * a21 - a11 * a20;
out[7] = a01 * a20 - a00 * a21;
out[8] = a00 * a11 - a01 * a10;
return out;
}
/**
* Calculates the determinant of a mat3
*
* @param {mat3} a the source matrix
* @returns {Number} determinant of a
*/
function determinant(a) {
var a00 = a[0],
a01 = a[1],
a02 = a[2];
var a10 = a[3],
a11 = a[4],
a12 = a[5];
var a20 = a[6],
a21 = a[7],
a22 = a[8];
return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
}
/**
* Multiplies two mat3's
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the first operand
* @param {mat3} b the second operand
* @returns {mat3} out
*/
function multiply(out, a, b) {
var a00 = a[0],
a01 = a[1],
a02 = a[2];
var a10 = a[3],
a11 = a[4],
a12 = a[5];
var a20 = a[6],
a21 = a[7],
a22 = a[8];
var b00 = b[0],
b01 = b[1],
b02 = b[2];
var b10 = b[3],
b11 = b[4],
b12 = b[5];
var b20 = b[6],
b21 = b[7],
b22 = b[8];
out[0] = b00 * a00 + b01 * a10 + b02 * a20;
out[1] = b00 * a01 + b01 * a11 + b02 * a21;
out[2] = b00 * a02 + b01 * a12 + b02 * a22;
out[3] = b10 * a00 + b11 * a10 + b12 * a20;
out[4] = b10 * a01 + b11 * a11 + b12 * a21;
out[5] = b10 * a02 + b11 * a12 + b12 * a22;
out[6] = b20 * a00 + b21 * a10 + b22 * a20;
out[7] = b20 * a01 + b21 * a11 + b22 * a21;
out[8] = b20 * a02 + b21 * a12 + b22 * a22;
return out;
}
/**
* Translate a mat3 by the given vector
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the matrix to translate
* @param {vec2} v vector to translate by
* @returns {mat3} out
*/
function translate(out, a, v) {
var a00 = a[0],
a01 = a[1],
a02 = a[2],
a10 = a[3],
a11 = a[4],
a12 = a[5],
a20 = a[6],
a21 = a[7],
a22 = a[8],
x = v[0],
y = v[1];
out[0] = a00;
out[1] = a01;
out[2] = a02;
out[3] = a10;
out[4] = a11;
out[5] = a12;
out[6] = x * a00 + y * a10 + a20;
out[7] = x * a01 + y * a11 + a21;
out[8] = x * a02 + y * a12 + a22;
return out;
}
/**
* Rotates a mat3 by the given angle
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat3} out
*/
function rotate(out, a, rad) {
var a00 = a[0],
a01 = a[1],
a02 = a[2],
a10 = a[3],
a11 = a[4],
a12 = a[5],
a20 = a[6],
a21 = a[7],
a22 = a[8],
s = Math.sin(rad),
c = Math.cos(rad);
out[0] = c * a00 + s * a10;
out[1] = c * a01 + s * a11;
out[2] = c * a02 + s * a12;
out[3] = c * a10 - s * a00;
out[4] = c * a11 - s * a01;
out[5] = c * a12 - s * a02;
out[6] = a20;
out[7] = a21;
out[8] = a22;
return out;
};
/**
* Scales the mat3 by the dimensions in the given vec2
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the matrix to rotate
* @param {vec2} v the vec2 to scale the matrix by
* @returns {mat3} out
**/
function scale(out, a, v) {
var x = v[0],
y = v[1];
out[0] = x * a[0];
out[1] = x * a[1];
out[2] = x * a[2];
out[3] = y * a[3];
out[4] = y * a[4];
out[5] = y * a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
return out;
}
/**
* Creates a matrix from a vector translation
* This is equivalent to (but much faster than):
*
* mat3.identity(dest);
* mat3.translate(dest, dest, vec);
*
* @param {mat3} out mat3 receiving operation result
* @param {vec2} v Translation vector
* @returns {mat3} out
*/
function fromTranslation(out, v) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 1;
out[5] = 0;
out[6] = v[0];
out[7] = v[1];
out[8] = 1;
return out;
}
/**
* Creates a matrix from a given angle
* This is equivalent to (but much faster than):
*
* mat3.identity(dest);
* mat3.rotate(dest, dest, rad);
*
* @param {mat3} out mat3 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat3} out
*/
function fromRotation(out, rad) {
var s = Math.sin(rad),
c = Math.cos(rad);
out[0] = c;
out[1] = s;
out[2] = 0;
out[3] = -s;
out[4] = c;
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 1;
return out;
}
/**
* Creates a matrix from a vector scaling
* This is equivalent to (but much faster than):
*
* mat3.identity(dest);
* mat3.scale(dest, dest, vec);
*
* @param {mat3} out mat3 receiving operation result
* @param {vec2} v Scaling vector
* @returns {mat3} out
*/
function fromScaling(out, v) {
out[0] = v[0];
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = v[1];
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 1;
return out;
}
/**
* Copies the values from a mat2d into a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat2d} a the matrix to copy
* @returns {mat3} out
**/
function fromMat2d(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = 0;
out[3] = a[2];
out[4] = a[3];
out[5] = 0;
out[6] = a[4];
out[7] = a[5];
out[8] = 1;
return out;
}
/**
* Calculates a 3x3 matrix from the given quaternion
*
* @param {mat3} out mat3 receiving operation result
* @param {quat} q Quaternion to create matrix from
*
* @returns {mat3} out
*/
function fromQuat(out, q) {
var x = q[0],
y = q[1],
z = q[2],
w = q[3];
var x2 = x + x;
var y2 = y + y;
var z2 = z + z;
var xx = x * x2;
var yx = y * x2;
var yy = y * y2;
var zx = z * x2;
var zy = z * y2;
var zz = z * z2;
var wx = w * x2;
var wy = w * y2;
var wz = w * z2;
out[0] = 1 - yy - zz;
out[3] = yx - wz;
out[6] = zx + wy;
out[1] = yx + wz;
out[4] = 1 - xx - zz;
out[7] = zy - wx;
out[2] = zx - wy;
out[5] = zy + wx;
out[8] = 1 - xx - yy;
return out;
}
/**
* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix
*
* @param {mat3} out mat3 receiving operation result
* @param {mat4} a Mat4 to derive the normal matrix from
*
* @returns {mat3} out
*/
function normalFromMat4(out, a) {
var a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3];
var a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
var a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
var a30 = a[12],
a31 = a[13],
a32 = a[14],
a33 = a[15];
var b00 = a00 * a11 - a01 * a10;
var b01 = a00 * a12 - a02 * a10;
var b02 = a00 * a13 - a03 * a10;
var b03 = a01 * a12 - a02 * a11;
var b04 = a01 * a13 - a03 * a11;
var b05 = a02 * a13 - a03 * a12;
var b06 = a20 * a31 - a21 * a30;
var b07 = a20 * a32 - a22 * a30;
var b08 = a20 * a33 - a23 * a30;
var b09 = a21 * a32 - a22 * a31;
var b10 = a21 * a33 - a23 * a31;
var b11 = a22 * a33 - a23 * a32;
// Calculate the determinant
var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
return out;
}
/**
* Generates a 2D projection matrix with the given bounds
*
* @param {mat3} out mat3 frustum matrix will be written into
* @param {number} width Width of your gl context
* @param {number} height Height of gl context
* @returns {mat3} out
*/
function projection(out, width, height) {
out[0] = 2 / width;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = -2 / height;
out[5] = 0;
out[6] = -1;
out[7] = 1;
out[8] = 1;
return out;
}
/**
* Returns a string representation of a mat3
*
* @param {mat3} a matrix to represent as a string
* @returns {String} string representation of the matrix
*/
function str(a) {
return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ')';
}
/**
* Returns Frobenius norm of a mat3
*
* @param {mat3} a the matrix to calculate Frobenius norm of
* @returns {Number} Frobenius norm
*/
function frob(a) {
return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2));
}
/**
* Adds two mat3's
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the first operand
* @param {mat3} b the second operand
* @returns {mat3} out
*/
function add(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
out[3] = a[3] + b[3];
out[4] = a[4] + b[4];
out[5] = a[5] + b[5];
out[6] = a[6] + b[6];
out[7] = a[7] + b[7];
out[8] = a[8] + b[8];
return out;
}
/**
* Subtracts matrix b from matrix a
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the first operand
* @param {mat3} b the second operand
* @returns {mat3} out
*/
function subtract(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
out[3] = a[3] - b[3];
out[4] = a[4] - b[4];
out[5] = a[5] - b[5];
out[6] = a[6] - b[6];
out[7] = a[7] - b[7];
out[8] = a[8] - b[8];
return out;
}
/**
* Multiply each element of the matrix by a scalar.
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the matrix to scale
* @param {Number} b amount to scale the matrix's elements by
* @returns {mat3} out
*/
function multiplyScalar(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
out[3] = a[3] * b;
out[4] = a[4] * b;
out[5] = a[5] * b;
out[6] = a[6] * b;
out[7] = a[7] * b;
out[8] = a[8] * b;
return out;
}
/**
* Adds two mat3's after multiplying each element of the second operand by a scalar value.
*
* @param {mat3} out the receiving vector
* @param {mat3} a the first operand
* @param {mat3} b the second operand
* @param {Number} scale the amount to scale b's elements by before adding
* @returns {mat3} out
*/
function multiplyScalarAndAdd(out, a, b, scale) {
out[0] = a[0] + b[0] * scale;
out[1] = a[1] + b[1] * scale;
out[2] = a[2] + b[2] * scale;
out[3] = a[3] + b[3] * scale;
out[4] = a[4] + b[4] * scale;
out[5] = a[5] + b[5] * scale;
out[6] = a[6] + b[6] * scale;
out[7] = a[7] + b[7] * scale;
out[8] = a[8] + b[8] * scale;
return out;
}
/**
* Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
*
* @param {mat3} a The first matrix.
* @param {mat3} b The second matrix.
* @returns {Boolean} True if the matrices are equal, false otherwise.
*/
function exactEquals(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];
}
/**
* Returns whether or not the matrices have approximately the same elements in the same position.
*
* @param {mat3} a The first matrix.
* @param {mat3} b The second matrix.
* @returns {Boolean} True if the matrices are equal, false otherwise.
*/
function equals(a, b) {
var a0 = a[0],
a1 = a[1],
a2 = a[2],
a3 = a[3],
a4 = a[4],
a5 = a[5],
a6 = a[6],
a7 = a[7],
a8 = a[8];
var b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3],
b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7],
b8 = b[8];
return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));
}
/**
* Alias for {@link mat3.multiply}
* @function
*/
var mul = exports.mul = multiply;
/**
* Alias for {@link mat3.subtract}
* @function
*/
var sub = exports.sub = subtract;
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sub = exports.mul = undefined;
exports.create = create;
exports.clone = clone;
exports.copy = copy;
exports.fromValues = fromValues;
exports.set = set;
exports.identity = identity;
exports.transpose = transpose;
exports.invert = invert;
exports.adjoint = adjoint;
exports.determinant = determinant;
exports.multiply = multiply;
exports.translate = translate;
exports.scale = scale;
exports.rotate = rotate;
exports.rotateX = rotateX;
exports.rotateY = rotateY;
exports.rotateZ = rotateZ;
exports.fromTranslation = fromTranslation;
exports.fromScaling = fromScaling;
exports.fromRotation = fromRotation;
exports.fromXRotation = fromXRotation;
exports.fromYRotation = fromYRotation;
exports.fromZRotation = fromZRotation;
exports.fromRotationTranslation = fromRotationTranslation;
exports.fromQuat2 = fromQuat2;
exports.getTranslation = getTranslation;
exports.getScaling = getScaling;
exports.getRotation = getRotation;
exports.fromRotationTranslationScale = fromRotationTranslationScale;
exports.fromRotationTranslationScaleOrigin = fromRotationTranslationScaleOrigin;
exports.fromQuat = fromQuat;
exports.frustum = frustum;
exports.perspective = perspective;
exports.perspectiveFromFieldOfView = perspectiveFromFieldOfView;
exports.ortho = ortho;
exports.lookAt = lookAt;
exports.targetTo = targetTo;
exports.str = str;
exports.frob = frob;
exports.add = add;
exports.subtract = subtract;
exports.multiplyScalar = multiplyScalar;
exports.multiplyScalarAndAdd = multiplyScalarAndAdd;
exports.exactEquals = exactEquals;
exports.equals = equals;
var _common = __webpack_require__(36);
var glMatrix = _interopRequireWildcard(_common);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* @class 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.
* @name mat4
*/
/**
* Creates a new identity mat4
*
* @returns {mat4} a new 4x4 matrix
*/
function create() {
var out = new glMatrix.ARRAY_TYPE(16);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Creates a new mat4 initialized with values from an existing matrix
*
* @param {mat4} a matrix to clone
* @returns {mat4} a new 4x4 matrix
*/
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
function clone(a) {
var out = new glMatrix.ARRAY_TYPE(16);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
}
/**
* Copy the values from one mat4 to another
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
}
/**
* Create a new mat4 with the given values
*
* @param {Number} m00 Component in column 0, row 0 position (index 0)
* @param {Number} m01 Component in column 0, row 1 position (index 1)
* @param {Number} m02 Component in column 0, row 2 position (index 2)
* @param {Number} m03 Component in column 0, row 3 position (index 3)
* @param {Number} m10 Component in column 1, row 0 position (index 4)
* @param {Number} m11 Component in column 1, row 1 position (index 5)
* @param {Number} m12 Component in column 1, row 2 position (index 6)
* @param {Number} m13 Component in column 1, row 3 position (index 7)
* @param {Number} m20 Component in column 2, row 0 position (index 8)
* @param {Number} m21 Component in column 2, row 1 position (index 9)
* @param {Number} m22 Component in column 2, row 2 position (index 10)
* @param {Number} m23 Component in column 2, row 3 position (index 11)
* @param {Number} m30 Component in column 3, row 0 position (index 12)
* @param {Number} m31 Component in column 3, row 1 position (index 13)
* @param {Number} m32 Component in column 3, row 2 position (index 14)
* @param {Number} m33 Component in column 3, row 3 position (index 15)
* @returns {mat4} A new mat4
*/
function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
var out = new glMatrix.ARRAY_TYPE(16);
out[0] = m00;
out[1] = m01;
out[2] = m02;
out[3] = m03;
out[4] = m10;
out[5] = m11;
out[6] = m12;
out[7] = m13;
out[8] = m20;
out[9] = m21;
out[10] = m22;
out[11] = m23;
out[12] = m30;
out[13] = m31;
out[14] = m32;
out[15] = m33;
return out;
}
/**
* Set the components of a mat4 to the given values
*
* @param {mat4} out the receiving matrix
* @param {Number} m00 Component in column 0, row 0 position (index 0)
* @param {Number} m01 Component in column 0, row 1 position (index 1)
* @param {Number} m02 Component in column 0, row 2 position (index 2)
* @param {Number} m03 Component in column 0, row 3 position (index 3)
* @param {Number} m10 Component in column 1, row 0 position (index 4)
* @param {Number} m11 Component in column 1, row 1 position (index 5)
* @param {Number} m12 Component in column 1, row 2 position (index 6)
* @param {Number} m13 Component in column 1, row 3 position (index 7)
* @param {Number} m20 Component in column 2, row 0 position (index 8)
* @param {Number} m21 Component in column 2, row 1 position (index 9)
* @param {Number} m22 Component in column 2, row 2 position (index 10)
* @param {Number} m23 Component in column 2, row 3 position (index 11)
* @param {Number} m30 Component in column 3, row 0 position (index 12)
* @param {Number} m31 Component in column 3, row 1 position (index 13)
* @param {Number} m32 Component in column 3, row 2 position (index 14)
* @param {Number} m33 Component in column 3, row 3 position (index 15)
* @returns {mat4} out
*/
function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
out[0] = m00;
out[1] = m01;
out[2] = m02;
out[3] = m03;
out[4] = m10;
out[5] = m11;
out[6] = m12;
out[7] = m13;
out[8] = m20;
out[9] = m21;
out[10] = m22;
out[11] = m23;
out[12] = m30;
out[13] = m31;
out[14] = m32;
out[15] = m33;
return out;
}
/**
* Set a mat4 to the identity matrix
*
* @param {mat4} out the receiving matrix
* @returns {mat4} out
*/
function identity(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Transpose the values of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function transpose(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a01 = a[1],
a02 = a[2],
a03 = a[3];
var a12 = a[6],
a13 = a[7];
var a23 = a[11];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a01;
out[6] = a[9];
out[7] = a[13];
out[8] = a02;
out[9] = a12;
out[11] = a[14];
out[12] = a03;
out[13] = a13;
out[14] = a23;
} else {
out[0] = a[0];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a[1];
out[5] = a[5];
out[6] = a[9];
out[7] = a[13];
out[8] = a[2];
out[9] = a[6];
out[10] = a[10];
out[11] = a[14];
out[12] = a[3];
out[13] = a[7];
out[14] = a[11];
out[15] = a[15];
}
return out;
}
/**
* Inverts a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function invert(out, a) {
var a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3];
var a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
var a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
var a30 = a[12],
a31 = a[13],
a32 = a[14],
a33 = a[15];
var b00 = a00 * a11 - a01 * a10;
var b01 = a00 * a12 - a02 * a10;
var b02 = a00 * a13 - a03 * a10;
var b03 = a01 * a12 - a02 * a11;
var b04 = a01 * a13 - a03 * a11;
var b05 = a02 * a13 - a03 * a12;
var b06 = a20 * a31 - a21 * a30;
var b07 = a20 * a32 - a22 * a30;
var b08 = a20 * a33 - a23 * a30;
var b09 = a21 * a32 - a22 * a31;
var b10 = a21 * a33 - a23 * a31;
var b11 = a22 * a33 - a23 * a32;
// Calculate the determinant
var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return out;
}
/**
* Calculates the adjugate of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function adjoint(out, a) {
var a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3];
var a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
var a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
var a30 = a[12],
a31 = a[13],
a32 = a[14],
a33 = a[15];
out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);
out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);
out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);
out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);
out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);
out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);
out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);
out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);
return out;
}
/**
* Calculates the determinant of a mat4
*
* @param {mat4} a the source matrix
* @returns {Number} determinant of a
*/
function determinant(a) {
var a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3];
var a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
var a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
var a30 = a[12],
a31 = a[13],
a32 = a[14],
a33 = a[15];
var b00 = a00 * a11 - a01 * a10;
var b01 = a00 * a12 - a02 * a10;
var b02 = a00 * a13 - a03 * a10;
var b03 = a01 * a12 - a02 * a11;
var b04 = a01 * a13 - a03 * a11;
var b05 = a02 * a13 - a03 * a12;
var b06 = a20 * a31 - a21 * a30;
var b07 = a20 * a32 - a22 * a30;
var b08 = a20 * a33 - a23 * a30;
var b09 = a21 * a32 - a22 * a31;
var b10 = a21 * a33 - a23 * a31;
var b11 = a22 * a33 - a23 * a32;
// Calculate the determinant
return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
}
/**
* Multiplies two mat4s
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @returns {mat4} out
*/
function multiply(out, a, b) {
var a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3];
var a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
var a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
var a30 = a[12],
a31 = a[13],
a32 = a[14],
a33 = a[15];
// Cache only the current line of the second matrix
var b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3];
out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[4];b1 = b[5];b2 = b[6];b3 = b[7];
out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[8];b1 = b[9];b2 = b[10];b3 = b[11];
out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[12];b1 = b[13];b2 = b[14];b3 = b[15];
out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
return out;
}
/**
* Translate a mat4 by the given vector
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to translate
* @param {vec3} v vector to translate by
* @returns {mat4} out
*/
function translate(out, a, v) {
var x = v[0],
y = v[1],
z = v[2];
var a00 = void 0,
a01 = void 0,
a02 = void 0,
a03 = void 0;
var a10 = void 0,
a11 = void 0,
a12 = void 0,
a13 = void 0;
var a20 = void 0,
a21 = void 0,
a22 = void 0,
a23 = void 0;
if (a === out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
} else {
a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
out[12] = a00 * x + a10 * y + a20 * z + a[12];
out[13] = a01 * x + a11 * y + a21 * z + a[13];
out[14] = a02 * x + a12 * y + a22 * z + a[14];
out[15] = a03 * x + a13 * y + a23 * z + a[15];
}
return out;
}
/**
* Scales the mat4 by the dimensions in the given vec3 not using vectorization
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to scale
* @param {vec3} v the vec3 to scale the matrix by
* @returns {mat4} out
**/
function scale(out, a, v) {
var x = v[0],
y = v[1],
z = v[2];
out[0] = a[0] * x;
out[1] = a[1] * x;
out[2] = a[2] * x;
out[3] = a[3] * x;
out[4] = a[4] * y;
out[5] = a[5] * y;
out[6] = a[6] * y;
out[7] = a[7] * y;
out[8] = a[8] * z;
out[9] = a[9] * z;
out[10] = a[10] * z;
out[11] = a[11] * z;
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
}
/**
* Rotates a mat4 by the given angle around the given axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @param {vec3} axis the axis to rotate around
* @returns {mat4} out
*/
function rotate(out, a, rad, axis) {
var x = axis[0],
y = axis[1],
z = axis[2];
var len = Math.sqrt(x * x + y * y + z * z);
var s = void 0,
c = void 0,
t = void 0;
var a00 = void 0,
a01 = void 0,
a02 = void 0,
a03 = void 0;
var a10 = void 0,
a11 = void 0,
a12 = void 0,
a13 = void 0;
var a20 = void 0,
a21 = void 0,
a22 = void 0,
a23 = void 0;
var b00 = void 0,
b01 = void 0,
b02 = void 0;
var b10 = void 0,
b11 = void 0,
b12 = void 0;
var b20 = void 0,
b21 = void 0,
b22 = void 0;
if (Math.abs(len) < glMatrix.EPSILON) {
return null;
}
len = 1 / len;
x *= len;
y *= len;
z *= len;
s = Math.sin(rad);
c = Math.cos(rad);
t = 1 - c;
a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
// Construct the elements of the rotation matrix
b00 = x * x * t + c;b01 = y * x * t + z * s;b02 = z * x * t - y * s;
b10 = x * y * t - z * s;b11 = y * y * t + c;b12 = z * y * t + x * s;
b20 = x * z * t + y * s;b21 = y * z * t - x * s;b22 = z * z * t + c;
// Perform rotation-specific matrix multiplication
out[0] = a00 * b00 + a10 * b01 + a20 * b02;
out[1] = a01 * b00 + a11 * b01 + a21 * b02;
out[2] = a02 * b00 + a12 * b01 + a22 * b02;
out[3] = a03 * b00 + a13 * b01 + a23 * b02;
out[4] = a00 * b10 + a10 * b11 + a20 * b12;
out[5] = a01 * b10 + a11 * b11 + a21 * b12;
out[6] = a02 * b10 + a12 * b11 + a22 * b12;
out[7] = a03 * b10 + a13 * b11 + a23 * b12;
out[8] = a00 * b20 + a10 * b21 + a20 * b22;
out[9] = a01 * b20 + a11 * b21 + a21 * b22;
out[10] = a02 * b20 + a12 * b21 + a22 * b22;
out[11] = a03 * b20 + a13 * b21 + a23 * b22;
if (a !== out) {
// If the source and destination differ, copy the unchanged last row
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
return out;
}
/**
* Rotates a matrix by the given angle around the X axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateX(out, a, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
if (a !== out) {
// If the source and destination differ, copy the unchanged rows
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[4] = a10 * c + a20 * s;
out[5] = a11 * c + a21 * s;
out[6] = a12 * c + a22 * s;
out[7] = a13 * c + a23 * s;
out[8] = a20 * c - a10 * s;
out[9] = a21 * c - a11 * s;
out[10] = a22 * c - a12 * s;
out[11] = a23 * c - a13 * s;
return out;
}
/**
* Rotates a matrix by the given angle around the Y axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateY(out, a, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
if (a !== out) {
// If the source and destination differ, copy the unchanged rows
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c - a20 * s;
out[1] = a01 * c - a21 * s;
out[2] = a02 * c - a22 * s;
out[3] = a03 * c - a23 * s;
out[8] = a00 * s + a20 * c;
out[9] = a01 * s + a21 * c;
out[10] = a02 * s + a22 * c;
out[11] = a03 * s + a23 * c;
return out;
}
/**
* Rotates a matrix by the given angle around the Z axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateZ(out, a, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
if (a !== out) {
// If the source and destination differ, copy the unchanged last row
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c + a10 * s;
out[1] = a01 * c + a11 * s;
out[2] = a02 * c + a12 * s;
out[3] = a03 * c + a13 * s;
out[4] = a10 * c - a00 * s;
out[5] = a11 * c - a01 * s;
out[6] = a12 * c - a02 * s;
out[7] = a13 * c - a03 * s;
return out;
}
/**
* Creates a matrix from a vector translation
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.translate(dest, dest, vec);
*
* @param {mat4} out mat4 receiving operation result
* @param {vec3} v Translation vector
* @returns {mat4} out
*/
function fromTranslation(out, v) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
}
/**
* Creates a matrix from a vector scaling
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.scale(dest, dest, vec);
*
* @param {mat4} out mat4 receiving operation result
* @param {vec3} v Scaling vector
* @returns {mat4} out
*/
function fromScaling(out, v) {
out[0] = v[0];
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = v[1];
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = v[2];
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Creates a matrix from a given angle around a given axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.rotate(dest, dest, rad, axis);
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @param {vec3} axis the axis to rotate around
* @returns {mat4} out
*/
function fromRotation(out, rad, axis) {
var x = axis[0],
y = axis[1],
z = axis[2];
var len = Math.sqrt(x * x + y * y + z * z);
var s = void 0,
c = void 0,
t = void 0;
if (Math.abs(len) < glMatrix.EPSILON) {
return null;
}
len = 1 / len;
x *= len;
y *= len;
z *= len;
s = Math.sin(rad);
c = Math.cos(rad);
t = 1 - c;
// Perform rotation-specific matrix multiplication
out[0] = x * x * t + c;
out[1] = y * x * t + z * s;
out[2] = z * x * t - y * s;
out[3] = 0;
out[4] = x * y * t - z * s;
out[5] = y * y * t + c;
out[6] = z * y * t + x * s;
out[7] = 0;
out[8] = x * z * t + y * s;
out[9] = y * z * t - x * s;
out[10] = z * z * t + c;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Creates a matrix from the given angle around the X axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.rotateX(dest, dest, rad);
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function fromXRotation(out, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
// Perform axis-specific matrix multiplication
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = c;
out[6] = s;
out[7] = 0;
out[8] = 0;
out[9] = -s;
out[10] = c;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Creates a matrix from the given angle around the Y axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.rotateY(dest, dest, rad);
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function fromYRotation(out, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
// Perform axis-specific matrix multiplication
out[0] = c;
out[1] = 0;
out[2] = -s;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = s;
out[9] = 0;
out[10] = c;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Creates a matrix from the given angle around the Z axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.rotateZ(dest, dest, rad);
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function fromZRotation(out, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
// Perform axis-specific matrix multiplication
out[0] = c;
out[1] = s;
out[2] = 0;
out[3] = 0;
out[4] = -s;
out[5] = c;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Creates a matrix from a quaternion rotation and vector translation
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.translate(dest, vec);
* let quatMat = mat4.create();
* quat4.toMat4(quat, quatMat);
* mat4.multiply(dest, quatMat);
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @param {vec3} v Translation vector
* @returns {mat4} out
*/
function fromRotationTranslation(out, q, v) {
// Quaternion math
var x = q[0],
y = q[1],
z = q[2],
w = q[3];
var x2 = x + x;
var y2 = y + y;
var z2 = z + z;
var xx = x * x2;
var xy = x * y2;
var xz = x * z2;
var yy = y * y2;
var yz = y * z2;
var zz = z * z2;
var wx = w * x2;
var wy = w * y2;
var wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
}
/**
* Creates a new mat4 from a dual quat.
*
* @param {mat4} out Matrix
* @param {quat2} a Dual Quaternion
* @returns {mat4} mat4 receiving operation result
*/
function fromQuat2(out, a) {
var translation = new glMatrix.ARRAY_TYPE(3);
var bx = -a[0],
by = -a[1],
bz = -a[2],
bw = a[3],
ax = a[4],
ay = a[5],
az = a[6],
aw = a[7];
var magnitude = bx * bx + by * by + bz * bz + bw * bw;
//Only scale if it makes sense
if (magnitude > 0) {
translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;
translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;
translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;
} else {
translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
}
fromRotationTranslation(out, a, translation);
return out;
}
/**
* Returns the translation vector component of a transformation
* matrix. If a matrix is built with fromRotationTranslation,
* the returned vector will be the same as the translation vector
* originally supplied.
* @param {vec3} out Vector to receive translation component
* @param {mat4} mat Matrix to be decomposed (input)
* @return {vec3} out
*/
function getTranslation(out, mat) {
out[0] = mat[12];
out[1] = mat[13];
out[2] = mat[14];
return out;
}
/**
* Returns the scaling factor component of a transformation
* matrix. If a matrix is built with fromRotationTranslationScale
* with a normalized Quaternion paramter, the returned vector will be
* the same as the scaling vector
* originally supplied.
* @param {vec3} out Vector to receive scaling factor component
* @param {mat4} mat Matrix to be decomposed (input)
* @return {vec3} out
*/
function getScaling(out, mat) {
var m11 = mat[0];
var m12 = mat[1];
var m13 = mat[2];
var m21 = mat[4];
var m22 = mat[5];
var m23 = mat[6];
var m31 = mat[8];
var m32 = mat[9];
var m33 = mat[10];
out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);
out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);
out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);
return out;
}
/**
* Returns a quaternion representing the rotational component
* of a transformation matrix. If a matrix is built with
* fromRotationTranslation, the returned quaternion will be the
* same as the quaternion originally supplied.
* @param {quat} out Quaternion to receive the rotation component
* @param {mat4} mat Matrix to be decomposed (input)
* @return {quat} out
*/
function getRotation(out, mat) {
// Algorithm taken from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
var trace = mat[0] + mat[5] + mat[10];
var S = 0;
if (trace > 0) {
S = Math.sqrt(trace + 1.0) * 2;
out[3] = 0.25 * S;
out[0] = (mat[6] - mat[9]) / S;
out[1] = (mat[8] - mat[2]) / S;
out[2] = (mat[1] - mat[4]) / S;
} else if (mat[0] > mat[5] && mat[0] > mat[10]) {
S = Math.sqrt(1.0 + mat[0] - mat[5] - mat[10]) * 2;
out[3] = (mat[6] - mat[9]) / S;
out[0] = 0.25 * S;
out[1] = (mat[1] + mat[4]) / S;
out[2] = (mat[8] + mat[2]) / S;
} else if (mat[5] > mat[10]) {
S = Math.sqrt(1.0 + mat[5] - mat[0] - mat[10]) * 2;
out[3] = (mat[8] - mat[2]) / S;
out[0] = (mat[1] + mat[4]) / S;
out[1] = 0.25 * S;
out[2] = (mat[6] + mat[9]) / S;
} else {
S = Math.sqrt(1.0 + mat[10] - mat[0] - mat[5]) * 2;
out[3] = (mat[1] - mat[4]) / S;
out[0] = (mat[8] + mat[2]) / S;
out[1] = (mat[6] + mat[9]) / S;
out[2] = 0.25 * S;
}
return out;
}
/**
* Creates a matrix from a quaternion rotation, vector translation and vector scale
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.translate(dest, vec);
* let quatMat = mat4.create();
* quat4.toMat4(quat, quatMat);
* mat4.multiply(dest, quatMat);
* mat4.scale(dest, scale)
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @param {vec3} v Translation vector
* @param {vec3} s Scaling vector
* @returns {mat4} out
*/
function fromRotationTranslationScale(out, q, v, s) {
// Quaternion math
var x = q[0],
y = q[1],
z = q[2],
w = q[3];
var x2 = x + x;
var y2 = y + y;
var z2 = z + z;
var xx = x * x2;
var xy = x * y2;
var xz = x * z2;
var yy = y * y2;
var yz = y * z2;
var zz = z * z2;
var wx = w * x2;
var wy = w * y2;
var wz = w * z2;
var sx = s[0];
var sy = s[1];
var sz = s[2];
out[0] = (1 - (yy + zz)) * sx;
out[1] = (xy + wz) * sx;
out[2] = (xz - wy) * sx;
out[3] = 0;
out[4] = (xy - wz) * sy;
out[5] = (1 - (xx + zz)) * sy;
out[6] = (yz + wx) * sy;
out[7] = 0;
out[8] = (xz + wy) * sz;
out[9] = (yz - wx) * sz;
out[10] = (1 - (xx + yy)) * sz;
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
}
/**
* Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.translate(dest, vec);
* mat4.translate(dest, origin);
* let quatMat = mat4.create();
* quat4.toMat4(quat, quatMat);
* mat4.multiply(dest, quatMat);
* mat4.scale(dest, scale)
* mat4.translate(dest, negativeOrigin);
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @param {vec3} v Translation vector
* @param {vec3} s Scaling vector
* @param {vec3} o The origin vector around which to scale and rotate
* @returns {mat4} out
*/
function fromRotationTranslationScaleOrigin(out, q, v, s, o) {
// Quaternion math
var x = q[0],
y = q[1],
z = q[2],
w = q[3];
var x2 = x + x;
var y2 = y + y;
var z2 = z + z;
var xx = x * x2;
var xy = x * y2;
var xz = x * z2;
var yy = y * y2;
var yz = y * z2;
var zz = z * z2;
var wx = w * x2;
var wy = w * y2;
var wz = w * z2;
var sx = s[0];
var sy = s[1];
var sz = s[2];
var ox = o[0];
var oy = o[1];
var oz = o[2];
var out0 = (1 - (yy + zz)) * sx;
var out1 = (xy + wz) * sx;
var out2 = (xz - wy) * sx;
var out4 = (xy - wz) * sy;
var out5 = (1 - (xx + zz)) * sy;
var out6 = (yz + wx) * sy;
var out8 = (xz + wy) * sz;
var out9 = (yz - wx) * sz;
var out10 = (1 - (xx + yy)) * sz;
out[0] = out0;
out[1] = out1;
out[2] = out2;
out[3] = 0;
out[4] = out4;
out[5] = out5;
out[6] = out6;
out[7] = 0;
out[8] = out8;
out[9] = out9;
out[10] = out10;
out[11] = 0;
out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);
out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);
out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);
out[15] = 1;
return out;
}
/**
* Calculates a 4x4 matrix from the given quaternion
*
* @param {mat4} out mat4 receiving operation result
* @param {quat} q Quaternion to create matrix from
*
* @returns {mat4} out
*/
function fromQuat(out, q) {
var x = q[0],
y = q[1],
z = q[2],
w = q[3];
var x2 = x + x;
var y2 = y + y;
var z2 = z + z;
var xx = x * x2;
var yx = y * x2;
var yy = y * y2;
var zx = z * x2;
var zy = z * y2;
var zz = z * z2;
var wx = w * x2;
var wy = w * y2;
var wz = w * z2;
out[0] = 1 - yy - zz;
out[1] = yx + wz;
out[2] = zx - wy;
out[3] = 0;
out[4] = yx - wz;
out[5] = 1 - xx - zz;
out[6] = zy + wx;
out[7] = 0;
out[8] = zx + wy;
out[9] = zy - wx;
out[10] = 1 - xx - yy;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Generates a frustum matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {Number} left Left bound of the frustum
* @param {Number} right Right bound of the frustum
* @param {Number} bottom Bottom bound of the frustum
* @param {Number} top Top bound of the frustum
* @param {Number} near Near bound of the frustum
* @param {Number} far Far bound of the frustum
* @returns {mat4} out
*/
function frustum(out, left, right, bottom, top, near, far) {
var rl = 1 / (right - left);
var tb = 1 / (top - bottom);
var nf = 1 / (near - far);
out[0] = near * 2 * rl;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = near * 2 * tb;
out[6] = 0;
out[7] = 0;
out[8] = (right + left) * rl;
out[9] = (top + bottom) * tb;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = far * near * 2 * nf;
out[15] = 0;
return out;
}
/**
* Generates a perspective projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fovy Vertical field of view in radians
* @param {number} aspect Aspect ratio. typically viewport width/height
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspective(out, fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2);
var nf = 1 / (near - far);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = 2 * far * near * nf;
out[15] = 0;
return out;
}
/**
* Generates a perspective projection matrix with the given field of view.
* This is primarily useful for generating projection matrices to be used
* with the still experiemental WebVR API.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspectiveFromFieldOfView(out, fov, near, far) {
var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
var xScale = 2.0 / (leftTan + rightTan);
var yScale = 2.0 / (upTan + downTan);
out[0] = xScale;
out[1] = 0.0;
out[2] = 0.0;
out[3] = 0.0;
out[4] = 0.0;
out[5] = yScale;
out[6] = 0.0;
out[7] = 0.0;
out[8] = -((leftTan - rightTan) * xScale * 0.5);
out[9] = (upTan - downTan) * yScale * 0.5;
out[10] = far / (near - far);
out[11] = -1.0;
out[12] = 0.0;
out[13] = 0.0;
out[14] = far * near / (near - far);
out[15] = 0.0;
return out;
}
/**
* Generates a orthogonal projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} left Left bound of the frustum
* @param {number} right Right bound of the frustum
* @param {number} bottom Bottom bound of the frustum
* @param {number} top Top bound of the frustum
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function ortho(out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right);
var bt = 1 / (bottom - top);
var nf = 1 / (near - far);
out[0] = -2 * lr;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = -2 * bt;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 2 * nf;
out[11] = 0;
out[12] = (left + right) * lr;
out[13] = (top + bottom) * bt;
out[14] = (far + near) * nf;
out[15] = 1;
return out;
}
/**
* Generates a look-at matrix with the given eye position, focal point, and up axis.
* If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {vec3} eye Position of the viewer
* @param {vec3} center Point the viewer is looking at
* @param {vec3} up vec3 pointing up
* @returns {mat4} out
*/
function lookAt(out, eye, center, up) {
var x0 = void 0,
x1 = void 0,
x2 = void 0,
y0 = void 0,
y1 = void 0,
y2 = void 0,
z0 = void 0,
z1 = void 0,
z2 = void 0,
len = void 0;
var eyex = eye[0];
var eyey = eye[1];
var eyez = eye[2];
var upx = up[0];
var upy = up[1];
var upz = up[2];
var centerx = center[0];
var centery = center[1];
var centerz = center[2];
if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {
return identity(out);
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
out[0] = x0;
out[1] = y0;
out[2] = z0;
out[3] = 0;
out[4] = x1;
out[5] = y1;
out[6] = z1;
out[7] = 0;
out[8] = x2;
out[9] = y2;
out[10] = z2;
out[11] = 0;
out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
out[15] = 1;
return out;
}
/**
* Generates a matrix that makes something look at something else.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {vec3} eye Position of the viewer
* @param {vec3} center Point the viewer is looking at
* @param {vec3} up vec3 pointing up
* @returns {mat4} out
*/
function targetTo(out, eye, target, up) {
var eyex = eye[0],
eyey = eye[1],
eyez = eye[2],
upx = up[0],
upy = up[1],
upz = up[2];
var z0 = eyex - target[0],
z1 = eyey - target[1],
z2 = eyez - target[2];
var len = z0 * z0 + z1 * z1 + z2 * z2;
if (len > 0) {
len = 1 / Math.sqrt(len);
z0 *= len;
z1 *= len;
z2 *= len;
}
var x0 = upy * z2 - upz * z1,
x1 = upz * z0 - upx * z2,
x2 = upx * z1 - upy * z0;
len = x0 * x0 + x1 * x1 + x2 * x2;
if (len > 0) {
len = 1 / Math.sqrt(len);
x0 *= len;
x1 *= len;
x2 *= len;
}
out[0] = x0;
out[1] = x1;
out[2] = x2;
out[3] = 0;
out[4] = z1 * x2 - z2 * x1;
out[5] = z2 * x0 - z0 * x2;
out[6] = z0 * x1 - z1 * x0;
out[7] = 0;
out[8] = z0;
out[9] = z1;
out[10] = z2;
out[11] = 0;
out[12] = eyex;
out[13] = eyey;
out[14] = eyez;
out[15] = 1;
return out;
};
/**
* Returns a string representation of a mat4
*
* @param {mat4} a matrix to represent as a string
* @returns {String} string representation of the matrix
*/
function str(a) {
return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' + a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')';
}
/**
* Returns Frobenius norm of a mat4
*
* @param {mat4} a the matrix to calculate Frobenius norm of
* @returns {Number} Frobenius norm
*/
function frob(a) {
return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2) + Math.pow(a[9], 2) + Math.pow(a[10], 2) + Math.pow(a[11], 2) + Math.pow(a[12], 2) + Math.pow(a[13], 2) + Math.pow(a[14], 2) + Math.pow(a[15], 2));
}
/**
* Adds two mat4's
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @returns {mat4} out
*/
function add(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
out[3] = a[3] + b[3];
out[4] = a[4] + b[4];
out[5] = a[5] + b[5];
out[6] = a[6] + b[6];
out[7] = a[7] + b[7];
out[8] = a[8] + b[8];
out[9] = a[9] + b[9];
out[10] = a[10] + b[10];
out[11] = a[11] + b[11];
out[12] = a[12] + b[12];
out[13] = a[13] + b[13];
out[14] = a[14] + b[14];
out[15] = a[15] + b[15];
return out;
}
/**
* Subtracts matrix b from matrix a
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @returns {mat4} out
*/
function subtract(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
out[3] = a[3] - b[3];
out[4] = a[4] - b[4];
out[5] = a[5] - b[5];
out[6] = a[6] - b[6];
out[7] = a[7] - b[7];
out[8] = a[8] - b[8];
out[9] = a[9] - b[9];
out[10] = a[10] - b[10];
out[11] = a[11] - b[11];
out[12] = a[12] - b[12];
out[13] = a[13] - b[13];
out[14] = a[14] - b[14];
out[15] = a[15] - b[15];
return out;
}
/**
* Multiply each element of the matrix by a scalar.
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to scale
* @param {Number} b amount to scale the matrix's elements by
* @returns {mat4} out
*/
function multiplyScalar(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
out[3] = a[3] * b;
out[4] = a[4] * b;
out[5] = a[5] * b;
out[6] = a[6] * b;
out[7] = a[7] * b;
out[8] = a[8] * b;
out[9] = a[9] * b;
out[10] = a[10] * b;
out[11] = a[11] * b;
out[12] = a[12] * b;
out[13] = a[13] * b;
out[14] = a[14] * b;
out[15] = a[15] * b;
return out;
}
/**
* Adds two mat4's after multiplying each element of the second operand by a scalar value.
*
* @param {mat4} out the receiving vector
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @param {Number} scale the amount to scale b's elements by before adding
* @returns {mat4} out
*/
function multiplyScalarAndAdd(out, a, b, scale) {
out[0] = a[0] + b[0] * scale;
out[1] = a[1] + b[1] * scale;
out[2] = a[2] + b[2] * scale;
out[3] = a[3] + b[3] * scale;
out[4] = a[4] + b[4] * scale;
out[5] = a[5] + b[5] * scale;
out[6] = a[6] + b[6] * scale;
out[7] = a[7] + b[7] * scale;
out[8] = a[8] + b[8] * scale;
out[9] = a[9] + b[9] * scale;
out[10] = a[10] + b[10] * scale;
out[11] = a[11] + b[11] * scale;
out[12] = a[12] + b[12] * scale;
out[13] = a[13] + b[13] * scale;
out[14] = a[14] + b[14] * scale;
out[15] = a[15] + b[15] * scale;
return out;
}
/**
* Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
*
* @param {mat4} a The first matrix.
* @param {mat4} b The second matrix.
* @returns {Boolean} True if the matrices are equal, false otherwise.
*/
function exactEquals(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];
}
/**
* Returns whether or not the matrices have approximately the same elements in the same position.
*
* @param {mat4} a The first matrix.
* @param {mat4} b The second matrix.
* @returns {Boolean} True if the matrices are equal, false otherwise.
*/
function equals(a, b) {
var a0 = a[0],
a1 = a[1],
a2 = a[2],
a3 = a[3];
var a4 = a[4],
a5 = a[5],
a6 = a[6],
a7 = a[7];
var a8 = a[8],
a9 = a[9],
a10 = a[10],
a11 = a[11];
var a12 = a[12],
a13 = a[13],
a14 = a[14],
a15 = a[15];
var b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3];
var b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7];
var b8 = b[8],
b9 = b[9],
b10 = b[10],
b11 = b[11];
var b12 = b[12],
b13 = b[13],
b14 = b[14],
b15 = b[15];
return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));
}
/**
* Alias for {@link mat4.multiply}
* @function
*/
var mul = exports.mul = multiply;
/**
* Alias for {@link mat4.subtract}
* @function
*/
var sub = exports.sub = subtract;
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setAxes = exports.sqlerp = exports.rotationTo = exports.equals = exports.exactEquals = exports.normalize = exports.sqrLen = exports.squaredLength = exports.len = exports.length = exports.lerp = exports.dot = exports.scale = exports.mul = exports.add = exports.set = exports.copy = exports.fromValues = exports.clone = undefined;
exports.create = create;
exports.identity = identity;
exports.setAxisAngle = setAxisAngle;
exports.getAxisAngle = getAxisAngle;
exports.multiply = multiply;
exports.rotateX = rotateX;
exports.rotateY = rotateY;
exports.rotateZ = rotateZ;
exports.calculateW = calculateW;
exports.slerp = slerp;
exports.invert = invert;
exports.conjugate = conjugate;
exports.fromMat3 = fromMat3;
exports.fromEuler = fromEuler;
exports.str = str;
var _common = __webpack_require__(36);
var glMatrix = _interopRequireWildcard(_common);
var _mat = __webpack_require__(266);
var mat3 = _interopRequireWildcard(_mat);
var _vec = __webpack_require__(269);
var vec3 = _interopRequireWildcard(_vec);
var _vec2 = __webpack_require__(270);
var vec4 = _interopRequireWildcard(_vec2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* Quaternion
* @module quat
*/
/**
* Creates a new identity quat
*
* @returns {quat} a new quaternion
*/
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
function create() {
var out = new glMatrix.ARRAY_TYPE(4);
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
}
/**
* Set a quat to the identity quaternion
*
* @param {quat} out the receiving quaternion
* @returns {quat} out
*/
function identity(out) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
}
/**
* Sets a quat from the given angle and rotation axis,
* then returns it.
*
* @param {quat} out the receiving quaternion
* @param {vec3} axis the axis around which to rotate
* @param {Number} rad the angle in radians
* @returns {quat} out
**/
function setAxisAngle(out, axis, rad) {
rad = rad * 0.5;
var s = Math.sin(rad);
out[0] = s * axis[0];
out[1] = s * axis[1];
out[2] = s * axis[2];
out[3] = Math.cos(rad);
return out;
}
/**
* Gets the rotation axis and angle for a given
* quaternion. If a quaternion is created with
* setAxisAngle, this method will return the same
* values as providied in the original parameter list
* OR functionally equivalent values.
* Example: The quaternion formed by axis [0, 0, 1] and
* angle -90 is the same as the quaternion formed by
* [0, 0, 1] and 270. This method favors the latter.
* @param {vec3} out_axis Vector receiving the axis of rotation
* @param {quat} q Quaternion to be decomposed
* @return {Number} Angle, in radians, of the rotation
*/
function getAxisAngle(out_axis, q) {
var rad = Math.acos(q[3]) * 2.0;
var s = Math.sin(rad / 2.0);
if (s != 0.0) {
out_axis[0] = q[0] / s;
out_axis[1] = q[1] / s;
out_axis[2] = q[2] / s;
} else {
// If s is zero, return any axis (no rotation - axis does not matter)
out_axis[0] = 1;
out_axis[1] = 0;
out_axis[2] = 0;
}
return rad;
}
/**
* Multiplies two quat's
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @returns {quat} out
*/
function multiply(out, a, b) {
var ax = a[0],
ay = a[1],
az = a[2],
aw = a[3];
var bx = b[0],
by = b[1],
bz = b[2],
bw = b[3];
out[0] = ax * bw + aw * bx + ay * bz - az * by;
out[1] = ay * bw + aw * by + az * bx - ax * bz;
out[2] = az * bw + aw * bz + ax * by - ay * bx;
out[3] = aw * bw - ax * bx - ay * by - az * bz;
return out;
}
/**
* Rotates a quaternion by the given angle about the X axis
*
* @param {quat} out quat receiving operation result
* @param {quat} a quat to rotate
* @param {number} rad angle (in radians) to rotate
* @returns {quat} out
*/
function rotateX(out, a, rad) {
rad *= 0.5;
var ax = a[0],
ay = a[1],
az = a[2],
aw = a[3];
var bx = Math.sin(rad),
bw = Math.cos(rad);
out[0] = ax * bw + aw * bx;
out[1] = ay * bw + az * bx;
out[2] = az * bw - ay * bx;
out[3] = aw * bw - ax * bx;
return out;
}
/**
* Rotates a quaternion by the given angle about the Y axis
*
* @param {quat} out quat receiving operation result
* @param {quat} a quat to rotate
* @param {number} rad angle (in radians) to rotate
* @returns {quat} out
*/
function rotateY(out, a, rad) {
rad *= 0.5;
var ax = a[0],
ay = a[1],
az = a[2],
aw = a[3];
var by = Math.sin(rad),
bw = Math.cos(rad);
out[0] = ax * bw - az * by;
out[1] = ay * bw + aw * by;
out[2] = az * bw + ax * by;
out[3] = aw * bw - ay * by;
return out;
}
/**
* Rotates a quaternion by the given angle about the Z axis
*
* @param {quat} out quat receiving operation result
* @param {quat} a quat to rotate
* @param {number} rad angle (in radians) to rotate
* @returns {quat} out
*/
function rotateZ(out, a, rad) {
rad *= 0.5;
var ax = a[0],
ay = a[1],
az = a[2],
aw = a[3];
var bz = Math.sin(rad),
bw = Math.cos(rad);
out[0] = ax * bw + ay * bz;
out[1] = ay * bw - ax * bz;
out[2] = az * bw + aw * bz;
out[3] = aw * bw - az * bz;
return out;
}
/**
* Calculates the W component of a quat from the X, Y, and Z components.
* Assumes that quaternion is 1 unit in length.
* Any existing W component will be ignored.
*
* @param {quat} out the receiving quaternion
* @param {quat} a quat to calculate W component of
* @returns {quat} out
*/
function calculateW(out, a) {
var x = a[0],
y = a[1],
z = a[2];
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
return out;
}
/**
* Performs a spherical linear interpolation between two quat
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {quat} out
*/
function slerp(out, a, b, t) {
// benchmarks:
// http://jsperf.com/quaternion-slerp-implementations
var ax = a[0],
ay = a[1],
az = a[2],
aw = a[3];
var bx = b[0],
by = b[1],
bz = b[2],
bw = b[3];
var omega = void 0,
cosom = void 0,
sinom = void 0,
scale0 = void 0,
scale1 = void 0;
// calc cosine
cosom = ax * bx + ay * by + az * bz + aw * bw;
// adjust signs (if necessary)
if (cosom < 0.0) {
cosom = -cosom;
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
// calculate coefficients
if (1.0 - cosom > 0.000001) {
// standard case (slerp)
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - t) * omega) / sinom;
scale1 = Math.sin(t * omega) / sinom;
} else {
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0 - t;
scale1 = t;
}
// calculate final values
out[0] = scale0 * ax + scale1 * bx;
out[1] = scale0 * ay + scale1 * by;
out[2] = scale0 * az + scale1 * bz;
out[3] = scale0 * aw + scale1 * bw;
return out;
}
/**
* Calculates the inverse of a quat
*
* @param {quat} out the receiving quaternion
* @param {quat} a quat to calculate inverse of
* @returns {quat} out
*/
function invert(out, a) {
var a0 = a[0],
a1 = a[1],
a2 = a[2],
a3 = a[3];
var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
var invDot = dot ? 1.0 / dot : 0;
// TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
out[0] = -a0 * invDot;
out[1] = -a1 * invDot;
out[2] = -a2 * invDot;
out[3] = a3 * invDot;
return out;
}
/**
* Calculates the conjugate of a quat
* If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
*
* @param {quat} out the receiving quaternion
* @param {quat} a quat to calculate conjugate of
* @returns {quat} out
*/
function conjugate(out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
out[3] = a[3];
return out;
}
/**
* Creates a quaternion from the given 3x3 rotation matrix.
*
* NOTE: The resultant quaternion is not normalized, so you should be sure
* to renormalize the quaternion yourself where necessary.
*
* @param {quat} out the receiving quaternion
* @param {mat3} m rotation matrix
* @returns {quat} out
* @function
*/
function fromMat3(out, m) {
// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
var fTrace = m[0] + m[4] + m[8];
var fRoot = void 0;
if (fTrace > 0.0) {
// |w| > 1/2, may as well choose w > 1/2
fRoot = Math.sqrt(fTrace + 1.0); // 2w
out[3] = 0.5 * fRoot;
fRoot = 0.5 / fRoot; // 1/(4w)
out[0] = (m[5] - m[7]) * fRoot;
out[1] = (m[6] - m[2]) * fRoot;
out[2] = (m[1] - m[3]) * fRoot;
} else {
// |w| <= 1/2
var i = 0;
if (m[4] > m[0]) i = 1;
if (m[8] > m[i * 3 + i]) i = 2;
var j = (i + 1) % 3;
var k = (i + 2) % 3;
fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
out[i] = 0.5 * fRoot;
fRoot = 0.5 / fRoot;
out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
}
return out;
}
/**
* Creates a quaternion from the given euler angle x, y, z.
*
* @param {quat} out the receiving quaternion
* @param {x} Angle to rotate around X axis in degrees.
* @param {y} Angle to rotate around Y axis in degrees.
* @param {z} Angle to rotate around Z axis in degrees.
* @returns {quat} out
* @function
*/
function fromEuler(out, x, y, z) {
var halfToRad = 0.5 * Math.PI / 180.0;
x *= halfToRad;
y *= halfToRad;
z *= halfToRad;
var sx = Math.sin(x);
var cx = Math.cos(x);
var sy = Math.sin(y);
var cy = Math.cos(y);
var sz = Math.sin(z);
var cz = Math.cos(z);
out[0] = sx * cy * cz - cx * sy * sz;
out[1] = cx * sy * cz + sx * cy * sz;
out[2] = cx * cy * sz - sx * sy * cz;
out[3] = cx * cy * cz + sx * sy * sz;
return out;
}
/**
* Returns a string representation of a quatenion
*
* @param {quat} a vector to represent as a string
* @returns {String} string representation of the vector
*/
function str(a) {
return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
}
/**
* Creates a new quat initialized with values from an existing quaternion
*
* @param {quat} a quaternion to clone
* @returns {quat} a new quaternion
* @function
*/
var clone = exports.clone = vec4.clone;
/**
* Creates a new quat initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {quat} a new quaternion
* @function
*/
var fromValues = exports.fromValues = vec4.fromValues;
/**
* Copy the values from one quat to another
*
* @param {quat} out the receiving quaternion
* @param {quat} a the source quaternion
* @returns {quat} out
* @function
*/
var copy = exports.copy = vec4.copy;
/**
* Set the components of a quat to the given values
*
* @param {quat} out the receiving quaternion
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {quat} out
* @function
*/
var set = exports.set = vec4.set;
/**
* Adds two quat's
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @returns {quat} out
* @function
*/
var add = exports.add = vec4.add;
/**
* Alias for {@link quat.multiply}
* @function
*/
var mul = exports.mul = multiply;
/**
* Scales a quat by a scalar number
*
* @param {quat} out the receiving vector
* @param {quat} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {quat} out
* @function
*/
var scale = exports.scale = vec4.scale;
/**
* Calculates the dot product of two quat's
*
* @param {quat} a the first operand
* @param {quat} b the second operand
* @returns {Number} dot product of a and b
* @function
*/
var dot = exports.dot = vec4.dot;
/**
* Performs a linear interpolation between two quat's
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {quat} out
* @function
*/
var lerp = exports.lerp = vec4.lerp;
/**
* Calculates the length of a quat
*
* @param {quat} a vector to calculate length of
* @returns {Number} length of a
*/
var length = exports.length = vec4.length;
/**
* Alias for {@link quat.length}
* @function
*/
var len = exports.len = length;
/**
* Calculates the squared length of a quat
*
* @param {quat} a vector to calculate squared length of
* @returns {Number} squared length of a
* @function
*/
var squaredLength = exports.squaredLength = vec4.squaredLength;
/**
* Alias for {@link quat.squaredLength}
* @function
*/
var sqrLen = exports.sqrLen = squaredLength;
/**
* Normalize a quat
*
* @param {quat} out the receiving quaternion
* @param {quat} a quaternion to normalize
* @returns {quat} out
* @function
*/
var normalize = exports.normalize = vec4.normalize;
/**
* Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)
*
* @param {quat} a The first quaternion.
* @param {quat} b The second quaternion.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
var exactEquals = exports.exactEquals = vec4.exactEquals;
/**
* Returns whether or not the quaternions have approximately the same elements in the same position.
*
* @param {quat} a The first vector.
* @param {quat} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
var equals = exports.equals = vec4.equals;
/**
* Sets a quaternion to represent the shortest rotation from one
* vector to another.
*
* Both vectors are assumed to be unit length.
*
* @param {quat} out the receiving quaternion.
* @param {vec3} a the initial vector
* @param {vec3} b the destination vector
* @returns {quat} out
*/
var rotationTo = exports.rotationTo = function () {
var tmpvec3 = vec3.create();
var xUnitVec3 = vec3.fromValues(1, 0, 0);
var yUnitVec3 = vec3.fromValues(0, 1, 0);
return function (out, a, b) {
var dot = vec3.dot(a, b);
if (dot < -0.999999) {
vec3.cross(tmpvec3, xUnitVec3, a);
if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);
vec3.normalize(tmpvec3, tmpvec3);
setAxisAngle(out, tmpvec3, Math.PI);
return out;
} else if (dot > 0.999999) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
} else {
vec3.cross(tmpvec3, a, b);
out[0] = tmpvec3[0];
out[1] = tmpvec3[1];
out[2] = tmpvec3[2];
out[3] = 1 + dot;
return normalize(out, out);
}
};
}();
/**
* Performs a spherical linear interpolation with two control points
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @param {quat} c the third operand
* @param {quat} d the fourth operand
* @param {Number} t interpolation amount
* @returns {quat} out
*/
var sqlerp = exports.sqlerp = function () {
var temp1 = create();
var temp2 = create();
return function (out, a, b, c, d, t) {
slerp(temp1, a, d, t);
slerp(temp2, b, c, t);
slerp(out, temp1, temp2, 2 * t * (1 - t));
return out;
};
}();
/**
* Sets the specified quaternion with values corresponding to the given
* axes. Each axis is a vec3 and is expected to be unit length and
* perpendicular to all other specified axes.
*
* @param {vec3} view the vector representing the viewing direction
* @param {vec3} right the vector representing the local "right" direction
* @param {vec3} up the vector representing the local "up" direction
* @returns {quat} out
*/
var setAxes = exports.setAxes = function () {
var matr = mat3.create();
return function (out, view, right, up) {
matr[0] = right[0];
matr[3] = right[1];
matr[6] = right[2];
matr[1] = up[0];
matr[4] = up[1];
matr[7] = up[2];
matr[2] = -view[0];
matr[5] = -view[1];
matr[8] = -view[2];
return normalize(out, fromMat3(out, matr));
};
}();
/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.forEach = exports.sqrLen = exports.len = exports.sqrDist = exports.dist = exports.div = exports.mul = exports.sub = undefined;
exports.create = create;
exports.clone = clone;
exports.length = length;
exports.fromValues = fromValues;
exports.copy = copy;
exports.set = set;
exports.add = add;
exports.subtract = subtract;
exports.multiply = multiply;
exports.divide = divide;
exports.ceil = ceil;
exports.floor = floor;
exports.min = min;
exports.max = max;
exports.round = round;
exports.scale = scale;
exports.scaleAndAdd = scaleAndAdd;
exports.distance = distance;
exports.squaredDistance = squaredDistance;
exports.squaredLength = squaredLength;
exports.negate = negate;
exports.inverse = inverse;
exports.normalize = normalize;
exports.dot = dot;
exports.cross = cross;
exports.lerp = lerp;
exports.hermite = hermite;
exports.bezier = bezier;
exports.random = random;
exports.transformMat4 = transformMat4;
exports.transformMat3 = transformMat3;
exports.transformQuat = transformQuat;
exports.rotateX = rotateX;
exports.rotateY = rotateY;
exports.rotateZ = rotateZ;
exports.angle = angle;
exports.str = str;
exports.exactEquals = exactEquals;
exports.equals = equals;
var _common = __webpack_require__(36);
var glMatrix = _interopRequireWildcard(_common);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* 3 Dimensional Vector
* @module vec3
*/
/**
* Creates a new, empty vec3
*
* @returns {vec3} a new 3D vector
*/
function create() {
var out = new glMatrix.ARRAY_TYPE(3);
out[0] = 0;
out[1] = 0;
out[2] = 0;
return out;
}
/**
* Creates a new vec3 initialized with values from an existing vector
*
* @param {vec3} a vector to clone
* @returns {vec3} a new 3D vector
*/
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
function clone(a) {
var out = new glMatrix.ARRAY_TYPE(3);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
return out;
}
/**
* Calculates the length of a vec3
*
* @param {vec3} a vector to calculate length of
* @returns {Number} length of a
*/
function length(a) {
var x = a[0];
var y = a[1];
var z = a[2];
return Math.sqrt(x * x + y * y + z * z);
}
/**
* Creates a new vec3 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} a new 3D vector
*/
function fromValues(x, y, z) {
var out = new glMatrix.ARRAY_TYPE(3);
out[0] = x;
out[1] = y;
out[2] = z;
return out;
}
/**
* Copy the values from one vec3 to another
*
* @param {vec3} out the receiving vector
* @param {vec3} a the source vector
* @returns {vec3} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
return out;
}
/**
* Set the components of a vec3 to the given values
*
* @param {vec3} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} out
*/
function set(out, x, y, z) {
out[0] = x;
out[1] = y;
out[2] = z;
return out;
}
/**
* Adds two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function add(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
return out;
}
/**
* Subtracts vector b from vector a
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function subtract(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
return out;
}
/**
* Multiplies two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function multiply(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
out[2] = a[2] * b[2];
return out;
}
/**
* Divides two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function divide(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
out[2] = a[2] / b[2];
return out;
}
/**
* Math.ceil the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to ceil
* @returns {vec3} out
*/
function ceil(out, a) {
out[0] = Math.ceil(a[0]);
out[1] = Math.ceil(a[1]);
out[2] = Math.ceil(a[2]);
return out;
}
/**
* Math.floor the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to floor
* @returns {vec3} out
*/
function floor(out, a) {
out[0] = Math.floor(a[0]);
out[1] = Math.floor(a[1]);
out[2] = Math.floor(a[2]);
return out;
}
/**
* Returns the minimum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function min(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
out[2] = Math.min(a[2], b[2]);
return out;
}
/**
* Returns the maximum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function max(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
out[2] = Math.max(a[2], b[2]);
return out;
}
/**
* Math.round the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to round
* @returns {vec3} out
*/
function round(out, a) {
out[0] = Math.round(a[0]);
out[1] = Math.round(a[1]);
out[2] = Math.round(a[2]);
return out;
}
/**
* Scales a vec3 by a scalar number
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec3} out
*/
function scale(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
return out;
}
/**
* Adds two vec3's after scaling the second operand by a scalar value
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec3} out
*/
function scaleAndAdd(out, a, b, scale) {
out[0] = a[0] + b[0] * scale;
out[1] = a[1] + b[1] * scale;
out[2] = a[2] + b[2] * scale;
return out;
}
/**
* Calculates the euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} distance between a and b
*/
function distance(a, b) {
var x = b[0] - a[0];
var y = b[1] - a[1];
var z = b[2] - a[2];
return Math.sqrt(x * x + y * y + z * z);
}
/**
* Calculates the squared euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} squared distance between a and b
*/
function squaredDistance(a, b) {
var x = b[0] - a[0];
var y = b[1] - a[1];
var z = b[2] - a[2];
return x * x + y * y + z * z;
}
/**
* Calculates the squared length of a vec3
*
* @param {vec3} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
function squaredLength(a) {
var x = a[0];
var y = a[1];
var z = a[2];
return x * x + y * y + z * z;
}
/**
* Negates the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to negate
* @returns {vec3} out
*/
function negate(out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
return out;
}
/**
* Returns the inverse of the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to invert
* @returns {vec3} out
*/
function inverse(out, a) {
out[0] = 1.0 / a[0];
out[1] = 1.0 / a[1];
out[2] = 1.0 / a[2];
return out;
}
/**
* Normalize a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to normalize
* @returns {vec3} out
*/
function normalize(out, a) {
var x = a[0];
var y = a[1];
var z = a[2];
var len = x * x + y * y + z * z;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
out[2] = a[2] * len;
}
return out;
}
/**
* Calculates the dot product of two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} dot product of a and b
*/
function dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
/**
* Computes the cross product of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function cross(out, a, b) {
var ax = a[0],
ay = a[1],
az = a[2];
var bx = b[0],
by = b[1],
bz = b[2];
out[0] = ay * bz - az * by;
out[1] = az * bx - ax * bz;
out[2] = ax * by - ay * bx;
return out;
}
/**
* Performs a linear interpolation between two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec3} out
*/
function lerp(out, a, b, t) {
var ax = a[0];
var ay = a[1];
var az = a[2];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
out[2] = az + t * (b[2] - az);
return out;
}
/**
* Performs a hermite interpolation with two control points
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {vec3} c the third operand
* @param {vec3} d the fourth operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec3} out
*/
function hermite(out, a, b, c, d, t) {
var factorTimes2 = t * t;
var factor1 = factorTimes2 * (2 * t - 3) + 1;
var factor2 = factorTimes2 * (t - 2) + t;
var factor3 = factorTimes2 * (t - 1);
var factor4 = factorTimes2 * (3 - 2 * t);
out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;
out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;
out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;
return out;
}
/**
* Performs a bezier interpolation with two control points
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {vec3} c the third operand
* @param {vec3} d the fourth operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec3} out
*/
function bezier(out, a, b, c, d, t) {
var inverseFactor = 1 - t;
var inverseFactorTimesTwo = inverseFactor * inverseFactor;
var factorTimes2 = t * t;
var factor1 = inverseFactorTimesTwo * inverseFactor;
var factor2 = 3 * t * inverseFactorTimesTwo;
var factor3 = 3 * factorTimes2 * inverseFactor;
var factor4 = factorTimes2 * t;
out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;
out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;
out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;
return out;
}
/**
* Generates a random vector with the given scale
*
* @param {vec3} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec3} out
*/
function random(out, scale) {
scale = scale || 1.0;
var r = glMatrix.RANDOM() * 2.0 * Math.PI;
var z = glMatrix.RANDOM() * 2.0 - 1.0;
var zScale = Math.sqrt(1.0 - z * z) * scale;
out[0] = Math.cos(r) * zScale;
out[1] = Math.sin(r) * zScale;
out[2] = z * scale;
return out;
}
/**
* Transforms the vec3 with a mat4.
* 4th vector component is implicitly '1'
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec3} out
*/
function transformMat4(out, a, m) {
var x = a[0],
y = a[1],
z = a[2];
var w = m[3] * x + m[7] * y + m[11] * z + m[15];
w = w || 1.0;
out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
return out;
}
/**
* Transforms the vec3 with a mat3.
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat3} m the 3x3 matrix to transform with
* @returns {vec3} out
*/
function transformMat3(out, a, m) {
var x = a[0],
y = a[1],
z = a[2];
out[0] = x * m[0] + y * m[3] + z * m[6];
out[1] = x * m[1] + y * m[4] + z * m[7];
out[2] = x * m[2] + y * m[5] + z * m[8];
return out;
}
/**
* Transforms the vec3 with a quat
* Can also be used for dual quaternions. (Multiply it with the real part)
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec3} out
*/
function transformQuat(out, a, q) {
// benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
var qx = q[0],
qy = q[1],
qz = q[2],
qw = q[3];
var x = a[0],
y = a[1],
z = a[2];
// var qvec = [qx, qy, qz];
// var uv = vec3.cross([], qvec, a);
var uvx = qy * z - qz * y,
uvy = qz * x - qx * z,
uvz = qx * y - qy * x;
// var uuv = vec3.cross([], qvec, uv);
var uuvx = qy * uvz - qz * uvy,
uuvy = qz * uvx - qx * uvz,
uuvz = qx * uvy - qy * uvx;
// vec3.scale(uv, uv, 2 * w);
var w2 = qw * 2;
uvx *= w2;
uvy *= w2;
uvz *= w2;
// vec3.scale(uuv, uuv, 2);
uuvx *= 2;
uuvy *= 2;
uuvz *= 2;
// return vec3.add(out, a, vec3.add(out, uv, uuv));
out[0] = x + uvx + uuvx;
out[1] = y + uvy + uuvy;
out[2] = z + uvz + uuvz;
return out;
}
/**
* Rotate a 3D vector around the x-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateX(out, a, b, c) {
var p = [],
r = [];
//Translate point to the origin
p[0] = a[0] - b[0];
p[1] = a[1] - b[1];
p[2] = a[2] - b[2];
//perform rotation
r[0] = p[0];
r[1] = p[1] * Math.cos(c) - p[2] * Math.sin(c);
r[2] = p[1] * Math.sin(c) + p[2] * Math.cos(c);
//translate to correct position
out[0] = r[0] + b[0];
out[1] = r[1] + b[1];
out[2] = r[2] + b[2];
return out;
}
/**
* Rotate a 3D vector around the y-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateY(out, a, b, c) {
var p = [],
r = [];
//Translate point to the origin
p[0] = a[0] - b[0];
p[1] = a[1] - b[1];
p[2] = a[2] - b[2];
//perform rotation
r[0] = p[2] * Math.sin(c) + p[0] * Math.cos(c);
r[1] = p[1];
r[2] = p[2] * Math.cos(c) - p[0] * Math.sin(c);
//translate to correct position
out[0] = r[0] + b[0];
out[1] = r[1] + b[1];
out[2] = r[2] + b[2];
return out;
}
/**
* Rotate a 3D vector around the z-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateZ(out, a, b, c) {
var p = [],
r = [];
//Translate point to the origin
p[0] = a[0] - b[0];
p[1] = a[1] - b[1];
p[2] = a[2] - b[2];
//perform rotation
r[0] = p[0] * Math.cos(c) - p[1] * Math.sin(c);
r[1] = p[0] * Math.sin(c) + p[1] * Math.cos(c);
r[2] = p[2];
//translate to correct position
out[0] = r[0] + b[0];
out[1] = r[1] + b[1];
out[2] = r[2] + b[2];
return out;
}
/**
* Get the angle between two 3D vectors
* @param {vec3} a The first operand
* @param {vec3} b The second operand
* @returns {Number} The angle in radians
*/
function angle(a, b) {
var tempA = fromValues(a[0], a[1], a[2]);
var tempB = fromValues(b[0], b[1], b[2]);
normalize(tempA, tempA);
normalize(tempB, tempB);
var cosine = dot(tempA, tempB);
if (cosine > 1.0) {
return 0;
} else if (cosine < -1.0) {
return Math.PI;
} else {
return Math.acos(cosine);
}
}
/**
* Returns a string representation of a vector
*
* @param {vec3} a vector to represent as a string
* @returns {String} string representation of the vector
*/
function str(a) {
return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')';
}
/**
* Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function exactEquals(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
}
/**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function equals(a, b) {
var a0 = a[0],
a1 = a[1],
a2 = a[2];
var b0 = b[0],
b1 = b[1],
b2 = b[2];
return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));
}
/**
* Alias for {@link vec3.subtract}
* @function
*/
var sub = exports.sub = subtract;
/**
* Alias for {@link vec3.multiply}
* @function
*/
var mul = exports.mul = multiply;
/**
* Alias for {@link vec3.divide}
* @function
*/
var div = exports.div = divide;
/**
* Alias for {@link vec3.distance}
* @function
*/
var dist = exports.dist = distance;
/**
* Alias for {@link vec3.squaredDistance}
* @function
*/
var sqrDist = exports.sqrDist = squaredDistance;
/**
* Alias for {@link vec3.length}
* @function
*/
var len = exports.len = length;
/**
* Alias for {@link vec3.squaredLength}
* @function
*/
var sqrLen = exports.sqrLen = squaredLength;
/**
* Perform some operation over an array of vec3s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
var forEach = exports.forEach = function () {
var vec = create();
return function (a, stride, offset, count, fn, arg) {
var i = void 0,
l = void 0;
if (!stride) {
stride = 3;
}
if (!offset) {
offset = 0;
}
if (count) {
l = Math.min(count * stride + offset, a.length);
} else {
l = a.length;
}
for (i = offset; i < l; i += stride) {
vec[0] = a[i];vec[1] = a[i + 1];vec[2] = a[i + 2];
fn(vec, vec, arg);
a[i] = vec[0];a[i + 1] = vec[1];a[i + 2] = vec[2];
}
return a;
};
}();
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.forEach = exports.sqrLen = exports.len = exports.sqrDist = exports.dist = exports.div = exports.mul = exports.sub = undefined;
exports.create = create;
exports.clone = clone;
exports.fromValues = fromValues;
exports.copy = copy;
exports.set = set;
exports.add = add;
exports.subtract = subtract;
exports.multiply = multiply;
exports.divide = divide;
exports.ceil = ceil;
exports.floor = floor;
exports.min = min;
exports.max = max;
exports.round = round;
exports.scale = scale;
exports.scaleAndAdd = scaleAndAdd;
exports.distance = distance;
exports.squaredDistance = squaredDistance;
exports.length = length;
exports.squaredLength = squaredLength;
exports.negate = negate;
exports.inverse = inverse;
exports.normalize = normalize;
exports.dot = dot;
exports.lerp = lerp;
exports.random = random;
exports.transformMat4 = transformMat4;
exports.transformQuat = transformQuat;
exports.str = str;
exports.exactEquals = exactEquals;
exports.equals = equals;
var _common = __webpack_require__(36);
var glMatrix = _interopRequireWildcard(_common);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* 4 Dimensional Vector
* @module vec4
*/
/**
* Creates a new, empty vec4
*
* @returns {vec4} a new 4D vector
*/
function create() {
var out = new glMatrix.ARRAY_TYPE(4);
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
return out;
}
/**
* Creates a new vec4 initialized with values from an existing vector
*
* @param {vec4} a vector to clone
* @returns {vec4} a new 4D vector
*/
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
function clone(a) {
var out = new glMatrix.ARRAY_TYPE(4);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
}
/**
* Creates a new vec4 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {vec4} a new 4D vector
*/
function fromValues(x, y, z, w) {
var out = new glMatrix.ARRAY_TYPE(4);
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
return out;
}
/**
* Copy the values from one vec4 to another
*
* @param {vec4} out the receiving vector
* @param {vec4} a the source vector
* @returns {vec4} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
}
/**
* Set the components of a vec4 to the given values
*
* @param {vec4} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {vec4} out
*/
function set(out, x, y, z, w) {
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
return out;
}
/**
* Adds two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
function add(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
out[3] = a[3] + b[3];
return out;
}
/**
* Subtracts vector b from vector a
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
function subtract(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
out[3] = a[3] - b[3];
return out;
}
/**
* Multiplies two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
function multiply(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
out[2] = a[2] * b[2];
out[3] = a[3] * b[3];
return out;
}
/**
* Divides two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
function divide(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
out[2] = a[2] / b[2];
out[3] = a[3] / b[3];
return out;
}
/**
* Math.ceil the components of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to ceil
* @returns {vec4} out
*/
function ceil(out, a) {
out[0] = Math.ceil(a[0]);
out[1] = Math.ceil(a[1]);
out[2] = Math.ceil(a[2]);
out[3] = Math.ceil(a[3]);
return out;
}
/**
* Math.floor the components of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to floor
* @returns {vec4} out
*/
function floor(out, a) {
out[0] = Math.floor(a[0]);
out[1] = Math.floor(a[1]);
out[2] = Math.floor(a[2]);
out[3] = Math.floor(a[3]);
return out;
}
/**
* Returns the minimum of two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
function min(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
out[2] = Math.min(a[2], b[2]);
out[3] = Math.min(a[3], b[3]);
return out;
}
/**
* Returns the maximum of two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
function max(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
out[2] = Math.max(a[2], b[2]);
out[3] = Math.max(a[3], b[3]);
return out;
}
/**
* Math.round the components of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to round
* @returns {vec4} out
*/
function round(out, a) {
out[0] = Math.round(a[0]);
out[1] = Math.round(a[1]);
out[2] = Math.round(a[2]);
out[3] = Math.round(a[3]);
return out;
}
/**
* Scales a vec4 by a scalar number
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec4} out
*/
function scale(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
out[3] = a[3] * b;
return out;
}
/**
* Adds two vec4's after scaling the second operand by a scalar value
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec4} out
*/
function scaleAndAdd(out, a, b, scale) {
out[0] = a[0] + b[0] * scale;
out[1] = a[1] + b[1] * scale;
out[2] = a[2] + b[2] * scale;
out[3] = a[3] + b[3] * scale;
return out;
}
/**
* Calculates the euclidian distance between two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} distance between a and b
*/
function distance(a, b) {
var x = b[0] - a[0];
var y = b[1] - a[1];
var z = b[2] - a[2];
var w = b[3] - a[3];
return Math.sqrt(x * x + y * y + z * z + w * w);
}
/**
* Calculates the squared euclidian distance between two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} squared distance between a and b
*/
function squaredDistance(a, b) {
var x = b[0] - a[0];
var y = b[1] - a[1];
var z = b[2] - a[2];
var w = b[3] - a[3];
return x * x + y * y + z * z + w * w;
}
/**
* Calculates the length of a vec4
*
* @param {vec4} a vector to calculate length of
* @returns {Number} length of a
*/
function length(a) {
var x = a[0];
var y = a[1];
var z = a[2];
var w = a[3];
return Math.sqrt(x * x + y * y + z * z + w * w);
}
/**
* Calculates the squared length of a vec4
*
* @param {vec4} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
function squaredLength(a) {
var x = a[0];
var y = a[1];
var z = a[2];
var w = a[3];
return x * x + y * y + z * z + w * w;
}
/**
* Negates the components of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to negate
* @returns {vec4} out
*/
function negate(out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
out[3] = -a[3];
return out;
}
/**
* Returns the inverse of the components of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to invert
* @returns {vec4} out
*/
function inverse(out, a) {
out[0] = 1.0 / a[0];
out[1] = 1.0 / a[1];
out[2] = 1.0 / a[2];
out[3] = 1.0 / a[3];
return out;
}
/**
* Normalize a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to normalize
* @returns {vec4} out
*/
function normalize(out, a) {
var x = a[0];
var y = a[1];
var z = a[2];
var w = a[3];
var len = x * x + y * y + z * z + w * w;
if (len > 0) {
len = 1 / Math.sqrt(len);
out[0] = x * len;
out[1] = y * len;
out[2] = z * len;
out[3] = w * len;
}
return out;
}
/**
* Calculates the dot product of two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} dot product of a and b
*/
function dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
/**
* Performs a linear interpolation between two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec4} out
*/
function lerp(out, a, b, t) {
var ax = a[0];
var ay = a[1];
var az = a[2];
var aw = a[3];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
out[2] = az + t * (b[2] - az);
out[3] = aw + t * (b[3] - aw);
return out;
}
/**
* Generates a random vector with the given scale
*
* @param {vec4} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec4} out
*/
function random(out, vectorScale) {
vectorScale = vectorScale || 1.0;
//TODO: This is a pretty awful way of doing this. Find something better.
out[0] = glMatrix.RANDOM();
out[1] = glMatrix.RANDOM();
out[2] = glMatrix.RANDOM();
out[3] = glMatrix.RANDOM();
normalize(out, out);
scale(out, out, vectorScale);
return out;
}
/**
* Transforms the vec4 with a mat4.
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec4} out
*/
function transformMat4(out, a, m) {
var x = a[0],
y = a[1],
z = a[2],
w = a[3];
out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
return out;
}
/**
* Transforms the vec4 with a quat
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec4} out
*/
function transformQuat(out, a, q) {
var x = a[0],
y = a[1],
z = a[2];
var qx = q[0],
qy = q[1],
qz = q[2],
qw = q[3];
// calculate quat * vec
var ix = qw * x + qy * z - qz * y;
var iy = qw * y + qz * x - qx * z;
var iz = qw * z + qx * y - qy * x;
var iw = -qx * x - qy * y - qz * z;
// calculate result * inverse quat
out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
out[3] = a[3];
return out;
}
/**
* Returns a string representation of a vector
*
* @param {vec4} a vector to represent as a string
* @returns {String} string representation of the vector
*/
function str(a) {
return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
}
/**
* Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
*
* @param {vec4} a The first vector.
* @param {vec4} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function exactEquals(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
}
/**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec4} a The first vector.
* @param {vec4} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function equals(a, b) {
var a0 = a[0],
a1 = a[1],
a2 = a[2],
a3 = a[3];
var b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3];
return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));
}
/**
* Alias for {@link vec4.subtract}
* @function
*/
var sub = exports.sub = subtract;
/**
* Alias for {@link vec4.multiply}
* @function
*/
var mul = exports.mul = multiply;
/**
* Alias for {@link vec4.divide}
* @function
*/
var div = exports.div = divide;
/**
* Alias for {@link vec4.distance}
* @function
*/
var dist = exports.dist = distance;
/**
* Alias for {@link vec4.squaredDistance}
* @function
*/
var sqrDist = exports.sqrDist = squaredDistance;
/**
* Alias for {@link vec4.length}
* @function
*/
var len = exports.len = length;
/**
* Alias for {@link vec4.squaredLength}
* @function
*/
var sqrLen = exports.sqrLen = squaredLength;
/**
* Perform some operation over an array of vec4s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
var forEach = exports.forEach = function () {
var vec = create();
return function (a, stride, offset, count, fn, arg) {
var i = void 0,
l = void 0;
if (!stride) {
stride = 4;
}
if (!offset) {
offset = 0;
}
if (count) {
l = Math.min(count * stride + offset, a.length);
} else {
l = a.length;
}
for (i = offset; i < l; i += stride) {
vec[0] = a[i];vec[1] = a[i + 1];vec[2] = a[i + 2];vec[3] = a[i + 3];
fn(vec, vec, arg);
a[i] = vec[0];a[i + 1] = vec[1];a[i + 2] = vec[2];a[i + 3] = vec[3];
}
return a;
};
}();
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _ForwardPass = __webpack_require__(547);
var _ForwardPass2 = _interopRequireDefault(_ForwardPass);
var _ViewNodeFactory = __webpack_require__(551);
var _ViewNodeFactory2 = _interopRequireDefault(_ViewNodeFactory);
var _RenderPass = __webpack_require__(273);
var _RenderPass2 = _interopRequireDefault(_RenderPass);
var _ShaderCache = __webpack_require__(590);
var _ShaderCache2 = _interopRequireDefault(_ShaderCache);
var _ViewNode = __webpack_require__(24);
var _ViewNode2 = _interopRequireDefault(_ViewNode);
var _TextureUnitManager = __webpack_require__(592);
var _TextureUnitManager2 = _interopRequireDefault(_TextureUnitManager);
var _Constants = __webpack_require__(32);
var _webvrPolyfill = __webpack_require__(593);
var _webvrPolyfill2 = _interopRequireDefault(_webvrPolyfill);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(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 vtkDebugMacro = _macro2.default.vtkDebugMacro,
vtkErrorMacro = _macro2.default.vtkErrorMacro;
function checkRenderTargetSupport(gl, format, type) {
// create temporary frame buffer and texture
var framebuffer = gl.createFramebuffer();
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, format, 2, 2, 0, format, type, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
// check frame buffer status
var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
// clean up
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindTexture(gl.TEXTURE_2D, null);
return status === gl.FRAMEBUFFER_COMPLETE;
}
// ----------------------------------------------------------------------------
// vtkOpenGLRenderWindow methods
// ----------------------------------------------------------------------------
function vtkOpenGLRenderWindow(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLRenderWindow');
// Auto update style
function updateWindow() {
// Canvas size
if (model.renderable) {
model.canvas.setAttribute('width', model.size[0]);
model.canvas.setAttribute('height', model.size[1]);
}
// Offscreen ?
model.canvas.style.display = model.useOffScreen ? 'none' : 'block';
// Cursor type
if (model.el) {
model.el.style.cursor = model.cursorVisibility ? model.cursor : 'none';
}
}
publicAPI.onModified(updateWindow);
// Builds myself.
publicAPI.buildPass = function (prepass) {
if (prepass) {
if (!model.renderable) {
return;
}
publicAPI.prepareNodes();
publicAPI.addMissingNodes(model.renderable.getRenderersByReference());
publicAPI.removeUnusedNodes();
publicAPI.initialize();
model.children.forEach(function (child) {
child.setOpenGLRenderWindow(publicAPI);
});
}
};
publicAPI.initialize = function () {
if (!model.initialized) {
model.context = publicAPI.get3DContext();
model.textureUnitManager = _TextureUnitManager2.default.newInstance();
model.textureUnitManager.setContext(model.context);
model.shaderCache.setContext(model.context);
// initialize blending for transparency
var gl = model.context;
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.depthFunc(gl.LEQUAL);
gl.enable(gl.BLEND);
model.initialized = true;
}
};
publicAPI.makeCurrent = function () {
model.context.makeCurrent();
};
publicAPI.setContainer = function (el) {
if (model.el && model.el !== el) {
// Remove canvas from previous container
if (model.canvas.parentNode === model.el) {
model.el.removeChild(model.canvas);
} else {
vtkErrorMacro('Error: canvas parent node does not match container');
}
}
if (model.el !== el) {
model.el = el;
if (model.el) {
model.el.appendChild(model.canvas);
}
// Trigger modified()
publicAPI.modified();
}
};
publicAPI.getFramebufferSize = function () {
if (model.activeFramebuffer) {
return model.activeFramebuffer.getSize();
}
return model.size;
};
publicAPI.isInViewport = function (x, y, viewport) {
var vCoords = viewport.getViewportByReference();
var size = publicAPI.getFramebufferSize();
if (vCoords[0] * size[0] <= x && vCoords[2] * size[0] >= x && vCoords[1] * size[1] <= y && vCoords[3] * size[1] >= y) {
return true;
}
return false;
};
publicAPI.getViewportSize = function (viewport) {
var vCoords = viewport.getViewportByReference();
var size = publicAPI.getFramebufferSize();
return [(vCoords[2] - vCoords[0]) * size[0], (vCoords[3] - vCoords[1]) * size[1]];
};
publicAPI.getViewportCenter = function (viewport) {
var size = publicAPI.getViewportSize(viewport);
return [size[0] * 0.5, size[1] * 0.5];
};
publicAPI.displayToNormalizedDisplay = function (x, y, z) {
var size = publicAPI.getFramebufferSize();
return [x / size[0], y / size[1], z];
};
publicAPI.normalizedDisplayToDisplay = function (x, y, z) {
var size = publicAPI.getFramebufferSize();
return [x * size[0], y * size[1], z];
};
publicAPI.worldToView = function (x, y, z, renderer) {
var dims = publicAPI.getViewportSize(renderer);
return renderer.worldToView(x, y, z, dims[0] / dims[1]);
};
publicAPI.viewToWorld = function (x, y, z, renderer) {
var dims = publicAPI.getViewportSize(renderer);
return renderer.viewToWorld(x, y, z, dims[0] / dims[1]);
};
publicAPI.worldToDisplay = function (x, y, z, renderer) {
var val = publicAPI.worldToView(x, y, z, renderer);
var val2 = renderer.viewToNormalizedDisplay(val[0], val[1], val[2]);
return publicAPI.normalizedDisplayToDisplay(val2[0], val2[1], val2[2]);
};
publicAPI.displayToWorld = function (x, y, z, renderer) {
var val = publicAPI.displayToNormalizedDisplay(x, y, z);
var val2 = renderer.normalizedDisplayToView(val[0], val[1], val[2]);
return publicAPI.viewToWorld(val2[0], val2[1], val2[2], renderer);
};
publicAPI.normalizedDisplayToViewport = function (x, y, z, renderer) {
var vCoords = renderer.getViewportByReference();
vCoords = publicAPI.normalizedDisplayToDisplay(vCoords[0], vCoords[1], 0.0);
var coords = publicAPI.normalizedDisplayToDisplay(x, y, z);
return [coords[0] - vCoords[0] - 0.5, coords[1] - vCoords[1] - 0.5, z];
};
publicAPI.viewportToNormalizedViewport = function (x, y, z, renderer) {
var size = publicAPI.getViewportSize(renderer);
if (size && size[0] !== 0 && size[1] !== 0) {
return [x / (size[0] - 1.0), y / (size[1] - 1.0), z];
}
return [x, y, z];
};
publicAPI.normalizedViewportToViewport = function (x, y, z) {
var size = publicAPI.getFramebufferSize();
return [x * (size[0] - 1.0), y * (size[1] - 1.0), z];
};
publicAPI.displayToLocalDisplay = function (x, y, z) {
var size = publicAPI.getFramebufferSize();
return [x, size[1] - y - 1, z];
};
publicAPI.viewportToNormalizedDisplay = function (x, y, z, renderer) {
var vCoords = renderer.getViewportByReference();
vCoords = publicAPI.normalizedDisplayToDisplay(vCoords[0], vCoords[1], 0.0);
var x2 = x + vCoords[0] + 0.5;
var y2 = y + vCoords[1] + 0.5;
return publicAPI.displayToNormalizedDisplay(x2, y2, z);
};
publicAPI.getPixelData = function (x1, y1, x2, y2) {
var pixels = new Uint8Array((x2 - x1 + 1) * (y2 - y1 + 1) * 4);
model.context.readPixels(x1, y1, x2 - x1 + 1, y2 - y1 + 1, model.context.RGBA, model.context.UNSIGNED_BYTE, pixels);
return pixels;
};
publicAPI.get2DContext = function () {
return model.canvas.getContext('2d');
};
publicAPI.get3DContext = function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { preserveDrawingBuffer: false, depth: true, alpha: true };
var result = null;
var webgl2Supported = typeof WebGL2RenderingContext !== 'undefined';
model.webgl2 = false;
if (model.defaultToWebgl2 && webgl2Supported) {
result = model.canvas.getContext('webgl2'); // , options);
if (result) {
model.webgl2 = true;
vtkDebugMacro('using webgl2');
}
}
if (!result) {
vtkDebugMacro('using webgl1');
result = model.canvas.getContext('webgl', options) || model.canvas.getContext('experimental-webgl', options);
}
/* eslint-disable */
var polyfill = new _webvrPolyfill2.default({
// Ensures the polyfill is always active on mobile, due to providing
// a polyfilled CardboardVRDisplay when no native API is available,
// and also polyfilling even when the native API is available, due to
// providing a CardboardVRDisplay when no native VRDisplays exist.
PROVIDE_MOBILE_VRDISPLAY: true,
// Polyfill optimizations
DIRTY_SUBMIT_FRAME_BINDINGS: false,
BUFFER_SCALE: 0.75
});
/* eslint-enable */
// Do we have webvr support
if (navigator.getVRDisplays) {
navigator.getVRDisplays().then(function (displays) {
if (displays.length > 0) {
// take the first display for now
model.vrDisplay = displays[0];
// set the clipping ranges
model.vrDisplay.depthNear = 0.01; // meters
model.vrDisplay.depthFar = 100.0; // meters
publicAPI.invokeHaveVRDisplay();
}
});
}
// prevent default context lost handler
model.canvas.addEventListener('webglcontextlost', function (event) {
event.preventDefault();
}, false);
model.canvas.addEventListener('webglcontextrestored', publicAPI.restoreContext, false);
return result;
};
publicAPI.startVR = function () {
if (model.vrDisplay.capabilities.canPresent) {
model.vrDisplay.requestPresent([{ source: model.canvas }]).then(function () {
model.oldCanvasSize = model.size.slice();
if (model.el && model.vrDisplay.capabilities.hasExternalDisplay) {
model.el.style.display = 'none';
}
if (model.queryVRSize) {
var leftEye = model.vrDisplay.getEyeParameters('left');
var rightEye = model.vrDisplay.getEyeParameters('right');
var width = Math.floor(leftEye.renderWidth + rightEye.renderWidth);
var height = Math.floor(Math.max(leftEye.renderHeight, rightEye.renderHeight));
publicAPI.setSize(width, height);
} else {
publicAPI.setSize(model.vrResolution);
}
var ren = model.renderable.getRenderers()[0];
ren.resetCamera();
model.vrFrameData = new VRFrameData();
model.renderable.getInteractor().switchToVRAnimation();
publicAPI.vrRender();
}).catch(function () {
console.log('failed to requestPresent');
});
} else {
vtkErrorMacro('vrDisplay is not connected');
}
};
publicAPI.stopVR = function () {
model.renderable.getInteractor().returnFromVRAnimation();
model.vrDisplay.exitPresent();
model.vrDisplay.cancelAnimationFrame(model.vrSceneFrame);
publicAPI.setSize.apply(publicAPI, _toConsumableArray(model.oldCanvasSize));
if (model.el && model.vrDisplay.capabilities.hasExternalDisplay) {
model.el.style.display = 'block';
}
var ren = model.renderable.getRenderers()[0];
ren.getActiveCamera().setProjectionMatrix(null);
ren.setViewport(0.0, 0, 1.0, 1.0);
publicAPI.traverseAllPasses();
};
publicAPI.vrRender = function () {
model.renderable.getInteractor().updateGamepads(model.vrDisplay.displayId);
model.vrSceneFrame = model.vrDisplay.requestAnimationFrame(publicAPI.vrRender);
model.vrDisplay.getFrameData(model.vrFrameData);
// get the first renderer
var ren = model.renderable.getRenderers()[0];
// do the left eye
ren.setViewport(0, 0, 0.5, 1.0);
ren.getActiveCamera().computeViewParametersFromPhysicalMatrix(model.vrFrameData.leftViewMatrix);
ren.getActiveCamera().setProjectionMatrix(model.vrFrameData.leftProjectionMatrix);
publicAPI.traverseAllPasses();
ren.setViewport(0.5, 0, 1.0, 1.0);
ren.getActiveCamera().computeViewParametersFromPhysicalMatrix(model.vrFrameData.rightViewMatrix);
ren.getActiveCamera().setProjectionMatrix(model.vrFrameData.rightProjectionMatrix);
publicAPI.traverseAllPasses();
model.vrDisplay.submitFrame();
};
publicAPI.restoreContext = function () {
var rp = _RenderPass2.default.newInstance();
rp.setCurrentOperation('Release');
rp.traverse(publicAPI, null);
};
publicAPI.activateTexture = function (texture) {
// Only add if it isn't already there
var result = model.textureResourceIds.get(texture);
if (result !== undefined) {
model.context.activeTexture(model.context.TEXTURE0 + result);
return;
}
var activeUnit = publicAPI.getTextureUnitManager().allocate();
if (activeUnit < 0) {
vtkErrorMacro('Hardware does not support the number of textures defined.');
return;
}
model.textureResourceIds.set(texture, activeUnit);
model.context.activeTexture(model.context.TEXTURE0 + activeUnit);
};
publicAPI.deactivateTexture = function (texture) {
// Only deactivate if it isn't already there
var result = model.textureResourceIds.get(texture);
if (result !== undefined) {
publicAPI.getTextureUnitManager().free(result);
delete model.textureResourceIds.delete(texture);
}
};
publicAPI.getTextureUnitForTexture = function (texture) {
var result = model.textureResourceIds.get(texture);
if (result !== undefined) {
return result;
}
return -1;
};
publicAPI.getDefaultTextureInternalFormat = function (vtktype, numComps, useFloat) {
if (model.webgl2) {
switch (vtktype) {
case _Constants.VtkDataTypes.UNSIGNED_CHAR:
switch (numComps) {
case 1:
return model.context.R8;
case 2:
return model.context.RG8;
case 3:
return model.context.RGB8;
case 4:
default:
return model.context.RGBA8;
}
default:
case _Constants.VtkDataTypes.FLOAT:
switch (numComps) {
case 1:
return model.context.R16F;
case 2:
return model.context.RG16F;
case 3:
return model.context.RGB16F;
case 4:
default:
return model.context.RGBA16F;
}
}
}
// webgl1 only supports four types
switch (numComps) {
case 1:
return model.context.LUMINANCE;
case 2:
return model.context.LUMINANCE_ALPHA;
case 3:
return model.context.RGB;
case 4:
default:
return model.context.RGBA;
}
};
function getCanvasDataURL() {
var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : model.imageFormat;
return model.canvas.toDataURL(format);
}
publicAPI.captureNextImage = function () {
var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'image/png';
if (model.deleted) {
return null;
}
model.imageFormat = format;
var previous = model.notifyImageReady;
model.notifyImageReady = true;
return new Promise(function (resolve, reject) {
var subscription = publicAPI.onImageReady(function (imageURL) {
model.notifyImageReady = previous;
subscription.unsubscribe();
resolve(imageURL);
});
});
};
publicAPI.getGLInformations = function () {
var gl = publicAPI.get3DContext();
var glTextureFloat = gl.getExtension('OES_texture_float');
var glTextureHalfFloat = gl.getExtension('OES_texture_half_float');
var glDebugRendererInfo = gl.getExtension('WEBGL_debug_renderer_info');
var glDrawBuffers = gl.getExtension('WEBGL_draw_buffers');
var glAnisotropic = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
var params = [['Max Vertex Attributes', 'MAX_VERTEX_ATTRIBS', gl.getParameter(gl.MAX_VERTEX_ATTRIBS)], ['Max Varying Vectors', 'MAX_VARYING_VECTORS', gl.getParameter(gl.MAX_VARYING_VECTORS)], ['Max Vertex Uniform Vectors', 'MAX_VERTEX_UNIFORM_VECTORS', gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS)], ['Max Fragment Uniform Vectors', 'MAX_FRAGMENT_UNIFORM_VECTORS', gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS)], ['Max Fragment Texture Image Units', 'MAX_TEXTURE_IMAGE_UNITS', gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)], ['Max Vertex Texture Image Units', 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS)], ['Max Combined Texture Image Units', 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS)], ['Max 2D Texture Size', 'MAX_TEXTURE_SIZE', gl.getParameter(gl.MAX_TEXTURE_SIZE)], ['Max Cube Texture Size', 'MAX_CUBE_MAP_TEXTURE_SIZE', gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE)], ['Max Texture Anisotropy', 'MAX_TEXTURE_MAX_ANISOTROPY_EXT', glAnisotropic && gl.getParameter(glAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)], ['Point Size Range', 'ALIASED_POINT_SIZE_RANGE', gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE).join(' - ')], ['Line Width Range', 'ALIASED_LINE_WIDTH_RANGE', gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE).join(' - ')], ['Max Viewport Dimensions', 'MAX_VIEWPORT_DIMS', gl.getParameter(gl.MAX_VIEWPORT_DIMS).join(' - ')], ['Max Renderbuffer Size', 'MAX_RENDERBUFFER_SIZE', gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)], ['Framebuffer Red Bits', 'RED_BITS', gl.getParameter(gl.RED_BITS)], ['Framebuffer Green Bits', 'GREEN_BITS', gl.getParameter(gl.GREEN_BITS)], ['Framebuffer Blue Bits', 'BLUE_BITS', gl.getParameter(gl.BLUE_BITS)], ['Framebuffer Alpha Bits', 'ALPHA_BITS', gl.getParameter(gl.ALPHA_BITS)], ['Framebuffer Depth Bits', 'DEPTH_BITS', gl.getParameter(gl.DEPTH_BITS)], ['Framebuffer Stencil Bits', 'STENCIL_BITS', gl.getParameter(gl.STENCIL_BITS)], ['Framebuffer Subpixel Bits', 'SUBPIXEL_BITS', gl.getParameter(gl.SUBPIXEL_BITS)], ['MSAA Samples', 'SAMPLES', gl.getParameter(gl.SAMPLES)], ['MSAA Sample Buffers', 'SAMPLE_BUFFERS', gl.getParameter(gl.SAMPLE_BUFFERS)], ['Supported Formats for UByte Render Targets ', 'UNSIGNED_BYTE RENDER TARGET FORMATS', [glTextureFloat && checkRenderTargetSupport(gl, gl.RGBA, gl.UNSIGNED_BYTE) ? 'RGBA' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.RGB, gl.UNSIGNED_BYTE) ? 'RGB' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.LUMINANCE, gl.UNSIGNED_BYTE) ? 'LUMINANCE' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.ALPHA, gl.UNSIGNED_BYTE) ? 'ALPHA' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.LUMINANCE_ALPHA, gl.UNSIGNED_BYTE) ? 'LUMINANCE_ALPHA' : ''].join(' ')], ['Supported Formats for Half Float Render Targets', 'HALF FLOAT RENDER TARGET FORMATS', [glTextureHalfFloat && checkRenderTargetSupport(gl, gl.RGBA, glTextureHalfFloat.HALF_FLOAT_OES) ? 'RGBA' : '', glTextureHalfFloat && checkRenderTargetSupport(gl, gl.RGB, glTextureHalfFloat.HALF_FLOAT_OES) ? 'RGB' : '', glTextureHalfFloat && checkRenderTargetSupport(gl, gl.LUMINANCE, glTextureHalfFloat.HALF_FLOAT_OES) ? 'LUMINANCE' : '', glTextureHalfFloat && checkRenderTargetSupport(gl, gl.ALPHA, glTextureHalfFloat.HALF_FLOAT_OES) ? 'ALPHA' : '', glTextureHalfFloat && checkRenderTargetSupport(gl, gl.LUMINANCE_ALPHA, glTextureHalfFloat.HALF_FLOAT_OES) ? 'LUMINANCE_ALPHA' : ''].join(' ')], ['Supported Formats for Full Float Render Targets', 'FLOAT RENDER TARGET FORMATS', [glTextureFloat && checkRenderTargetSupport(gl, gl.RGBA, gl.FLOAT) ? 'RGBA' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.RGB, gl.FLOAT) ? 'RGB' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.LUMINANCE, gl.FLOAT) ? 'LUMINANCE' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.ALPHA, gl.FLOAT) ? 'ALPHA' : '', glTextureFloat && checkRenderTargetSupport(gl, gl.LUMINANCE_ALPHA, gl.FLOAT) ? 'LUMINANCE_ALPHA' : ''].join(' ')], ['Max Multiple Render Targets Buffers', 'MAX_DRAW_BUFFERS_WEBGL', glDrawBuffers ? gl.getParameter(glDrawBuffers.MAX_DRAW_BUFFERS_WEBGL) : 0], ['High Float Precision in Vertex Shader', 'HIGH_FLOAT VERTEX_SHADER', [gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).rangeMax, ')'].join('')], ['Medium Float Precision in Vertex Shader', 'MEDIUM_FLOAT VERTEX_SHADER', [gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMax, ')'].join('')], ['Low Float Precision in Vertex Shader', 'LOW_FLOAT VERTEX_SHADER', [gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT).rangeMax, ')'].join('')], ['High Float Precision in Fragment Shader', 'HIGH_FLOAT FRAGMENT_SHADER', [gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).rangeMax, ')'].join('')], ['Medium Float Precision in Fragment Shader', 'MEDIUM_FLOAT FRAGMENT_SHADER', [gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).rangeMax, ')'].join('')], ['Low Float Precision in Fragment Shader', 'LOW_FLOAT FRAGMENT_SHADER', [gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT).rangeMax, ')'].join('')], ['High Int Precision in Vertex Shader', 'HIGH_INT VERTEX_SHADER', [gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT).rangeMax, ')'].join('')], ['Medium Int Precision in Vertex Shader', 'MEDIUM_INT VERTEX_SHADER', [gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT).rangeMax, ')'].join('')], ['Low Int Precision in Vertex Shader', 'LOW_INT VERTEX_SHADER', [gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT).rangeMax, ')'].join('')], ['High Int Precision in Fragment Shader', 'HIGH_INT FRAGMENT_SHADER', [gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT).rangeMax, ')'].join('')], ['Medium Int Precision in Fragment Shader', 'MEDIUM_INT FRAGMENT_SHADER', [gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT).rangeMax, ')'].join('')], ['Low Int Precision in Fragment Shader', 'LOW_INT FRAGMENT_SHADER', [gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).precision, ' (-2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMin, ' - 2', gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMax, ')'].join('')], ['Supported Extensions', 'EXTENSIONS', gl.getSupportedExtensions().join('
\t\t\t\t\t ')], ['WebGL Renderer', 'RENDERER', gl.getParameter(gl.RENDERER)], ['WebGL Vendor', 'VENDOR', gl.getParameter(gl.VENDOR)], ['WebGL Version', 'VERSION', gl.getParameter(gl.VERSION)], ['Shading Language Version', 'SHADING_LANGUAGE_VERSION', gl.getParameter(gl.SHADING_LANGUAGE_VERSION)], ['Unmasked Renderer', 'UNMASKED_RENDERER', glDebugRendererInfo && gl.getParameter(glDebugRendererInfo.UNMASKED_RENDERER_WEBGL)], ['Unmasked Vendor', 'UNMASKED_VENDOR', glDebugRendererInfo && gl.getParameter(glDebugRendererInfo.UNMASKED_VENDOR_WEBGL)], ['WebGL Version', 'WEBGL_VERSION', model.webgl2 ? 2 : 1]];
var result = {};
while (params.length) {
var _params$pop = params.pop(),
_params$pop2 = _slicedToArray(_params$pop, 3),
label = _params$pop2[0],
key = _params$pop2[1],
value = _params$pop2[2];
if (key) {
result[key] = { label: label, value: value };
}
}
return result;
};
publicAPI.traverseAllPasses = function () {
if (model.renderPasses) {
for (var index = 0; index < model.renderPasses.length; ++index) {
model.renderPasses[index].traverse(publicAPI, null);
}
}
if (model.notifyImageReady) {
publicAPI.invokeImageReady(getCanvasDataURL());
}
};
publicAPI.disableDepthMask = function () {
if (model.depthMaskEnabled) {
model.context.depthMask(false);
model.depthMaskEnabled = false;
}
};
publicAPI.enableDepthMask = function () {
if (!model.depthMaskEnabled) {
model.context.depthMask(true);
model.depthMaskEnabled = true;
}
};
publicAPI.disableCullFace = function () {
if (model.cullFaceEnabled) {
model.context.disable(model.context.CULL_FACE);
model.cullFaceEnabled = false;
}
};
publicAPI.enableCullFace = function () {
if (!model.cullFaceEnabled) {
model.context.enable(model.context.CULL_FACE);
model.cullFaceEnabled = true;
}
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
cullFaceEnabled: false,
depthMaskEnabled: true,
shaderCache: null,
initialized: false,
context: null,
canvas: null,
size: [300, 300],
cursorVisibility: true,
cursor: 'pointer',
textureUnitManager: null,
textureResourceIds: null,
renderPasses: [],
notifyImageReady: false,
webgl2: false,
defaultToWebgl2: true, // attempt webgl2 on by default
vrResolution: [2160, 1200],
queryVRSize: false,
activeFramebuffer: null,
vrDisplay: null,
imageFormat: 'image/png'
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Create internal instances
model.canvas = document.createElement('canvas');
model.canvas.style.width = '100%';
model.textureResourceIds = new Map();
// Inheritance
_ViewNode2.default.extend(publicAPI, model, initialValues);
model.myFactory = _ViewNodeFactory2.default.newInstance();
model.shaderCache = _ShaderCache2.default.newInstance();
model.shaderCache.setOpenGLRenderWindow(publicAPI);
// setup default forward pass rendering
model.renderPasses[0] = _ForwardPass2.default.newInstance();
_macro2.default.event(publicAPI, model, 'imageReady');
_macro2.default.event(publicAPI, model, 'haveVRDisplay');
// Build VTK API
_macro2.default.get(publicAPI, model, ['shaderCache', 'textureUnitManager', 'webgl2', 'vrDisplay']);
_macro2.default.setGet(publicAPI, model, ['initialized', 'context', 'canvas', 'renderPasses', 'notifyImageReady', 'defaultToWebgl2', 'cursor', 'queryVRSize',
// might want to make this not call modified as
// we change the active framebuffer a lot. Or maybe
// only mark modified if the size or depth
// of the buffer has changed
'activeFramebuffer']);
_macro2.default.setGetArray(publicAPI, model, ['size', 'vrResolution'], 2);
// Object methods
vtkOpenGLRenderWindow(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkOpenGLRenderWindow');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 272 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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"); } }
var TinyEmitter = function () {
function TinyEmitter() {
_classCallCheck(this, TinyEmitter);
Object.defineProperty(this, '__listeners', {
value: {},
enumerable: false,
writable: false
});
}
_createClass(TinyEmitter, [{
key: 'emit',
value: function emit(eventName) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.__listeners[eventName][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var handler = _step.value;
handler.apply(undefined, args);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return this;
}
}, {
key: 'once',
value: function once(eventName, handler) {
var _this = this;
var once = function once() {
_this.off(eventName, once);
handler.apply(undefined, arguments);
};
return this.on(eventName, once);
}
}, {
key: 'on',
value: function on(eventName, handler) {
if (!this.__listeners[eventName]) this.__listeners[eventName] = [];
this.__listeners[eventName].push(handler);
return this;
}
}, {
key: 'off',
value: function off(eventName, handler) {
if (handler) this.__listeners[eventName] = this.__listeners[eventName].filter(function (h) {
return h !== handler;
});else this.__listeners[eventName] = [];
return this;
}
}]);
return TinyEmitter;
}();
module.exports = TinyEmitter;
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// ----------------------------------------------------------------------------
function vtkRenderPass(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkRenderPass');
publicAPI.getOperation = function () {
return model.currentOperation;
};
publicAPI.setCurrentOperation = function (val) {
model.currentOperation = val;
model.currentTraverseOperation = 'traverse' + _macro2.default.capitalize(model.currentOperation);
};
publicAPI.getTraverseOperation = function () {
return model.currentTraverseOperation;
};
// by default this class will traverse all of its
// preDelegateOperations, then call its delegate render passes
// the traverse all of its postDelegateOperations
// any of those three arrays can be empty
publicAPI.traverse = function (viewNode) {
var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (model.deleted) {
return;
}
// we just render our delegates in order
model.currentParent = parent;
model.preDelegateOperations.forEach(function (val) {
publicAPI.setCurrentOperation(val);
viewNode.traverse(publicAPI);
});
model.delegates.forEach(function (val) {
val.traverse(viewNode, publicAPI);
});
model.postDelegateOperations.forEach(function (val) {
publicAPI.setCurrentOperation(val);
viewNode.traverse(publicAPI);
});
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
delegates: [],
currentOperation: null,
preDelegateOperations: [],
postDelegateOperations: [],
currentParent: null
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
_macro2.default.obj(publicAPI, model);
_macro2.default.get(publicAPI, model, ['currentOperation']);
_macro2.default.setGet(publicAPI, model, ['delegates', 'currentParent', 'preDelegateOperations', 'postDelegateOperations']);
// Object methods
vtkRenderPass(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkRenderPass');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 274 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Constants = __webpack_require__(558);
var _Constants2 = _interopRequireDefault(_Constants);
var _Framebuffer = __webpack_require__(169);
var _Framebuffer2 = _interopRequireDefault(_Framebuffer);
var _SelectionNode = __webpack_require__(559);
var _SelectionNode2 = _interopRequireDefault(_SelectionNode);
var _DataSet = __webpack_require__(170);
var _DataSet2 = _interopRequireDefault(_DataSet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var PassTypes = _Constants2.default.PassTypes;
var SelectionContent = _SelectionNode2.default.SelectionContent,
SelectionField = _SelectionNode2.default.SelectionField;
var FieldAssociations = _DataSet2.default.FieldAssociations;
var vtkErrorMacro = _macro2.default.vtkErrorMacro;
// ----------------------------------------------------------------------------
// vtkOpenGLHardwareSelector methods
// ----------------------------------------------------------------------------
function vtkOpenGLHardwareSelector(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLHardwareSelector');
//----------------------------------------------------------------------------
publicAPI.releasePixBuffers = function () {
model.pixBuffer = [];
};
//----------------------------------------------------------------------------
publicAPI.beginSelection = function () {
model.openGLRenderer = model.openGLRenderWindow.getViewNodeFor(model.renderer);
model.maxAttributeId = 0;
model.framebuffer = _Framebuffer2.default.newInstance();
model.framebuffer.setOpenGLRenderWindow(model.openGLRenderWindow);
model.framebuffer.saveCurrentBindingsAndBuffers();
var size = model.openGLRenderWindow.getSize();
model.framebuffer.create(size[0], size[1]);
model.framebuffer.populateFramebuffer();
model.openGLRenderer.clear();
model.openGLRenderer.setSelector(publicAPI);
model.hitProps = [];
model.props = [];
publicAPI.releasePixBuffers();
};
//----------------------------------------------------------------------------
publicAPI.endSelection = function () {
model.hitProps = [];
model.openGLRenderer.setSelector(null);
model.framebuffer.restorePreviousBindingsAndBuffers();
};
publicAPI.preCapturePass = function () {};
publicAPI.postCapturePass = function () {};
//----------------------------------------------------------------------------
publicAPI.select = function () {
var sel = null;
if (publicAPI.captureBuffers()) {
sel = publicAPI.generateSelection(model.area[0], model.area[1], model.area[2], model.area[3]);
publicAPI.releasePixBuffers();
}
return sel;
};
//----------------------------------------------------------------------------
publicAPI.captureBuffers = function () {
if (!model.renderer || !model.openGLRenderWindow) {
vtkErrorMacro('Renderer and view must be set before calling Select.');
return false;
}
model.openGLRenderer = model.openGLRenderWindow.getViewNodeFor(model.renderer);
// int rgba[4];
// rwin.getColorBufferSizes(rgba);
// if (rgba[0] < 8 || rgba[1] < 8 || rgba[2] < 8) {
// vtkErrorMacro("Color buffer depth must be atleast 8 bit. "
// "Currently: " << rgba[0] << ", " << rgba[1] << ", " < 0) {
val--;
if (model.hitProps.indexOf(val) === -1) {
model.hitProps.push(val);
}
}
}
}
};
//----------------------------------------------------------------------------
publicAPI.renderProp = function (prop) {
if (model.currentPass === PassTypes.ACTOR_PASS) {
publicAPI.setPropColorValueFromInt(model.props.length + model.idOffset);
model.props.push(prop);
}
};
//----------------------------------------------------------------------------
publicAPI.renderCompositeIndex = function (index) {
if (model.currentPass === PassTypes.COMPOSITE_INDEX_PASS) {
publicAPI.setPropColorValueFromInt(index + model.idOffset);
}
};
//----------------------------------------------------------------------------
// TODO: make inline
publicAPI.renderAttributeId = function (attribid) {
if (attribid < 0) {
// negative attribid is valid. It happens when rendering higher order
// elements where new points are added for rendering smooth surfaces.
return;
}
model.maxAttributeId = attribid > model.maxAttributeId ? attribid : model.maxAttributeId;
// if (model.currentPass < PassTypes.ID_LOW24) {
// return; // useless...
// }
};
//----------------------------------------------------------------------------
publicAPI.getPropFromID = function (id) {
if (id >= 0 && id < model.props.length) {
return model.props[id];
}
return null;
};
//----------------------------------------------------------------------------
publicAPI.passTypeToString = function (type) {
return _macro2.default.enumToString(PassTypes, type);
};
//----------------------------------------------------------------------------
publicAPI.isPropHit = function (id) {
return model.hitProps.hasKey(id);
};
publicAPI.convert = function (xx, yy, pb) {
if (!pb) {
return 0;
}
var offset = (yy * (model.area[2] - model.area[0] + 1) + xx) * 4;
var rgb = [];
rgb[0] = pb[offset];
rgb[1] = pb[offset + 1];
rgb[2] = pb[offset + 2];
var val = rgb[2];
val *= 256;
val += rgb[1];
val *= 256;
val += rgb[0];
return val;
};
publicAPI.setPropColorValueFromInt = function (val) {
model.propColorValue[0] = val % 256 / 255.0;
model.propColorValue[1] = val / 256 % 256 / 255.0;
model.propColorValue[2] = val / 65536 % 256 / 255.0;
};
// info has
// valid
// propId
// prop
// compositeID
// attributeID
//----------------------------------------------------------------------------
publicAPI.getPixelInformation = function (inDisplayPosition, maxDistance, outSelectedPosition) {
// Base case
var maxDist = maxDistance < 0 ? 0 : maxDistance;
if (maxDist === 0) {
outSelectedPosition[0] = inDisplayPosition[0];
outSelectedPosition[1] = inDisplayPosition[1];
if (inDisplayPosition[0] < model.area[0] || inDisplayPosition[0] > model.area[2] || inDisplayPosition[1] < model.area[1] || inDisplayPosition[1] > model.area[3]) {
return null;
}
// offset inDisplayPosition based on the lower-left-corner of the Area.
var displayPosition = [inDisplayPosition[0] - model.area[0], inDisplayPosition[1] - model.area[1]];
var actorid = publicAPI.convert(displayPosition[0], displayPosition[1], model.pixBuffer[PassTypes.ACTOR_PASS]);
if (actorid <= 0) {
// the pixel did not hit any actor.
return null;
}
var _info = {};
_info.valid = true;
_info.propID = actorid - model.idOffset;
_info.prop = publicAPI.getPropFromID(_info.propID);
var compositeID = publicAPI.convert(displayPosition[0], displayPosition[1], model.pixBuffer[PassTypes.COMPOSITE_INDEX_PASS]);
if (compositeID < 0 || compositeID > 0xffffff) {
compositeID = 0;
}
_info.compositeID = compositeID - model.idOffset;
// const low24 = publicAPI.convert(
// displayPosition[0], displayPosition[1], model.pixBuffer[PassTypes.ID_LOW24]);
// // id 0 is reserved for nothing present.
// info.attributeID = low24 - model.idOffset;
// if (info.attributeID < 0) {
// // the pixel did not hit any cell.
// return null;
// }
return _info;
}
// Iterate over successively growing boxes.
// They recursively call the base case to handle single pixels.
var dispPos = [inDisplayPosition[0], inDisplayPosition[1]];
var curPos = [0, 0];
var info = publicAPI.getPixelInformation(inDisplayPosition, 0, outSelectedPosition);
if (info && info.valid) {
return info;
}
for (var dist = 1; dist < maxDist; ++dist) {
// Vertical sides of box.
for (var y = dispPos[1] > dist ? dispPos[1] - dist : 0; y <= dispPos[1] + dist; ++y) {
curPos[1] = y;
if (dispPos[0] >= dist) {
curPos[0] = dispPos[0] - dist;
info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
if (info && info.valid) {
return info;
}
}
curPos[0] = dispPos[0] + dist;
info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
if (info && info.valid) {
return info;
}
}
// Horizontal sides of box.
for (var x = dispPos[0] >= dist ? dispPos[0] - (dist - 1) : 0; x <= dispPos[0] + (dist - 1); ++x) {
curPos[0] = x;
if (dispPos[1] >= dist) {
curPos[1] = dispPos[1] - dist;
info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
if (info && info.valid) {
return info;
}
}
curPos[1] = dispPos[1] + dist;
info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
if (info && info.valid) {
return info;
}
}
}
// nothing hit.
outSelectedPosition[0] = inDisplayPosition[0];
outSelectedPosition[1] = inDisplayPosition[1];
return null;
};
//-----------------------------------------------------------------------------
publicAPI.convertSelection = function (fieldassociation, dataMap) {
var sel = [];
var count = 0;
dataMap.forEach(function (value, key) {
var child = _SelectionNode2.default.newInstance();
child.setContentType(SelectionContent.INDICES);
switch (fieldassociation) {
case FieldAssociations.FIELD_ASSOCIATION_CELLS:
child.setFieldType(SelectionField.CELL);
break;
case FieldAssociations.FIELD_ASSOCIATION_POINTS:
child.setFieldType(SelectionField.POINT);
break;
default:
vtkErrorMacro('Unknown field association');
}
child.getProperties().propID = value.info.propID;
child.getProperties().prop = value.info.prop;
child.getProperties().compositeID = value.info.compositeID;
child.getProperties().pixelCount = value.pixelCount;
child.setSelectionList(value.attributeIDs);
sel[count] = child;
count++;
});
return sel;
};
publicAPI.getInfoHash = function (info) {
return info.propID + ' ' + info.compositeID;
};
//----------------------------------------------------------------------------
publicAPI.generateSelection = function (x1, y1, x2, y2) {
var dataMap = new Map();
var outSelectedPosition = [0, 0];
for (var yy = y1; yy <= y2; yy++) {
for (var xx = x1; xx <= x2; xx++) {
var pos = [xx, yy];
var info = publicAPI.getPixelInformation(pos, 0, outSelectedPosition);
if (info && info.valid) {
var hash = publicAPI.getInfoHash(info);
if (!dataMap.has(hash)) {
dataMap.set(hash, {
info: info,
pixelCount: 1,
attributeIDs: [info.attributeID]
});
} else {
dataMap.get(hash).pixelCount++;
if (dataMap.get(hash).attributeIDs.indexOf(info.attributeID) === -1) {
dataMap.get(hash).attributeIDs.push(info.attributeID);
}
}
}
}
}
return publicAPI.convertSelection(model.fieldAssociation, dataMap);
};
publicAPI.attach = function (w, r) {
model.openGLRenderWindow = w;
model.renderer = r;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
fieldAssociation: FieldAssociations.FIELD_ASSOCIATION_CELLS,
renderer: null,
area: null,
openGLRenderWindow: null,
openGLRenderer: null,
currentPass: -1,
propColorValue: null,
props: null,
idOffset: 1
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
_macro2.default.obj(publicAPI, model);
model.area = [0, 0, 0, 0];
model.propColorValue = [0, 0, 0];
model.props = [];
_macro2.default.setGet(publicAPI, model, ['fieldAssociation', 'renderer', 'currentPass']);
_macro2.default.setGetArray(publicAPI, model, ['area'], 4);
_macro2.default.setGetArray(publicAPI, model, ['propColorValue'], 3);
_macro2.default.event(publicAPI, model, 'event');
// Object methods
vtkOpenGLHardwareSelector(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkOpenGLHardwareSelector');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend }, _Constants2.default);
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var AttributeTypes = exports.AttributeTypes = {
SCALARS: 0,
VECTORS: 1,
NORMALS: 2,
TCOORDS: 3,
TENSORS: 4,
GLOBALIDS: 5,
PEDIGREEIDS: 6,
EDGEFLAG: 7,
NUM_ATTRIBUTES: 8
};
var AttributeLimitTypes = exports.AttributeLimitTypes = {
MAX: 0,
EXACT: 1,
NOLIMIT: 2
};
var CellGhostTypes = exports.CellGhostTypes = {
DUPLICATECELL: 1, // the cell is present on multiple processors
HIGHCONNECTIVITYCELL: 2, // the cell has more neighbors than in a regular mesh
LOWCONNECTIVITYCELL: 4, // the cell has less neighbors than in a regular mesh
REFINEDCELL: 8, // other cells are present that refines it.
EXTERIORCELL: 16, // the cell is on the exterior of the data set
HIDDENCELL: 32 // the cell is needed to maintain connectivity, but the data values should be ignored.
};
var PointGhostTypes = exports.PointGhostTypes = {
DUPLICATEPOINT: 1, // the cell is present on multiple processors
HIDDENPOINT: 2 // the point is needed to maintain connectivity, but the data values should be ignored.
};
var AttributeCopyOperations = exports.AttributeCopyOperations = {
COPYTUPLE: 0,
INTERPOLATE: 1,
PASSDATA: 2,
ALLCOPY: 3 // all of the above
};
var ghostArrayName = exports.ghostArrayName = 'vtkGhostType';
var DesiredOutputPrecision = exports.DesiredOutputPrecision = {
DEFAULT: 0, // use the point type that does not truncate any data
SINGLE: 1, // use Float32Array
DOUBLE: 2 // use Float64Array
};
exports.default = {
AttributeCopyOperations: AttributeCopyOperations,
AttributeLimitTypes: AttributeLimitTypes,
AttributeTypes: AttributeTypes,
CellGhostTypes: CellGhostTypes,
DesiredOutputPrecision: DesiredOutputPrecision,
PointGhostTypes: PointGhostTypes,
ghostArrayName: ghostArrayName
};
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Constants = __webpack_require__(88);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// ----------------------------------------------------------------------------
// vtkOpenGLVertexArrayObject methods
// ----------------------------------------------------------------------------
function vtkOpenGLVertexArrayObject(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLVertexArrayObject');
// Public API methods
publicAPI.exposedMethod = function () {
// This is a publicly exposed method of this object
};
publicAPI.initialize = function () {
model.instancingExtension = null;
if (!model.openGLRenderWindow.getWebgl2()) {
model.instancingExtension = model.context.getExtension('ANGLE_instanced_arrays');
}
if (!model.forceEmulation && model.openGLRenderWindow && model.openGLRenderWindow.getWebgl2()) {
model.extension = null;
model.supported = true;
model.handleVAO = model.context.createVertexArray();
} else {
model.extension = model.context.getExtension('OES_vertex_array_object');
// Start setting up VAO
if (!model.forceEmulation && model.extension) {
model.supported = true;
model.handleVAO = model.extension.createVertexArrayOES();
} else {
model.supported = false;
}
}
};
publicAPI.isReady = function () {
return (
// We either probed and allocated a VAO, or are falling back as the current
// hardware does not support VAOs.
model.handleVAO !== 0 || model.supported === false
);
};
publicAPI.bind = function () {
// Either simply bind the VAO, or emulate behavior by binding all attributes.
if (!publicAPI.isReady()) {
publicAPI.initialize();
}
if (publicAPI.isReady() && model.supported) {
if (model.extension) {
model.extension.bindVertexArrayOES(model.handleVAO);
} else {
model.context.bindVertexArray(model.handleVAO);
}
} else if (publicAPI.isReady()) {
var gl = model.context;
for (var ibuff = 0; ibuff < model.buffers.length; ++ibuff) {
var buff = model.buffers[ibuff];
model.context.bindBuffer(gl.ARRAY_BUFFER, buff.buffer);
for (var iatt = 0; iatt < buff.attributes.length; ++iatt) {
var attrIt = buff.attributes[iatt];
var matrixCount = attrIt.isMatrix ? attrIt.size : 1;
for (var i = 0; i < matrixCount; ++i) {
gl.enableVertexAttribArray(attrIt.index + i);
gl.vertexAttribPointer(attrIt.index + i, attrIt.size, attrIt.type, attrIt.normalize, attrIt.stride, attrIt.offset + attrIt.stride * i / attrIt.size);
if (attrIt.divisor > 0) {
if (model.instancingExtension) {
model.instancingExtension.vertexAttribDivisorANGLE(attrIt.index + i, 1);
} else {
gl.vertexAttribDivisor(attrIt.index + i, 1);
}
}
}
}
}
}
};
publicAPI.release = function () {
// Either simply release the VAO, or emulate behavior by releasing all attributes.
if (publicAPI.isReady() && model.supported) {
if (model.extension) {
model.extension.bindVertexArrayOES(null);
} else {
model.context.bindVertexArray(null);
}
} else if (publicAPI.isReady()) {
var gl = model.context;
for (var ibuff = 0; ibuff < model.buffers.length; ++ibuff) {
var buff = model.buffers[ibuff];
model.context.bindBuffer(gl.ARRAY_BUFFER, buff.buffer);
for (var iatt = 0; iatt < buff.attributes.length; ++iatt) {
var attrIt = buff.attributes[iatt];
var matrixCount = attrIt.isMatrix ? attrIt.size : 1;
for (var i = 0; i < matrixCount; ++i) {
gl.enableVertexAttribArray(attrIt.index + i);
gl.vertexAttribPointer(attrIt.index + i, attrIt.size, attrIt.type, attrIt.normalize, attrIt.stride, attrIt.offset + attrIt.stride * i / attrIt.size);
if (attrIt.divisor > 0) {
if (model.instancingExtension) {
model.instancingExtension.vertexAttribDivisorANGLE(attrIt.index + i, 0);
} else {
gl.vertexAttribDivisor(attrIt.index + i, 0);
}
}
gl.disableVertexAttribArray(attrIt.index + i);
}
}
}
}
};
publicAPI.shaderProgramChanged = function () {
publicAPI.release();
if (model.handleVAO) {
if (model.extension) {
model.extension.deleteVertexArrayOES(model.handleVAO);
} else {
model.context.deleteVertexArray(model.handleVAO);
}
}
model.handleVAO = 0;
model.handleProgram = 0;
};
publicAPI.releaseGraphicsResources = function () {
publicAPI.shaderProgramChanged();
if (model.handleVAO) {
if (model.extension) {
model.extension.deleteVertexArrayOES(model.handleVAO);
} else {
model.context.deleteVertexArray(model.handleVAO);
}
}
model.handleVAO = 0;
model.supported = true;
model.handleProgram = 0;
};
publicAPI.addAttributeArray = function (program, buffer, name, offset, stride, elementType, elementTupleSize, normalize) {
return publicAPI.addAttributeArrayWithDivisor(program, buffer, name, offset, stride, elementType, elementTupleSize, normalize, 0, false);
};
publicAPI.addAttributeArrayWithDivisor = function (program, buffer, name, offset, stride, elementType, elementTupleSize, normalize, divisor, isMatrix) {
if (!program) {
return false;
}
// Check the program is bound, and the buffer is valid.
if (!program.isBound() || buffer.getHandle() === 0 || buffer.getType() !== _Constants.ObjectType.ARRAY_BUFFER) {
return false;
}
// Perform initalization if necessary, ensure program matches VAOs.
if (model.handleProgram === 0) {
model.handleProgram = program.getHandle();
}
if (!publicAPI.isReady()) {
publicAPI.initialize();
}
if (!publicAPI.isReady() || model.handleProgram !== program.getHandle()) {
return false;
}
var gl = model.context;
var attribs = {};
attribs.name = name;
attribs.index = gl.getAttribLocation(model.handleProgram, name);
attribs.offset = offset;
attribs.stride = stride;
attribs.type = elementType;
attribs.size = elementTupleSize;
attribs.normalize = normalize;
attribs.isMatrix = isMatrix;
attribs.divisor = divisor;
if (attribs.Index === -1) {
return false;
}
// Always make the call as even the first use wants the attrib pointer setting
// up when we are emulating.
buffer.bind();
gl.enableVertexAttribArray(attribs.index);
gl.vertexAttribPointer(attribs.index, attribs.size, attribs.type, attribs.normalize, attribs.stride, attribs.offset);
if (divisor > 0) {
if (model.instancingExtension) {
model.instancingExtension.vertexAttribDivisorANGLE(attribs.index, 1);
} else {
gl.vertexAttribDivisor(attribs.index, 1);
}
}
attribs.buffer = buffer.getHandle();
// If vertex array objects are not supported then build up our list.
if (!model.supported) {
// find the buffer
var buffFound = false;
for (var ibuff = 0; ibuff < model.buffers.length; ++ibuff) {
var buff = model.buffers[ibuff];
if (buff.buffer === attribs.buffer) {
buffFound = true;
var found = false;
for (var iatt = 0; iatt < buff.attributes.length; ++iatt) {
var attrIt = buff.attributes[iatt];
if (attrIt.name === name) {
found = true;
buff.attributes[iatt] = attribs;
}
}
if (!found) {
buff.attributes.push(attribs);
}
}
}
if (!buffFound) {
model.buffers.push({ buffer: attribs.buffer, attributes: [attribs] });
}
}
return true;
};
publicAPI.addAttributeMatrixWithDivisor = function (program, buffer, name, offset, stride, elementType, elementTupleSize, normalize, divisor) {
// bind the first row of values
var result = publicAPI.addAttributeArrayWithDivisor(program, buffer, name, offset, stride, elementType, elementTupleSize, normalize, divisor, true);
if (!result) {
return result;
}
var gl = model.context;
var index = gl.getAttribLocation(model.handleProgram, name);
for (var i = 1; i < elementTupleSize; i++) {
gl.enableVertexAttribArray(index + i);
gl.vertexAttribPointer(index + i, elementTupleSize, elementType, normalize, stride, offset + stride * i / elementTupleSize);
if (divisor > 0) {
if (model.instancingExtension) {
model.instancingExtension.vertexAttribDivisorANGLE(index + i, 1);
} else {
gl.vertexAttribDivisor(index + i, 1);
}
}
}
return true;
};
publicAPI.removeAttributeArray = function (name) {
if (!publicAPI.isReady() || model.handleProgram === 0) {
return false;
}
// If we don't have real VAOs find the entry and remove it too.
if (!model.supported) {
for (var ibuff = 0; ibuff < model.buffers.length; ++ibuff) {
var buff = model.buffers[ibuff];
for (var iatt = 0; iatt < buff.attributes.length; ++iatt) {
var attrIt = buff.attributes[iatt];
if (attrIt.name === name) {
buff.attributes.splice(iatt, 1);
if (!buff.attributes.length) {
model.buffers.splice(ibuff, 1);
}
return true;
}
}
}
}
return true;
};
publicAPI.setOpenGLRenderWindow = function (rw) {
if (model.openGLRenderWindow === rw) {
return;
}
publicAPI.releaseGraphicsResources();
model.openGLRenderWindow = rw;
model.context = null;
if (rw) {
model.context = model.openGLRenderWindow.getContext();
}
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
forceEmulation: false,
handleVAO: 0,
handleProgram: 0,
supported: true,
buffers: null,
context: null,
openGLRenderWindow: null
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Internal objects initialization
model.buffers = [];
// Object methods
_macro2.default.obj(publicAPI, model);
// Create get-only macros
_macro2.default.get(publicAPI, model, ['supported']);
// Create get-set macros
_macro2.default.setGet(publicAPI, model, ['forceEmulation']);
// For more macro methods, see "Sources/macro.js"
// Object specific methods
vtkOpenGLVertexArrayObject(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkOpenGLVertexArrayObject');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var StructuredType = exports.StructuredType = {
UNCHANGED: 0,
SINGLE_POINT: 1,
X_LINE: 2,
Y_LINE: 3,
Z_LINE: 4,
XY_PLANE: 5,
YZ_PLANE: 6,
XZ_PLANE: 7,
XYZ_GRID: 8,
EMPTY: 9
};
exports.default = {
StructuredType: StructuredType
};
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ColorMode = exports.ColorMode = {
DEFAULT: 0,
MAP_SCALARS: 1,
DIRECT_SCALARS: 2
};
var ScalarMode = exports.ScalarMode = {
DEFAULT: 0,
USE_POINT_DATA: 1,
USE_CELL_DATA: 2,
USE_POINT_FIELD_DATA: 3,
USE_CELL_FIELD_DATA: 4,
USE_FIELD_DATA: 5
};
var GetArray = exports.GetArray = {
BY_ID: 0,
BY_NAME: 1
};
exports.default = {
ColorMode: ColorMode,
GetArray: GetArray,
ScalarMode: ScalarMode
};
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = "//VTK::System::Dec\n\n/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPolyDataVS.glsl\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*/\n\nattribute vec4 vertexMC;\n\n// frag position in VC\n//VTK::PositionVC::Dec\n\n// optional normal declaration\n//VTK::Normal::Dec\n\n// extra lighting parameters\n//VTK::Light::Dec\n\n// Texture coordinates\n//VTK::TCoord::Dec\n\n// material property values\n//VTK::Color::Dec\n\n// clipping plane vars\n//VTK::Clip::Dec\n\n// camera and actor matrix values\n//VTK::Camera::Dec\n\n// Apple Bug\n//VTK::PrimID::Dec\n\n// picking support\n//VTK::Picking::Dec\n\nvoid main()\n{\n //VTK::Color::Impl\n\n //VTK::Normal::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::Clip::Impl\n\n //VTK::PrimID::Impl\n\n //VTK::PositionVC::Impl\n\n //VTK::Light::Impl\n\n //VTK::Picking::Impl\n}\n";
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _glMatrix = __webpack_require__(13);
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Camera = __webpack_require__(594);
var _Camera2 = _interopRequireDefault(_Camera);
var _Light = __webpack_require__(595);
var _Light2 = _interopRequireDefault(_Light);
var _Math = __webpack_require__(10);
var _Math2 = _interopRequireDefault(_Math);
var _Viewport = __webpack_require__(596);
var _Viewport2 = _interopRequireDefault(_Viewport);
var _BoundingBox = __webpack_require__(167);
var _BoundingBox2 = _interopRequireDefault(_BoundingBox);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var vtkDebugMacro = _macro2.default.vtkDebugMacro,
vtkErrorMacro = _macro2.default.vtkErrorMacro,
vtkWarningMacro = _macro2.default.vtkWarningMacro;
function notImplemented(method) {
return function () {
return vtkErrorMacro('vtkRenderer::' + method + ' - NOT IMPLEMENTED');
};
}
// ----------------------------------------------------------------------------
// vtkRenderer methods
// ----------------------------------------------------------------------------
function vtkRenderer(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkRenderer');
// make sure background has 4 entries. Default to opaque black
if (!model.background) model.background = [0, 0, 0, 1];
while (model.background.length < 3) {
model.background.push(0);
}if (model.background.length === 3) model.background.push(1);
// Events
var COMPUTE_VISIBLE_PROP_BOUNDS_EVENT = {
type: 'ComputeVisiblePropBoundsEvent',
renderer: publicAPI
};
var RESET_CAMERA_CLIPPING_RANGE_EVENT = {
type: 'ResetCameraClippingRangeEvent',
renderer: publicAPI
};
var RESET_CAMERA_EVENT = {
type: 'ResetCameraEvent',
renderer: publicAPI
};
publicAPI.updateCamera = function () {
if (!model.activeCamera) {
vtkDebugMacro('No cameras are on, creating one.');
// the get method will automagically create a camera
// and reset it since one hasn't been specified yet.
publicAPI.getActiveCameraAndResetIfCreated();
}
// update the viewing transformation
model.activeCamera.render(publicAPI);
return true;
};
publicAPI.updateLightsGeometryToFollowCamera = function () {
// only update the light's geometry if this Renderer is tracking
// this lights. That allows one renderer to view the lights that
// another renderer is setting up.
var camera = publicAPI.getActiveCameraAndResetIfCreated();
model.lights.forEach(function (light) {
if (light.lightTypeIsSceneLight()) {
// Do nothing. Don't reset the transform matrix because applications
// may have set a custom matrix. Only reset the transform matrix in
// vtkLight::SetLightTypeToSceneLight()
} else if (light.lightTypeIsHeadLight()) {
// update position and orientation of light to match camera.
light.setPositionFrom(camera.getPositionByReference());
light.setFocalPointFrom(camera.getFocalPointByReference());
light.modified(camera.getMTime());
} else if (light.lightTypeIsCameraLight()) {
vtkErrorMacro('camera lights not supported yet', light.get());
} else {
vtkErrorMacro('light has unknown light type', light.get());
}
});
};
publicAPI.updateLightGeometry = function () {
if (model.lightFollowCamera) {
// only update the light's geometry if this Renderer is tracking
// this lights. That allows one renderer to view the lights that
// another renderer is setting up.
return publicAPI.updateLightsGeometryToFollowCamera();
}
return true;
};
publicAPI.allocateTime = notImplemented('allocateTime');
publicAPI.updateGeometry = notImplemented('updateGeometry');
publicAPI.getVTKWindow = function () {
return model.renderWindow;
};
publicAPI.setLayer = function (layer) {
vtkDebugMacro(publicAPI.getClassName(), publicAPI, 'setting Layer to ', layer);
if (model.layer !== layer) {
model.layer = layer;
publicAPI.modified();
}
publicAPI.setPreserveColorBuffer(!!layer);
};
publicAPI.setActiveCamera = function (camera) {
if (model.activeCamera === camera) {
return false;
}
model.activeCamera = camera;
publicAPI.modified();
publicAPI.invokeEvent({ type: 'ActiveCameraEvent', camera: camera });
return true;
};
publicAPI.makeCamera = function () {
var camera = _Camera2.default.newInstance();
publicAPI.invokeEvent({ type: 'CreateCameraEvent', camera: camera });
return camera;
};
// Replace the set/get macro method
publicAPI.getActiveCamera = function () {
if (!model.activeCamera) {
model.activeCamera = publicAPI.makeCamera();
}
return model.activeCamera;
};
publicAPI.getActiveCameraAndResetIfCreated = function () {
if (!model.activeCamera) {
publicAPI.getActiveCamera();
publicAPI.resetCamera();
}
return model.activeCamera;
};
publicAPI.addActor = publicAPI.addViewProp;
publicAPI.addVolume = publicAPI.addViewProp;
publicAPI.removeActor = function (actor) {
model.actors = model.actors.filter(function (a) {
return a !== actor;
});
publicAPI.removeViewProp(actor);
};
publicAPI.removeVolume = function (volume) {
model.volumes = model.volumes.filter(function (v) {
return v !== volume;
});
publicAPI.removeViewProp(volume);
};
publicAPI.addLight = function (light) {
model.lights = [].concat(model.lights, light);
publicAPI.modified();
};
publicAPI.getActors = function () {
model.actors = [];
model.props.forEach(function (prop) {
model.actors = model.actors.concat(prop.getActors());
});
return model.actors;
};
publicAPI.getVolumes = function () {
model.volumes = [];
model.props.forEach(function (prop) {
model.volumes = model.volumes.concat(prop.getVolumes());
});
return model.volumes;
};
publicAPI.removeLight = function (light) {
model.lights = model.lights.filter(function (l) {
return l !== light;
});
publicAPI.modified();
};
publicAPI.removeAllLights = function () {
model.lights = [];
};
publicAPI.setLightCollection = function (lights) {
model.lights = lights;
publicAPI.modified();
};
publicAPI.makeLight = _Light2.default.newInstance;
publicAPI.createLight = function () {
if (!model.automaticLightCreation) {
return;
}
if (model.createdLight) {
publicAPI.removeLight(model.createdLight);
model.createdLight.delete();
model.createdLight = null;
}
model.createdLight = publicAPI.makeLight();
publicAPI.addLight(model.createdLight);
model.createdLight.setLightTypeToHeadLight();
// set these values just to have a good default should LightFollowCamera
// be turned off.
model.createdLight.setPosition(publicAPI.getActiveCamera().getPosition());
model.createdLight.setFocalPoint(publicAPI.getActiveCamera().getFocalPoint());
};
// requires the aspect ratio of the viewport as X/Y
publicAPI.normalizedDisplayToWorld = function (x, y, z, aspect) {
var vpd = publicAPI.normalizedDisplayToView(x, y, z);
return publicAPI.viewToWorld(vpd[0], vpd[1], vpd[2], aspect);
};
// requires the aspect ratio of the viewport as X/Y
publicAPI.worldToNormalizedDisplay = function (x, y, z, aspect) {
var vpd = publicAPI.worldToView(x, y, z);
return publicAPI.viewToNormalizedDisplay(vpd[0], vpd[1], vpd[2], aspect);
};
// requires the aspect ratio of the viewport as X/Y
publicAPI.viewToWorld = function (x, y, z, aspect) {
if (model.activeCamera === null) {
vtkErrorMacro('ViewToWorld: no active camera, cannot compute view to world, returning 0,0,0');
return [0, 0, 0];
}
// get the perspective transformation from the active camera
var matrix = model.activeCamera.getCompositeProjectionMatrix(aspect, -1.0, 1.0);
_glMatrix.mat4.invert(matrix, matrix);
_glMatrix.mat4.transpose(matrix, matrix);
// Transform point to world coordinates
var result = _glMatrix.vec3.fromValues(x, y, z);
_glMatrix.vec3.transformMat4(result, result, matrix);
return [result[0], result[1], result[2]];
};
// Convert world point coordinates to view coordinates.
// requires the aspect ratio of the viewport as X/Y
publicAPI.worldToView = function (x, y, z, aspect) {
if (model.activeCamera === null) {
vtkErrorMacro('ViewToWorld: no active camera, cannot compute view to world, returning 0,0,0');
return [0, 0, 0];
}
// get the perspective transformation from the active camera
var matrix = model.activeCamera.getCompositeProjectionMatrix(aspect, -1.0, 1.0);
_glMatrix.mat4.transpose(matrix, matrix);
var result = _glMatrix.vec3.fromValues(x, y, z);
_glMatrix.vec3.transformMat4(result, result, matrix);
return [result[0], result[1], result[2]];
};
publicAPI.computeVisiblePropBounds = function () {
model.allBounds[0] = _BoundingBox2.default.INIT_BOUNDS[0];
model.allBounds[1] = _BoundingBox2.default.INIT_BOUNDS[1];
model.allBounds[2] = _BoundingBox2.default.INIT_BOUNDS[2];
model.allBounds[3] = _BoundingBox2.default.INIT_BOUNDS[3];
model.allBounds[4] = _BoundingBox2.default.INIT_BOUNDS[4];
model.allBounds[5] = _BoundingBox2.default.INIT_BOUNDS[5];
var nothingVisible = true;
publicAPI.invokeEvent(COMPUTE_VISIBLE_PROP_BOUNDS_EVENT);
// loop through all props
for (var index = 0; index < model.props.length; ++index) {
var prop = model.props[index];
if (prop.getVisibility() && prop.getUseBounds()) {
var bounds = prop.getBounds();
if (bounds && _Math2.default.areBoundsInitialized(bounds)) {
nothingVisible = false;
if (bounds[0] < model.allBounds[0]) {
model.allBounds[0] = bounds[0];
}
if (bounds[1] > model.allBounds[1]) {
model.allBounds[1] = bounds[1];
}
if (bounds[2] < model.allBounds[2]) {
model.allBounds[2] = bounds[2];
}
if (bounds[3] > model.allBounds[3]) {
model.allBounds[3] = bounds[3];
}
if (bounds[4] < model.allBounds[4]) {
model.allBounds[4] = bounds[4];
}
if (bounds[5] > model.allBounds[5]) {
model.allBounds[5] = bounds[5];
}
}
}
}
if (nothingVisible) {
_Math2.default.uninitializeBounds(model.allBounds);
vtkDebugMacro("Can't compute bounds, no 3D props are visible");
}
return model.allBounds;
};
publicAPI.resetCamera = function () {
var bounds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var boundsToUse = bounds || publicAPI.computeVisiblePropBounds();
var center = [0, 0, 0];
if (!_Math2.default.areBoundsInitialized(boundsToUse)) {
vtkDebugMacro('Cannot reset camera!');
return false;
}
var vn = null;
if (publicAPI.getActiveCamera()) {
vn = model.activeCamera.getViewPlaneNormal();
} else {
vtkErrorMacro('Trying to reset non-existant camera');
return false;
}
// Reset the perspective zoom factors, otherwise subsequent zooms will cause
// the view angle to become very small and cause bad depth sorting.
model.activeCamera.setViewAngle(30.0);
center[0] = (boundsToUse[0] + boundsToUse[1]) / 2.0;
center[1] = (boundsToUse[2] + boundsToUse[3]) / 2.0;
center[2] = (boundsToUse[4] + boundsToUse[5]) / 2.0;
var w1 = boundsToUse[1] - boundsToUse[0];
var w2 = boundsToUse[3] - boundsToUse[2];
var w3 = boundsToUse[5] - boundsToUse[4];
w1 *= w1;
w2 *= w2;
w3 *= w3;
var radius = w1 + w2 + w3;
// If we have just a single point, pick a radius of 1.0
radius = radius === 0 ? 1.0 : radius;
// compute the radius of the enclosing sphere
radius = Math.sqrt(radius) * 0.5;
// default so that the bounding sphere fits within the view fustrum
// compute the distance from the intersection of the view frustum with the
// bounding sphere. Basically in 2D draw a circle representing the bounding
// sphere in 2D then draw a horizontal line going out from the center of
// the circle. That is the camera view. Then draw a line from the camera
// position to the point where it intersects the circle. (it will be tangent
// to the circle at this point, this is important, only go to the tangent
// point, do not draw all the way to the view plane). Then draw the radius
// from the tangent point to the center of the circle. You will note that
// this forms a right triangle with one side being the radius, another being
// the target distance for the camera, then just find the target dist using
// a sin.
var angle = _Math2.default.radiansFromDegrees(model.activeCamera.getViewAngle());
var parallelScale = radius;
var distance = radius / Math.sin(angle * 0.5);
// check view-up vector against view plane normal
var vup = model.activeCamera.getViewUp();
if (Math.abs(_Math2.default.dot(vup, vn)) > 0.999) {
vtkWarningMacro('Resetting view-up since view plane normal is parallel');
model.activeCamera.setViewUp(-vup[2], vup[0], vup[1]);
}
// update the camera
model.activeCamera.setFocalPoint(center[0], center[1], center[2]);
model.activeCamera.setPosition(center[0] + distance * vn[0], center[1] + distance * vn[1], center[2] + distance * vn[2]);
publicAPI.resetCameraClippingRange(boundsToUse);
// setup default parallel scale
model.activeCamera.setParallelScale(parallelScale);
// update reasonable world to physical values
model.activeCamera.setPhysicalScale(1.0 / radius);
model.activeCamera.setPhysicalTranslation(-center[0], -center[1], -center[2]);
// Here to let parallel/distributed compositing intercept
// and do the right thing.
publicAPI.invokeEvent(RESET_CAMERA_EVENT);
return true;
};
publicAPI.resetCameraClippingRange = function () {
var bounds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var boundsToUse = bounds || publicAPI.computeVisiblePropBounds();
if (!_Math2.default.areBoundsInitialized(boundsToUse)) {
vtkDebugMacro('Cannot reset camera clipping range!');
return false;
}
// Make sure we have an active camera
publicAPI.getActiveCameraAndResetIfCreated();
if (!model.activeCamera) {
vtkErrorMacro('Trying to reset clipping range of non-existant camera');
return false;
}
// Get the exact range for the bounds
var range = model.activeCamera.computeClippingRange(boundsToUse);
// do not let far - near be less than 0.1 of the window height
// this is for cases such as 2D images which may have zero range
var minGap = 0.0;
if (model.activeCamera.getParallelProjection()) {
minGap = 0.1 * model.activeCamera.getParallelScale();
} else {
var angle = _Math2.default.radiansFromDegrees(model.activeCamera.getViewAngle());
minGap = 0.2 * Math.tan(angle / 2.0) * range[1];
}
if (range[1] - range[0] < minGap) {
minGap = minGap - range[1] + range[0];
range[1] += minGap / 2.0;
range[0] -= minGap / 2.0;
}
// Do not let the range behind the camera throw off the calculation.
if (range[0] < 0.0) {
range[0] = 0.0;
}
// Give ourselves a little breathing room
range[0] = 0.99 * range[0] - (range[1] - range[0]) * model.clippingRangeExpansion;
range[1] = 1.01 * range[1] + (range[1] - range[0]) * model.clippingRangeExpansion;
// Make sure near is not bigger than far
range[0] = range[0] >= range[1] ? 0.01 * range[1] : range[0];
// Make sure near is at least some fraction of far - this prevents near
// from being behind the camera or too close in front. How close is too
// close depends on the resolution of the depth buffer
if (!model.nearClippingPlaneTolerance) {
model.nearClippingPlaneTolerance = 0.01;
}
// make sure the front clipping range is not too far from the far clippnig
// range, this is to make sure that the zbuffer resolution is effectively
// used
if (range[0] < model.nearClippingPlaneTolerance * range[1]) {
range[0] = model.nearClippingPlaneTolerance * range[1];
}
model.activeCamera.setClippingRange(range[0], range[1]);
// Here to let parallel/distributed compositing intercept
// and do the right thing.
publicAPI.invokeEvent(RESET_CAMERA_CLIPPING_RANGE_EVENT);
return false;
};
publicAPI.setRenderWindow = function (renderWindow) {
if (renderWindow !== model.renderWindow) {
model.vtkWindow = renderWindow;
model.renderWindow = renderWindow;
}
};
publicAPI.visibleActorCount = function () {
return model.props.filter(function (prop) {
return prop.getVisibility();
}).length;
};
publicAPI.visibleVolumeCount = publicAPI.visibleActorCount;
publicAPI.getMTime = function () {
var m1 = model.mtime;
var m2 = model.activeCamera ? model.activeCamera.getMTime() : 0;
if (m2 > m1) {
m1 = m2;
}
var m3 = model.createdLight ? model.createdLight.getMTime() : 0;
if (m3 > m1) {
m1 = m3;
}
return m1;
};
publicAPI.getTransparent = function () {
return !!model.preserveColorBuffer;
};
publicAPI.isActiveCameraCreated = function () {
return !!model.activeCamera;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
pickedProp: null,
activeCamera: null,
allBounds: [],
ambient: [1, 1, 1],
allocatedRenderTime: 100,
timeFactor: 1,
createdLight: null,
automaticLightCreation: true,
twoSidedLighting: true,
lastRenderTimeInSeconds: -1,
renderWindow: null,
lights: [],
actors: [],
volumes: [],
lightFollowCamera: true,
numberOfPropsRendered: 0,
propArray: null,
pathArray: null,
layer: 1,
preserveColorBuffer: false,
preserveDepthBuffer: false,
computeVisiblePropBounds: _Math2.default.createUninitializedBounds(),
interactive: true,
nearClippingPlaneTolerance: 0,
clippingRangeExpansion: 0.05,
erase: true,
draw: true,
useShadows: false,
useDepthPeeling: false,
occlusionRatio: 0,
maximumNumberOfPeels: 4,
selector: null,
delegate: null,
texturedBackground: false,
backgroundTexture: null,
pass: 0
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
_Viewport2.default.extend(publicAPI, model, initialValues);
// Build VTK API
_macro2.default.get(publicAPI, model, ['renderWindow', 'allocatedRenderTime', 'timeFactor', 'lastRenderTimeInSeconds', 'numberOfPropsRendered', 'lastRenderingUsedDepthPeeling', 'selector']);
_macro2.default.setGet(publicAPI, model, ['twoSidedLighting', 'lightFollowCamera', 'automaticLightCreation', 'erase', 'draw', 'nearClippingPlaneTolerance', 'clippingRangeExpansion', 'backingStore', 'interactive', 'layer', 'preserveColorBuffer', 'preserveDepthBuffer', 'useDepthPeeling', 'occlusionRatio', 'maximumNumberOfPeels', 'delegate', 'backgroundTexture', 'texturedBackground', 'useShadows', 'pass']);
_macro2.default.getArray(publicAPI, model, ['actors', 'volumes', 'lights']);
_macro2.default.setGetArray(publicAPI, model, ['background'], 4, 1.0);
// Object methods
vtkRenderer(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkRenderer');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _Math = __webpack_require__(10);
var _Math2 = _interopRequireDefault(_Math);
var _InteractorStyleTrackballCamera = __webpack_require__(598);
var _InteractorStyleTrackballCamera2 = _interopRequireDefault(_InteractorStyleTrackballCamera);
var _Constants = __webpack_require__(283);
var _Constants2 = _interopRequireDefault(_Constants);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Device = _Constants2.default.Device,
Input = _Constants2.default.Input;
var vtkWarningMacro = _macro2.default.vtkWarningMacro,
vtkErrorMacro = _macro2.default.vtkErrorMacro,
normalizeWheel = _macro2.default.normalizeWheel,
vtkOnceErrorMacro = _macro2.default.vtkOnceErrorMacro;
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
var deviceInputMap = {
'OpenVR Gamepad': [Input.TrackPad, Input.Trigger, Input.Grip, Input.ApplicationMenu]
};
var handledEvents = ['StartAnimation', 'Animation', 'EndAnimation', 'StartMouseMove', 'MouseMove', 'EndMouseMove', 'LeftButtonPress', 'LeftButtonRelease', 'MiddleButtonPress', 'MiddleButtonRelease', 'RightButtonPress', 'RightButtonRelease', 'KeyPress', 'KeyDown', 'KeyUp', 'StartMouseWheel', 'MouseWheel', 'EndMouseWheel', 'StartPinch', 'Pinch', 'EndPinch', 'StartPan', 'Pan', 'EndPan', 'StartRotate', 'Rotate', 'EndRotate', 'Button3D', 'Move3D'];
function preventDefault(event) {
event.stopPropagation();
event.preventDefault();
return false;
}
// ----------------------------------------------------------------------------
// vtkRenderWindowInteractor methods
// ----------------------------------------------------------------------------
function vtkRenderWindowInteractor(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkRenderWindowInteractor');
// Initialize list of requesters
var animationRequesters = new Set();
// Public API methods
//----------------------------------------------------------------------
publicAPI.start = function () {
// Let the compositing handle the event loop if it wants to.
// if (publicAPI.HasObserver(vtkCommand::StartEvent) && !publicAPI.HandleEventLoop) {
// publicAPI.invokeEvent({ type: 'StartEvent' });
// return;
// }
// As a convenience, initialize if we aren't initialized yet.
if (!model.initialized) {
publicAPI.initialize();
if (!model.initialized) {
return;
}
}
// Pass execution to the subclass which will run the event loop,
// this will not return until TerminateApp is called.
publicAPI.startEventLoop();
};
//----------------------------------------------------------------------
publicAPI.setRenderWindow = function (aren) {
vtkErrorMacro('you want to call setView(view) instead of setRenderWindow on a vtk.js interactor');
};
//----------------------------------------------------------------------
publicAPI.setInteractorStyle = function (style) {
if (model.interactorStyle !== style) {
if (model.interactorStyle != null) {
model.interactorStyle.setInteractor(null);
}
model.interactorStyle = style;
if (model.interactorStyle != null) {
if (model.interactorStyle.getInteractor() !== publicAPI) {
model.interactorStyle.setInteractor(publicAPI);
}
}
}
};
//---------------------------------------------------------------------
publicAPI.initialize = function () {
model.initialized = true;
publicAPI.enable();
publicAPI.render();
};
publicAPI.enable = function () {
return publicAPI.setEnabled(true);
};
publicAPI.disable = function () {
return publicAPI.setEnabled(false);
};
publicAPI.startEventLoop = function () {
return vtkWarningMacro('empty event loop');
};
function updateCurrentRenderer(x, y) {
model.currentRenderer = publicAPI.findPokedRenderer(x, y);
}
publicAPI.getCurrentRenderer = function () {
if (model.currentRenderer) {
return model.currentRenderer;
}
updateCurrentRenderer(0, 0);
return model.currentRenderer;
};
function getScreenEventPositionFor(source) {
var bounds = model.container.getBoundingClientRect();
var canvas = model.view.getCanvas();
var scaleX = canvas.width / bounds.width;
var scaleY = canvas.height / bounds.height;
var position = {
x: scaleX * (source.clientX - bounds.left),
y: scaleY * (bounds.height - source.clientY + bounds.top),
z: 0
};
updateCurrentRenderer(position.x, position.y);
return position;
}
function getTouchEventPositionsFor(touches) {
var positions = {};
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
positions[touch.identifier] = getScreenEventPositionFor(touch);
}
return positions;
}
function getModifierKeysFor(event) {
return {
controlKey: event.ctrlKey,
altKey: event.altKey,
shiftKey: event.shiftKey
};
}
function getKeysFor(event) {
var modifierKeys = getModifierKeysFor(event);
var keys = {
key: event.key,
keyCode: event.charCode
};
Object.assign(keys, modifierKeys);
return keys;
}
function interactionRegistration(addListeners) {
var rootElm = document.querySelector('body');
var method = addListeners ? 'addEventListener' : 'removeEventListener';
var invMethod = addListeners ? 'removeEventListener' : 'addEventListener';
if (model.container) {
model.container[invMethod]('mousemove', publicAPI.handleMouseMove);
}
rootElm[method]('mouseup', publicAPI.handleMouseUp);
rootElm[method]('mousemove', publicAPI.handleMouseMove);
rootElm[method]('touchend', publicAPI.handleTouchEnd, false);
rootElm[method]('touchcancel', publicAPI.handleTouchEnd, false);
rootElm[method]('touchmove', publicAPI.handleTouchMove, false);
}
publicAPI.bindEvents = function (container) {
model.container = container;
container.addEventListener('contextmenu', preventDefault);
// container.addEventListener('click', preventDefault); // Avoid stopping event propagation
container.addEventListener('wheel', publicAPI.handleWheel);
container.addEventListener('DOMMouseScroll', publicAPI.handleWheel);
container.addEventListener('mousemove', publicAPI.handleMouseMove);
container.addEventListener('mousedown', publicAPI.handleMouseDown);
document.querySelector('body').addEventListener('keypress', publicAPI.handleKeyPress);
document.querySelector('body').addEventListener('keydown', publicAPI.handleKeyDown);
document.querySelector('body').addEventListener('keyup', publicAPI.handleKeyUp);
container.addEventListener('touchstart', publicAPI.handleTouchStart, false);
};
publicAPI.unbindEvents = function () {
interactionRegistration(false);
model.container.removeEventListener('contextmenu', preventDefault);
// model.container.removeEventListener('click', preventDefault); // Avoid stopping event propagation
model.container.removeEventListener('wheel', publicAPI.handleWheel);
model.container.removeEventListener('DOMMouseScroll', publicAPI.handleWheel);
model.container.removeEventListener('mousemove', publicAPI.handleMouseMove);
model.container.removeEventListener('mousedown', publicAPI.handleMouseDown);
document.querySelector('body').removeEventListener('keypress', publicAPI.handleKeyPress);
document.querySelector('body').removeEventListener('keydown', publicAPI.handleKeyDown);
document.querySelector('body').removeEventListener('keyup', publicAPI.handleKeyUp);
model.container.removeEventListener('touchstart', publicAPI.handleTouchStart);
model.container = null;
};
publicAPI.handleKeyPress = function (event) {
var data = getKeysFor(event);
publicAPI.keyPressEvent(data);
};
publicAPI.handleKeyDown = function (event) {
var data = getKeysFor(event);
publicAPI.keyDownEvent(data);
};
publicAPI.handleKeyUp = function (event) {
var data = getKeysFor(event);
publicAPI.keyUpEvent(data);
};
publicAPI.handleMouseDown = function (event) {
interactionRegistration(true);
event.stopPropagation();
event.preventDefault();
var callData = {
position: getScreenEventPositionFor(event)
};
var keys = getModifierKeysFor(event);
Object.assign(callData, keys);
switch (event.which) {
case 1:
publicAPI.leftButtonPressEvent(callData);
break;
case 2:
publicAPI.middleButtonPressEvent(callData);
break;
case 3:
publicAPI.rightButtonPressEvent(callData);
break;
default:
vtkErrorMacro('Unknown mouse button pressed: ' + event.which);
break;
}
};
//----------------------------------------------------------------------
function forceRender() {
if (model.view && model.enabled && model.enableRender) {
model.inRender = true;
model.view.traverseAllPasses();
model.inRender = false;
}
// outside the above test so that third-party code can redirect
// the render to the appropriate class
publicAPI.invokeRenderEvent();
}
publicAPI.requestAnimation = function (requestor) {
if (requestor === undefined) {
vtkErrorMacro('undefined requester, can not start animating');
return;
}
if (animationRequesters.has(requestor)) {
vtkWarningMacro('requester is already registered for animating');
return;
}
animationRequesters.add(requestor);
if (animationRequesters.size === 1) {
model.lastFrameTime = 0.1;
model.lastFrameStart = Date.now();
model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
publicAPI.startAnimationEvent();
}
};
publicAPI.isAnimating = function () {
return model.vrAnimation || model.animationRequest !== null;
};
publicAPI.cancelAnimation = function (requestor) {
var skipWarning = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!animationRequesters.has(requestor)) {
if (!skipWarning) {
var requestStr = requestor && requestor.getClassName ? requestor.getClassName() : requestor;
vtkWarningMacro(requestStr + ' did not request an animation');
}
return;
}
animationRequesters.delete(requestor);
if (model.animationRequest && animationRequesters.size === 0) {
cancelAnimationFrame(model.animationRequest);
model.animationRequest = null;
publicAPI.endAnimationEvent();
publicAPI.render();
}
};
publicAPI.switchToVRAnimation = function () {
// cancel existing animation if any
if (model.animationRequest) {
cancelAnimationFrame(model.animationRequest);
model.animationRequest = null;
}
model.vrAnimation = true;
};
publicAPI.returnFromVRAnimation = function () {
model.vrAnimation = false;
};
publicAPI.updateGamepads = function (displayId) {
var gamepads = navigator.getGamepads();
// watch for when buttons change state and fire events
for (var i = 0; i < gamepads.length; ++i) {
var gp = gamepads[i];
if (gp && gp.displayId === displayId) {
if (!(gp.index in model.lastGamepadValues)) {
model.lastGamepadValues[gp.index] = { buttons: {} };
}
for (var b = 0; b < gp.buttons.length; ++b) {
if (!(b in model.lastGamepadValues[gp.index].buttons)) {
model.lastGamepadValues[gp.index].buttons[b] = false;
}
if (model.lastGamepadValues[gp.index].buttons[b] !== gp.buttons[b].pressed) {
publicAPI.button3DEvent({
gamepad: gp,
position: gp.pose.position,
orientation: gp.pose.orientation,
pressed: gp.buttons[b].pressed,
device: gp.hand === 'left' ? Device.LeftController : Device.RightController,
input: deviceInputMap[gp.id] && deviceInputMap[gp.id][b] ? deviceInputMap[gp.id][b] : Input.Trigger
});
model.lastGamepadValues[gp.index].buttons[b] = gp.buttons[b].pressed;
}
if (model.lastGamepadValues[gp.index].buttons[b]) {
publicAPI.move3DEvent({
gamepad: gp,
position: gp.pose.position,
orientation: gp.pose.orientation,
device: gp.hand === 'left' ? Device.LeftController : Device.RightController
});
}
}
}
}
};
publicAPI.handleMouseMove = function (event) {
// Do not consume event for move
// event.stopPropagation();
// event.preventDefault();
var callData = {
position: getScreenEventPositionFor(event)
};
var keys = getModifierKeysFor(event);
Object.assign(callData, keys);
if (model.moveTimeoutID === 0) {
publicAPI.startMouseMoveEvent(callData);
} else {
publicAPI.mouseMoveEvent(callData);
clearTimeout(model.moveTimeoutID);
}
// start a timer to keep us animating while we get mouse move events
model.moveTimeoutID = setTimeout(function () {
publicAPI.endMouseMoveEvent();
model.moveTimeoutID = 0;
}, 200);
};
publicAPI.handleAnimation = function () {
var currTime = Date.now();
if (model.FrameTime === -1.0) {
model.lastFrameTime = 0.1;
} else {
model.lastFrameTime = (currTime - model.lastFrameStart) / 1000.0;
}
model.lastFrameTime = Math.max(0.01, model.lastFrameTime);
model.lastFrameStart = currTime;
publicAPI.animationEvent();
forceRender();
model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
};
publicAPI.handleWheel = function (event) {
event.stopPropagation();
event.preventDefault();
/**
* wheel event values can vary significantly across browsers, platforms
* and devices [1]. `normalizeWheel` uses facebook's solution from their
* fixed-data-table repository [2].
*
* [1] https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel
* [2] https://github.com/facebookarchive/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
*
* This code will return an object with properties:
*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*
*/
var callData = normalizeWheel(event);
if (model.wheelTimeoutID === 0) {
publicAPI.startMouseWheelEvent(callData);
} else {
publicAPI.mouseWheelEvent(callData);
clearTimeout(model.wheelTimeoutID);
}
// start a timer to keep us animating while we get wheel events
model.wheelTimeoutID = setTimeout(function () {
publicAPI.endMouseWheelEvent();
model.wheelTimeoutID = 0;
}, 200);
};
publicAPI.handleMouseUp = function (event) {
interactionRegistration(false);
event.stopPropagation();
event.preventDefault();
var callData = {
position: getScreenEventPositionFor(event)
};
var keys = getModifierKeysFor(event);
Object.assign(callData, keys);
switch (event.which) {
case 1:
publicAPI.leftButtonReleaseEvent(callData);
break;
case 2:
publicAPI.middleButtonReleaseEvent(callData);
break;
case 3:
publicAPI.rightButtonReleaseEvent(callData);
break;
default:
vtkErrorMacro('Unknown mouse button released: ' + event.which);
break;
}
};
publicAPI.handleTouchStart = function (event) {
interactionRegistration(true);
event.stopPropagation();
event.preventDefault();
// If multitouch
if (model.recognizeGestures && event.touches.length > 1) {
var positions = getTouchEventPositionsFor(event.touches);
// did we just transition to multitouch?
if (event.touches.length === 2) {
var touch = event.touches[0];
var callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false
};
publicAPI.leftButtonReleaseEvent(callData);
}
// handle the gesture
publicAPI.recognizeGesture('TouchStart', positions);
} else {
var _touch = event.touches[0];
var _callData = {
position: getScreenEventPositionFor(_touch),
shiftKey: false,
altKey: false,
controlKey: false
};
publicAPI.leftButtonPressEvent(_callData);
}
};
publicAPI.handleTouchMove = function (event) {
event.stopPropagation();
event.preventDefault();
if (model.recognizeGestures && event.touches.length > 1) {
var positions = getTouchEventPositionsFor(event.touches);
publicAPI.recognizeGesture('TouchMove', positions);
} else {
var touch = event.touches[0];
var callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false
};
publicAPI.mouseMoveEvent(callData);
}
};
publicAPI.handleTouchEnd = function (event) {
event.stopPropagation();
event.preventDefault();
if (model.recognizeGestures) {
// No more fingers down
if (event.touches.length === 0) {
// If just one finger released, consider as left button
if (event.changedTouches.length === 1) {
var touch = event.changedTouches[0];
var callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false
};
publicAPI.leftButtonReleaseEvent(callData);
interactionRegistration(false);
} else {
// If more than one finger released, recognize touchend
var positions = getTouchEventPositionsFor(event.changedTouches);
publicAPI.recognizeGesture('TouchEnd', positions);
interactionRegistration(false);
}
} else if (event.touches.length === 1) {
// If one finger left, end touch and start button press
var _positions = getTouchEventPositionsFor(event.changedTouches);
publicAPI.recognizeGesture('TouchEnd', _positions);
var _touch2 = event.touches[0];
var _callData2 = {
position: getScreenEventPositionFor(_touch2),
shiftKey: false,
altKey: false,
controlKey: false
};
publicAPI.leftButtonPressEvent(_callData2);
} else {
// If more than one finger left, keep touch move
var _positions2 = getTouchEventPositionsFor(event.touches);
publicAPI.recognizeGesture('TouchMove', _positions2);
}
} else {
var _touch3 = event.changedTouches[0];
var _callData3 = {
position: getScreenEventPositionFor(_touch3),
shiftKey: false,
altKey: false,
controlKey: false
};
publicAPI.leftButtonReleaseEvent(_callData3);
interactionRegistration(false);
}
};
publicAPI.setView = function (val) {
if (model.view === val) {
return;
}
model.view = val;
model.view.getRenderable().setInteractor(publicAPI);
publicAPI.modified();
};
publicAPI.findPokedRenderer = function () {
var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (!model.view) {
return null;
}
var rc = model.view.getRenderable().getRenderersByReference();
var interactiveren = null;
var viewportren = null;
var currentRenderer = null;
var count = rc.length;
while (count--) {
var aren = rc[count];
if (model.view.isInViewport(x, y, aren) && aren.getInteractive()) {
currentRenderer = aren;
}
if (interactiveren === null && aren.getInteractive()) {
// Save this renderer in case we can't find one in the viewport that
// is interactive.
interactiveren = aren;
}
if (viewportren === null && model.view.isInViewport(x, y, aren)) {
// Save this renderer in case we can't find one in the viewport that
// is interactive.
viewportren = aren;
}
}
// We must have a value. If we found an interactive renderer before, that's
// better than a non-interactive renderer.
if (currentRenderer === null) {
currentRenderer = interactiveren;
}
// We must have a value. If we found a renderer that is in the viewport,
// that is better than any old viewport (but not as good as an interactive
// one).
if (currentRenderer === null) {
currentRenderer = viewportren;
}
// We must have a value - take anything.
if (currentRenderer == null) {
currentRenderer = rc[0];
}
return currentRenderer;
};
// only render if we are not animating. If we are animating
// then renders will happen naturally anyhow and we definitely
// do not want extra renders as the make the apparent interaction
// rate slower.
publicAPI.render = function () {
if (model.animationRequest === null && !model.inRender) {
forceRender();
}
};
// create the generic Event methods
handledEvents.forEach(function (eventName) {
var lowerFirst = eventName.charAt(0).toLowerCase() + eventName.slice(1);
publicAPI[lowerFirst + 'Event'] = function (arg) {
// Check that interactor enabled
if (!model.enabled) {
return;
}
// Check that a poked renderer exists
var renderer = publicAPI.getCurrentRenderer();
if (!renderer) {
vtkOnceErrorMacro('\n Can not forward events without a current renderer on the interactor.\n ');
return;
}
// Pass the eventName and the poked renderer
var callData = {
type: eventName,
pokedRenderer: model.currentRenderer
};
// Add the arguments to the call data
Object.assign(callData, arg);
// Call invoke
publicAPI['invoke' + eventName](callData);
};
});
// we know we are in multitouch now, so start recognizing
publicAPI.recognizeGesture = function (event, positions) {
// more than two pointers we ignore
if (Object.keys(positions).length > 2) {
return;
}
if (!model.startingEventPositions) {
model.startingEventPositions = {};
}
// store the initial positions
if (event === 'TouchStart') {
Object.keys(positions).forEach(function (key) {
model.startingEventPositions[key] = positions[key];
});
// we do not know what the gesture is yet
model.currentGesture = 'Start';
return;
}
// end the gesture if needed
if (event === 'TouchEnd') {
if (model.currentGesture === 'Pinch') {
publicAPI.render();
publicAPI.endPinchEvent();
}
if (model.currentGesture === 'Rotate') {
publicAPI.render();
publicAPI.endRotateEvent();
}
if (model.currentGesture === 'Pan') {
publicAPI.render();
publicAPI.endPanEvent();
}
model.currentGesture = 'Start';
model.startingEventPositions = {};
return;
}
// what are the two pointers we are working with
var count = 0;
var posVals = [];
var startVals = [];
Object.keys(positions).forEach(function (key) {
posVals[count] = positions[key];
startVals[count] = model.startingEventPositions[key];
count++;
});
// The meat of the algorithm
// on move events we analyze them to determine what type
// of movement it is and then deal with it.
// calculate the distances
var originalDistance = Math.sqrt((startVals[0].x - startVals[1].x) * (startVals[0].x - startVals[1].x) + (startVals[0].y - startVals[1].y) * (startVals[0].y - startVals[1].y));
var newDistance = Math.sqrt((posVals[0].x - posVals[1].x) * (posVals[0].x - posVals[1].x) + (posVals[0].y - posVals[1].y) * (posVals[0].y - posVals[1].y));
// calculate rotations
var originalAngle = _Math2.default.degreesFromRadians(Math.atan2(startVals[1].y - startVals[0].y, startVals[1].x - startVals[0].x));
var newAngle = _Math2.default.degreesFromRadians(Math.atan2(posVals[1].y - posVals[0].y, posVals[1].x - posVals[0].x));
// angles are cyclic so watch for that, 1 and 359 are only 2 apart :)
var angleDeviation = newAngle - originalAngle;
newAngle = newAngle + 180.0 >= 360.0 ? newAngle - 180.0 : newAngle + 180.0;
originalAngle = originalAngle + 180.0 >= 360.0 ? originalAngle - 180.0 : originalAngle + 180.0;
if (Math.abs(newAngle - originalAngle) < Math.abs(angleDeviation)) {
angleDeviation = newAngle - originalAngle;
}
// calculate the translations
var trans = [];
trans[0] = (posVals[0].x - startVals[0].x + posVals[1].x - startVals[1].x) / 2.0;
trans[1] = (posVals[0].y - startVals[0].y + posVals[1].y - startVals[1].y) / 2.0;
if (event === 'TouchMove') {
// OK we want to
// - immediately respond to the user
// - allow the user to zoom without panning (saves focal point)
// - allow the user to rotate without panning (saves focal point)
// do we know what gesture we are doing yet? If not
// see if we can figure it out
if (model.currentGesture === 'Start') {
// pinch is a move to/from the center point
// rotate is a move along the circumference
// pan is a move of the center point
// compute the distance along each of these axes in pixels
// the first to break thresh wins
var thresh = 0.01 * Math.sqrt(model.container.clientWidth * model.container.clientWidth + model.container.clientHeight * model.container.clientHeight);
if (thresh < 15.0) {
thresh = 15.0;
}
var pinchDistance = Math.abs(newDistance - originalDistance);
var rotateDistance = newDistance * 3.1415926 * Math.abs(angleDeviation) / 360.0;
var panDistance = Math.sqrt(trans[0] * trans[0] + trans[1] * trans[1]);
if (pinchDistance > thresh && pinchDistance > rotateDistance && pinchDistance > panDistance) {
model.currentGesture = 'Pinch';
var callData = {
scale: 1.0,
touches: positions
};
publicAPI.startPinchEvent(callData);
} else if (rotateDistance > thresh && rotateDistance > panDistance) {
model.currentGesture = 'Rotate';
var _callData4 = {
rotation: 0.0,
touches: positions
};
publicAPI.startRotateEvent(_callData4);
} else if (panDistance > thresh) {
model.currentGesture = 'Pan';
var _callData5 = {
translation: [0, 0],
touches: positions
};
publicAPI.startPanEvent(_callData5);
}
} else {
// if we have found a specific type of movement then
// handle it
if (model.currentGesture === 'Rotate') {
var _callData6 = {
rotation: angleDeviation,
touches: positions
};
publicAPI.rotateEvent(_callData6);
}
if (model.currentGesture === 'Pinch') {
var _callData7 = {
scale: newDistance / originalDistance,
touches: positions
};
publicAPI.pinchEvent(_callData7);
}
if (model.currentGesture === 'Pan') {
var _callData8 = {
translation: trans,
touches: positions
};
publicAPI.panEvent(_callData8);
}
}
}
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
renderWindow: null,
interactorStyle: null,
picker: null,
pickingManager: null,
initialized: false,
enabled: false,
enableRender: true,
currentRenderer: null,
lightFollowCamera: true,
desiredUpdateRate: 30.0,
stillUpdateRate: 2.0,
container: null,
view: null,
recognizeGestures: true,
currentGesture: 'Start',
animationRequest: null,
lastFrameTime: 0.1,
wheelTimeoutID: 0,
moveTimeoutID: 0,
lastGamepadValues: {}
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Object methods
_macro2.default.obj(publicAPI, model);
_macro2.default.event(publicAPI, model, 'RenderEvent');
handledEvents.forEach(function (eventName) {
return _macro2.default.event(publicAPI, model, eventName);
});
// Create get-only macros
_macro2.default.get(publicAPI, model, ['initialized', 'container', 'enabled', 'enableRender', 'interactorStyle', 'lastFrameTime', 'view']);
// Create get-set macros
_macro2.default.setGet(publicAPI, model, ['lightFollowCamera', 'enabled', 'recognizeGestures', 'desiredUpdateRate', 'stillUpdateRate', 'picker']);
// For more macro methods, see "Sources/macro.js"
// Object specific methods
vtkRenderWindowInteractor(publicAPI, model);
publicAPI.setInteractorStyle(_InteractorStyleTrackballCamera2.default.newInstance());
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkRenderWindowInteractor');
// ----------------------------------------------------------------------------
exports.default = Object.assign({ newInstance: newInstance, extend: extend, handledEvents: handledEvents }, _Constants2.default);
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var States = exports.States = {
IS_START: 0,
IS_NONE: 0,
IS_ROTATE: 1,
IS_PAN: 2,
IS_SPIN: 3,
IS_DOLLY: 4,
IS_CAMERA_POSE: 11,
IS_WINDOW_LEVEL: 1024,
IS_SLICE: 1025
};
exports.default = {
States: States
};
/***/ }),
/* 283 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var Device = exports.Device = {
Unknown: 0,
LeftController: 1,
RightController: 2
};
var Input = exports.Input = {
Unknown: 0,
Trigger: 1,
TrackPad: 2,
Grip: 3,
ApplicationMenu: 4
};
exports.default = {
Device: Device,
Input: Input
};
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It isn't worth it to make additional optimizations as in original.
// Small size is preferable.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc ^= -1;
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// String encode/decode helpers
var utils = __webpack_require__(43);
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safari
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q = 0; q < 256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i = 0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function (buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function (str) {
var buf = new utils.Buf8(str.length);
for (var i = 0, len = buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function (buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means buffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
/***/ }),
/* 289 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/* 290 */
/***/ (function(module, exports, __webpack_require__) {
/*
* This file is used by module bundlers (browserify/webpack/etc) when
* including a stream implementation. We use "readable-stream" to get a
* consistent behavior between nodejs versions but bundlers often have a shim
* for "stream". Using this shim greatly improve the compatibility and greatly
* reduce the final size of the bundle (only one stream implementation, not
* two).
*/
module.exports = __webpack_require__(621);
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
/**/
var processNextTick = __webpack_require__(109);
/**/
module.exports = Readable;
/**/
var isArray = __webpack_require__(289);
/**/
/**/
var Duplex;
/**/
Readable.ReadableState = ReadableState;
/**/
var EE = __webpack_require__(60).EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/**/
/**/
var Stream = __webpack_require__(292);
/**/
// TODO(bmeurer): Change this back to const once hole checks are
// properly optimized away early in Ignition+TurboFan.
/**/
var Buffer = __webpack_require__(110).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/**/
/**/
var util = __webpack_require__(90);
util.inherits = __webpack_require__(70);
/**/
/**/
var debugUtil = __webpack_require__(622);
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/**/
var BufferList = __webpack_require__(623);
var destroyImpl = __webpack_require__(293);
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') {
return emitter.prependListener(event, fn);
} else {
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
}
function ReadableState(options, stream) {
Duplex = Duplex || __webpack_require__(53);
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = __webpack_require__(294).StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || __webpack_require__(53);
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = __webpack_require__(294).StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
processNextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
processNextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
processNextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) self.push(chunk);
}
self.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
processNextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25), __webpack_require__(87)))
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(60).EventEmitter;
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**/
var processNextTick = __webpack_require__(109);
/**/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
processNextTick(emitErrorNT, this, err);
}
return;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
processNextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(110).Buffer;
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return -1;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd'.repeat(p);
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd'.repeat(p + 1);
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd'.repeat(p + 2);
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character for each buffered byte of a (partial)
// character needs to be added to the output.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = __webpack_require__(53);
/**/
var util = __webpack_require__(90);
util.inherits = __webpack_require__(70);
/**/
util.inherits(Transform, Duplex);
function TransformState(stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
this.writeencoding = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return stream.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined) stream.push(data);
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(this);
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.once('prefinish', function () {
if (typeof this._flush === 'function') this._flush(function (er, data) {
done(stream, er, data);
});else done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data !== null && data !== undefined) stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length) throw new Error('Calling transform done when ws.length != 0');
if (ts.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(11);
var support = __webpack_require__(44);
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding
exports.encode = function(input) {
var output = [];
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0, len = input.length, remainingBytes = len;
var isArray = utils.getTypeOf(input) !== "string";
while (i < input.length) {
remainingBytes = len - i;
if (!isArray) {
chr1 = input.charCodeAt(i++);
chr2 = i < len ? input.charCodeAt(i++) : 0;
chr3 = i < len ? input.charCodeAt(i++) : 0;
} else {
chr1 = input[i++];
chr2 = i < len ? input[i++] : 0;
chr3 = i < len ? input[i++] : 0;
}
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
}
return output.join("");
};
// public method for decoding
exports.decode = function(input) {
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0, resultIndex = 0;
var dataUrlPrefix = "data:";
if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
// This is a common error: people give a data url
// (data:image/png;base64,iVBOR...) with a {base64: true} and
// wonders why things don't work.
// We can detect that the string input looks like a data url but we
// *can't* be sure it is one: removing everything up to the comma would
// be too dangerous.
throw new Error("Invalid base64 input, it looks like a data url.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
var totalLength = input.length * 3 / 4;
if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
totalLength--;
}
if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
totalLength--;
}
if (totalLength % 1 !== 0) {
// totalLength is not an integer, the length does not match a valid
// base64 content. That can happen if:
// - the input is not a base64 content
// - the input is *almost* a base64 content, with a extra chars at the
// beginning or at the end
// - the input uses a base64 variant (base64url for example)
throw new Error("Invalid base64 input, bad content length.");
}
var output;
if (support.uint8array) {
output = new Uint8Array(totalLength|0);
} else {
output = new Array(totalLength|0);
}
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output[resultIndex++] = chr1;
if (enc3 !== 64) {
output[resultIndex++] = chr2;
}
if (enc4 !== 64) {
output[resultIndex++] = chr3;
}
}
return output;
};
/***/ }),
/* 297 */
/***/ (function(module, exports) {
var core = module.exports = {version: '2.3.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(633);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ }),
/* 299 */
/***/ (function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(178)
, document = __webpack_require__(112).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var utils = __webpack_require__(11);
var ConvertWorker = __webpack_require__(646);
var GenericWorker = __webpack_require__(29);
var base64 = __webpack_require__(296);
var support = __webpack_require__(44);
var external = __webpack_require__(91);
var NodejsStreamOutputAdapter = null;
if (support.nodestream) {
try {
NodejsStreamOutputAdapter = __webpack_require__(647);
} catch(e) {}
}
/**
* Apply the final transformation of the data. If the user wants a Blob for
* example, it's easier to work with an U8intArray and finally do the
* ArrayBuffer/Blob conversion.
* @param {String} resultType the name of the final type
* @param {String} chunkType the type of the data in the given array.
* @param {Array} dataArray the array containing the data chunks to concatenate
* @param {String|Uint8Array|Buffer} content the content to transform
* @param {String} mimeType the mime type of the content, if applicable.
* @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
*/
function transformZipOutput(resultType, chunkType, dataArray, mimeType) {
var content = null;
switch(resultType) {
case "blob" :
return utils.newBlob(dataArray, mimeType);
case "base64" :
content = concat(chunkType, dataArray);
return base64.encode(content);
default :
content = concat(chunkType, dataArray);
return utils.transformTo(resultType, content);
}
}
/**
* Concatenate an array of data of the given type.
* @param {String} type the type of the data in the given array.
* @param {Array} dataArray the array containing the data chunks to concatenate
* @return {String|Uint8Array|Buffer} the concatenated data
* @throws Error if the asked type is unsupported
*/
function concat (type, dataArray) {
var i, index = 0, res = null, totalLength = 0;
for(i = 0; i < dataArray.length; i++) {
totalLength += dataArray[i].length;
}
switch(type) {
case "string":
return dataArray.join("");
case "array":
return Array.prototype.concat.apply([], dataArray);
case "uint8array":
res = new Uint8Array(totalLength);
for(i = 0; i < dataArray.length; i++) {
res.set(dataArray[i], index);
index += dataArray[i].length;
}
return res;
case "nodebuffer":
return Buffer.concat(dataArray);
default:
throw new Error("concat : unsupported type '" + type + "'");
}
}
/**
* Listen a StreamHelper, accumulate its content and concatenate it into a
* complete block.
* @param {StreamHelper} helper the helper to use.
* @param {Function} updateCallback a callback called on each update. Called
* with one arg :
* - the metadata linked to the update received.
* @return Promise the promise for the accumulation.
*/
function accumulate(helper, updateCallback) {
return new external.Promise(function (resolve, reject){
var dataArray = [];
var chunkType = helper._internalType,
resultType = helper._outputType,
mimeType = helper._mimeType;
helper
.on('data', function (data, meta) {
dataArray.push(data);
if(updateCallback) {
updateCallback(meta);
}
})
.on('error', function(err) {
dataArray = [];
reject(err);
})
.on('end', function (){
try {
var result = transformZipOutput(resultType, chunkType, dataArray, mimeType);
resolve(result);
} catch (e) {
reject(e);
}
dataArray = [];
})
.resume();
});
}
/**
* An helper to easily use workers outside of JSZip.
* @constructor
* @param {Worker} worker the worker to wrap
* @param {String} outputType the type of data expected by the use
* @param {String} mimeType the mime type of the content, if applicable.
*/
function StreamHelper(worker, outputType, mimeType) {
var internalType = outputType;
switch(outputType) {
case "blob":
internalType = "arraybuffer";
break;
case "arraybuffer":
internalType = "uint8array";
break;
case "base64":
internalType = "string";
break;
}
try {
// the type used internally
this._internalType = internalType;
// the type used to output results
this._outputType = outputType;
// the mime type
this._mimeType = mimeType;
utils.checkSupport(internalType);
this._worker = worker.pipe(new ConvertWorker(internalType));
// the last workers can be rewired without issues but we need to
// prevent any updates on previous workers.
worker.lock();
} catch(e) {
this._worker = new GenericWorker("error");
this._worker.error(e);
}
}
StreamHelper.prototype = {
/**
* Listen a StreamHelper, accumulate its content and concatenate it into a
* complete block.
* @param {Function} updateCb the update callback.
* @return Promise the promise for the accumulation.
*/
accumulate : function (updateCb) {
return accumulate(this, updateCb);
},
/**
* Add a listener on an event triggered on a stream.
* @param {String} evt the name of the event
* @param {Function} fn the listener
* @return {StreamHelper} the current helper.
*/
on : function (evt, fn) {
var self = this;
if(evt === "data") {
this._worker.on(evt, function (chunk) {
fn.call(self, chunk.data, chunk.meta);
});
} else {
this._worker.on(evt, function () {
utils.delay(fn, arguments, self);
});
}
return this;
},
/**
* Resume the flow of chunks.
* @return {StreamHelper} the current helper.
*/
resume : function () {
utils.delay(this._worker.resume, [], this._worker);
return this;
},
/**
* Pause the flow of chunks.
* @return {StreamHelper} the current helper.
*/
pause : function () {
this._worker.pause();
return this;
},
/**
* Return a nodejs stream for this helper.
* @param {Function} updateCb the update callback.
* @return {NodejsStreamOutputAdapter} the nodejs stream.
*/
toNodejsStream : function (updateCb) {
utils.checkSupport("nodestream");
if (this._outputType !== "nodebuffer") {
// an object stream containing blob/arraybuffer/uint8array/string
// is strange and I don't know if it would be useful.
// I you find this comment and have a good usecase, please open a
// bug report !
throw new Error(this._outputType + " is not supported by this method");
}
return new NodejsStreamOutputAdapter(this, {
objectMode : this._outputType !== "nodebuffer"
}, updateCb);
}
};
module.exports = StreamHelper;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(89).Buffer))
/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.base64 = false;
exports.binary = false;
exports.dir = false;
exports.createFolders = true;
exports.date = null;
exports.compression = null;
exports.compressionOptions = null;
exports.comment = null;
exports.unixPermissions = null;
exports.dosPermissions = null;
/***/ }),
/* 303 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(11);
var GenericWorker = __webpack_require__(29);
// the size of the generated chunks
// TODO expose this as a public variable
var DEFAULT_BLOCK_SIZE = 16 * 1024;
/**
* A worker that reads a content and emits chunks.
* @constructor
* @param {Promise} dataP the promise of the data to split
*/
function DataWorker(dataP) {
GenericWorker.call(this, "DataWorker");
var self = this;
this.dataIsReady = false;
this.index = 0;
this.max = 0;
this.data = null;
this.type = "";
this._tickScheduled = false;
dataP.then(function (data) {
self.dataIsReady = true;
self.data = data;
self.max = data && data.length || 0;
self.type = utils.getTypeOf(data);
if(!self.isPaused) {
self._tickAndRepeat();
}
}, function (e) {
self.error(e);
});
}
utils.inherits(DataWorker, GenericWorker);
/**
* @see GenericWorker.cleanUp
*/
DataWorker.prototype.cleanUp = function () {
GenericWorker.prototype.cleanUp.call(this);
this.data = null;
};
/**
* @see GenericWorker.resume
*/
DataWorker.prototype.resume = function () {
if(!GenericWorker.prototype.resume.call(this)) {
return false;
}
if (!this._tickScheduled && this.dataIsReady) {
this._tickScheduled = true;
utils.delay(this._tickAndRepeat, [], this);
}
return true;
};
/**
* Trigger a tick a schedule an other call to this function.
*/
DataWorker.prototype._tickAndRepeat = function() {
this._tickScheduled = false;
if(this.isPaused || this.isFinished) {
return;
}
this._tick();
if(!this.isFinished) {
utils.delay(this._tickAndRepeat, [], this);
this._tickScheduled = true;
}
};
/**
* Read and push a chunk.
*/
DataWorker.prototype._tick = function() {
if(this.isPaused || this.isFinished) {
return false;
}
var size = DEFAULT_BLOCK_SIZE;
var data = null, nextIndex = Math.min(this.max, this.index + size);
if (this.index >= this.max) {
// EOF
return this.end();
} else {
switch(this.type) {
case "string":
data = this.data.substring(this.index, nextIndex);
break;
case "uint8array":
data = this.data.subarray(this.index, nextIndex);
break;
case "array":
case "nodebuffer":
data = this.data.slice(this.index, nextIndex);
break;
}
this.index = nextIndex;
return this.push({
data : data,
meta : {
percent : this.max ? this.index / this.max * 100 : 0
}
});
}
};
module.exports = DataWorker;
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(11);
var GenericWorker = __webpack_require__(29);
/**
* A worker which calculate the total length of the data flowing through.
* @constructor
* @param {String} propName the name used to expose the length
*/
function DataLengthProbe(propName) {
GenericWorker.call(this, "DataLengthProbe for " + propName);
this.propName = propName;
this.withStreamInfo(propName, 0);
}
utils.inherits(DataLengthProbe, GenericWorker);
/**
* @see GenericWorker.processChunk
*/
DataLengthProbe.prototype.processChunk = function (chunk) {
if(chunk) {
var length = this.streamInfo[this.propName] || 0;
this.streamInfo[this.propName] = length + chunk.data.length;
}
GenericWorker.prototype.processChunk.call(this, chunk);
};
module.exports = DataLengthProbe;
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GenericWorker = __webpack_require__(29);
var crc32 = __webpack_require__(181);
var utils = __webpack_require__(11);
/**
* A worker which calculate the crc32 of the data flowing through.
* @constructor
*/
function Crc32Probe() {
GenericWorker.call(this, "Crc32Probe");
this.withStreamInfo("crc32", 0);
}
utils.inherits(Crc32Probe, GenericWorker);
/**
* @see GenericWorker.processChunk
*/
Crc32Probe.prototype.processChunk = function (chunk) {
this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
this.push(chunk);
};
module.exports = Crc32Probe;
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GenericWorker = __webpack_require__(29);
exports.STORE = {
magic: "\x00\x00",
compressWorker : function (compressionOptions) {
return new GenericWorker("STORE compression");
},
uncompressWorker : function () {
return new GenericWorker("STORE decompression");
}
};
exports.DEFLATE = __webpack_require__(650);
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.LOCAL_FILE_HEADER = "PK\x03\x04";
exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
exports.DATA_DESCRIPTOR = "PK\x07\x08";
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(11);
var support = __webpack_require__(44);
var ArrayReader = __webpack_require__(309);
var StringReader = __webpack_require__(655);
var NodeBufferReader = __webpack_require__(656);
var Uint8ArrayReader = __webpack_require__(311);
/**
* Create a reader adapted to the data.
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
* @return {DataReader} the data reader.
*/
module.exports = function (data) {
var type = utils.getTypeOf(data);
utils.checkSupport(type);
if (type === "string" && !support.uint8array) {
return new StringReader(data);
}
if (type === "nodebuffer") {
return new NodeBufferReader(data);
}
if (support.uint8array) {
return new Uint8ArrayReader(utils.transformTo("uint8array", data));
}
return new ArrayReader(utils.transformTo("array", data));
};
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var DataReader = __webpack_require__(310);
var utils = __webpack_require__(11);
function ArrayReader(data) {
DataReader.call(this, data);
for(var i = 0; i < this.data.length; i++) {
data[i] = data[i] & 0xFF;
}
}
utils.inherits(ArrayReader, DataReader);
/**
* @see DataReader.byteAt
*/
ArrayReader.prototype.byteAt = function(i) {
return this.data[this.zero + i];
};
/**
* @see DataReader.lastIndexOfSignature
*/
ArrayReader.prototype.lastIndexOfSignature = function(sig) {
var sig0 = sig.charCodeAt(0),
sig1 = sig.charCodeAt(1),
sig2 = sig.charCodeAt(2),
sig3 = sig.charCodeAt(3);
for (var i = this.length - 4; i >= 0; --i) {
if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
return i - this.zero;
}
}
return -1;
};
/**
* @see DataReader.readAndCheckSignature
*/
ArrayReader.prototype.readAndCheckSignature = function (sig) {
var sig0 = sig.charCodeAt(0),
sig1 = sig.charCodeAt(1),
sig2 = sig.charCodeAt(2),
sig3 = sig.charCodeAt(3),
data = this.readData(4);
return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
};
/**
* @see DataReader.readData
*/
ArrayReader.prototype.readData = function(size) {
this.checkOffset(size);
if(size === 0) {
return [];
}
var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
this.index += size;
return result;
};
module.exports = ArrayReader;
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(11);
function DataReader(data) {
this.data = data; // type : see implementation
this.length = data.length;
this.index = 0;
this.zero = 0;
}
DataReader.prototype = {
/**
* Check that the offset will not go too far.
* @param {string} offset the additional offset to check.
* @throws {Error} an Error if the offset is out of bounds.
*/
checkOffset: function(offset) {
this.checkIndex(this.index + offset);
},
/**
* Check that the specifed index will not be too far.
* @param {string} newIndex the index to check.
* @throws {Error} an Error if the index is out of bounds.
*/
checkIndex: function(newIndex) {
if (this.length < this.zero + newIndex || newIndex < 0) {
throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
}
},
/**
* Change the index.
* @param {number} newIndex The new index.
* @throws {Error} if the new index is out of the data.
*/
setIndex: function(newIndex) {
this.checkIndex(newIndex);
this.index = newIndex;
},
/**
* Skip the next n bytes.
* @param {number} n the number of bytes to skip.
* @throws {Error} if the new index is out of the data.
*/
skip: function(n) {
this.setIndex(this.index + n);
},
/**
* Get the byte at the specified index.
* @param {number} i the index to use.
* @return {number} a byte.
*/
byteAt: function(i) {
// see implementations
},
/**
* Get the next number with a given byte size.
* @param {number} size the number of bytes to read.
* @return {number} the corresponding number.
*/
readInt: function(size) {
var result = 0,
i;
this.checkOffset(size);
for (i = this.index + size - 1; i >= this.index; i--) {
result = (result << 8) + this.byteAt(i);
}
this.index += size;
return result;
},
/**
* Get the next string with a given byte size.
* @param {number} size the number of bytes to read.
* @return {string} the corresponding string.
*/
readString: function(size) {
return utils.transformTo("string", this.readData(size));
},
/**
* Get raw data without conversion, bytes.
* @param {number} size the number of bytes to read.
* @return {Object} the raw data, implementation specific.
*/
readData: function(size) {
// see implementations
},
/**
* Find the last occurence of a zip signature (4 bytes).
* @param {string} sig the signature to find.
* @return {number} the index of the last occurence, -1 if not found.
*/
lastIndexOfSignature: function(sig) {
// see implementations
},
/**
* Read the signature (4 bytes) at the current position and compare it with sig.
* @param {string} sig the expected signature
* @return {boolean} true if the signature matches, false otherwise.
*/
readAndCheckSignature: function(sig) {
// see implementations
},
/**
* Get the next date.
* @return {Date} the date.
*/
readDate: function() {
var dostime = this.readInt(4);
return new Date(Date.UTC(
((dostime >> 25) & 0x7f) + 1980, // year
((dostime >> 21) & 0x0f) - 1, // month
(dostime >> 16) & 0x1f, // day
(dostime >> 11) & 0x1f, // hour
(dostime >> 5) & 0x3f, // minute
(dostime & 0x1f) << 1)); // second
}
};
module.exports = DataReader;
/***/ }),
/* 311 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArrayReader = __webpack_require__(309);
var utils = __webpack_require__(11);
function Uint8ArrayReader(data) {
ArrayReader.call(this, data);
}
utils.inherits(Uint8ArrayReader, ArrayReader);
/**
* @see DataReader.readData
*/
Uint8ArrayReader.prototype.readData = function(size) {
this.checkOffset(size);
if(size === 0) {
// in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
return new Uint8Array(0);
}
var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
this.index += size;
return result;
};
module.exports = Uint8ArrayReader;
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _DataArray = __webpack_require__(16);
var _DataArray2 = _interopRequireDefault(_DataArray);
var _PolyData = __webpack_require__(33);
var _PolyData2 = _interopRequireDefault(_PolyData);
var _MatrixBuilder = __webpack_require__(182);
var _MatrixBuilder2 = _interopRequireDefault(_MatrixBuilder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(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); } }
// ----------------------------------------------------------------------------
// vtkCubeSource methods
// ----------------------------------------------------------------------------
function vtkCubeSource(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkCubeSource');
function requestData(inData, outData) {
var _vtkMatrixBuilder$bui;
if (model.deleted) {
return;
}
var polyData = _PolyData2.default.newInstance();
outData[0] = polyData;
var numberOfPolys = 6;
var numberOfPoints = 24;
// Define points
var points = new window[model.pointType](numberOfPoints * 3);
polyData.getPoints().setData(points, 3);
var normals = new window[model.pointType](numberOfPoints * 3);
var normalArray = _DataArray2.default.newInstance({
name: 'Normals',
values: normals,
numberOfComponents: 3
});
polyData.getPointData().setNormals(normalArray);
var tcdim = 2;
if (model.generate3DTextureCoordinates === true) {
tcdim = 3;
}
var textureCoords = new window[model.pointType](numberOfPoints * tcdim);
var tcoords = _DataArray2.default.newInstance({
name: 'TextureCoordinates',
values: textureCoords,
numberOfComponents: tcdim
});
polyData.getPointData().setTCoords(tcoords);
var x = [0.0, 0.0, 0.0];
var n = [0.0, 0.0, 0.0];
var tc = [0.0, 0.0];
var pointIndex = 0;
x[0] = -model.xLength / 2.0;
n[0] = -1.0;
n[1] = 0.0;
n[2] = 0.0;
for (var i = 0; i < 2; i++) {
x[1] = -model.yLength / 2.0;
for (var j = 0; j < 2; j++) {
tc[1] = x[1] + 0.5;
x[2] = -model.zLength / 2.0;
for (var k = 0; k < 2; k++) {
tc[0] = (x[2] + 0.5) * (1 - 2 * i);
points[pointIndex * 3] = x[0];
points[pointIndex * 3 + 1] = x[1];
points[pointIndex * 3 + 2] = x[2];
normals[pointIndex * 3] = n[0];
normals[pointIndex * 3 + 1] = n[1];
normals[pointIndex * 3 + 2] = n[2];
if (tcdim === 2) {
textureCoords[pointIndex * tcdim] = tc[0];
textureCoords[pointIndex * tcdim + 1] = tc[1];
} else {
textureCoords[pointIndex * tcdim] = 2 * i - 1;
textureCoords[pointIndex * tcdim + 1] = 2 * j - 1;
textureCoords[pointIndex * tcdim + 2] = 2 * k - 1;
}
pointIndex++;
x[2] += model.zLength;
}
x[1] += model.yLength;
}
x[0] += model.xLength;
n[0] += 2.0;
}
x[1] = -model.yLength / 2.0;
n[1] = -1.0;
n[0] = 0.0;
n[2] = 0.0;
for (var _i = 0; _i < 2; _i++) {
x[0] = -model.xLength / 2.0;
for (var _j = 0; _j < 2; _j++) {
tc[0] = (x[0] + 0.5) * (2 * _i - 1);
x[2] = -model.zLength / 2.0;
for (var _k = 0; _k < 2; _k++) {
tc[1] = (x[2] + 0.5) * -1;
points[pointIndex * 3] = x[0];
points[pointIndex * 3 + 1] = x[1];
points[pointIndex * 3 + 2] = x[2];
normals[pointIndex * 3] = n[0];
normals[pointIndex * 3 + 1] = n[1];
normals[pointIndex * 3 + 2] = n[2];
if (tcdim === 2) {
textureCoords[pointIndex * tcdim] = tc[0];
textureCoords[pointIndex * tcdim + 1] = tc[1];
} else {
textureCoords[pointIndex * tcdim] = 2 * _j - 1;
textureCoords[pointIndex * tcdim + 1] = 2 * _i - 1;
textureCoords[pointIndex * tcdim + 2] = 2 * _k - 1;
}
pointIndex++;
x[2] += model.zLength;
}
x[0] += model.xLength;
}
x[1] += model.yLength;
n[1] += 2.0;
}
x[2] = -model.zLength / 2.0;
n[2] = -1.0;
n[0] = 0.0;
n[1] = 0.0;
for (var _i2 = 0; _i2 < 2; _i2++) {
x[1] = -model.yLength / 2.0;
for (var _j2 = 0; _j2 < 2; _j2++) {
tc[1] = x[1] + 0.5;
x[0] = -model.xLength / 2.0;
for (var _k2 = 0; _k2 < 2; _k2++) {
tc[0] = (x[0] + 0.5) * (2 * _i2 - 1);
points[pointIndex * 3] = x[0];
points[pointIndex * 3 + 1] = x[1];
points[pointIndex * 3 + 2] = x[2];
normals[pointIndex * 3] = n[0];
normals[pointIndex * 3 + 1] = n[1];
normals[pointIndex * 3 + 2] = n[2];
if (tcdim === 2) {
textureCoords[pointIndex * tcdim] = tc[0];
textureCoords[pointIndex * tcdim + 1] = tc[1];
} else {
textureCoords[pointIndex * tcdim] = 2 * _k2 - 1;
textureCoords[pointIndex * tcdim + 1] = 2 * _j2 - 1;
textureCoords[pointIndex * tcdim + 2] = 2 * _i2 - 1;
}
pointIndex++;
x[0] += model.xLength;
}
x[1] += model.yLength;
}
x[2] += model.zLength;
n[2] += 2.0;
}
// Apply rotation to the points coordinates and normals
_MatrixBuilder2.default.buildFromDegree().rotateX(model.rotations[0]).rotateY(model.rotations[1]).rotateZ(model.rotations[2]).apply(points).apply(normals);
// Apply transformation to the points coordinates
(_vtkMatrixBuilder$bui = _MatrixBuilder2.default.buildFromRadian()).translate.apply(_vtkMatrixBuilder$bui, _toConsumableArray(model.center)).apply(points);
// Define quads
var polys = new window[model.pointType](numberOfPolys * 5);
polyData.getPolys().setData(polys, 1);
var polyIndex = 0;
polys[polyIndex++] = 4;
polys[polyIndex++] = 0;
polys[polyIndex++] = 1;
polys[polyIndex++] = 3;
polys[polyIndex++] = 2;
polys[polyIndex++] = 4;
polys[polyIndex++] = 4;
polys[polyIndex++] = 6;
polys[polyIndex++] = 7;
polys[polyIndex++] = 5;
polys[polyIndex++] = 4;
polys[polyIndex++] = 8;
polys[polyIndex++] = 10;
polys[polyIndex++] = 11;
polys[polyIndex++] = 9;
polys[polyIndex++] = 4;
polys[polyIndex++] = 12;
polys[polyIndex++] = 13;
polys[polyIndex++] = 15;
polys[polyIndex++] = 14;
polys[polyIndex++] = 4;
polys[polyIndex++] = 16;
polys[polyIndex++] = 18;
polys[polyIndex++] = 19;
polys[polyIndex++] = 17;
polys[polyIndex++] = 4;
polys[polyIndex++] = 20;
polys[polyIndex++] = 21;
polys[polyIndex++] = 23;
polys[polyIndex] = 22;
}
publicAPI.setBounds = function () {
for (var _len = arguments.length, bounds = Array(_len), _key = 0; _key < _len; _key++) {
bounds[_key] = arguments[_key];
}
var boundsArray = [];
if (Array.isArray(bounds[0])) {
boundsArray = bounds[0];
} else {
for (var i = 0; i < bounds.length; i++) {
boundsArray.push(bounds[i]);
}
}
if (boundsArray.length !== 6) {
return;
}
model.xLength = boundsArray[1] - boundsArray[0];
model.yLength = boundsArray[3] - boundsArray[2];
model.zLength = boundsArray[5] - boundsArray[4];
model.center = [(boundsArray[0] + boundsArray[1]) / 2.0, (boundsArray[2] + boundsArray[3]) / 2.0, (boundsArray[4] + boundsArray[5]) / 2.0];
};
// Expose methods
publicAPI.requestData = requestData;
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
xLength: 1.0,
yLength: 1.0,
zLength: 1.0,
center: [0.0, 0.0, 0.0],
rotations: [0.0, 0.0, 0.0],
pointType: 'Float32Array',
generate3DTextureCoordinates: false
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
_macro2.default.obj(publicAPI, model);
_macro2.default.setGet(publicAPI, model, ['xLength', 'yLength', 'zLength', 'generate3DTextureCoordinates']);
_macro2.default.setGetArray(publicAPI, model, ['center', 'rotations'], 3);
_macro2.default.algo(publicAPI, model, 0, 1);
vtkCubeSource(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkCubeSource');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newInstance = undefined;
exports.extend = extend;
var _macro = __webpack_require__(1);
var _macro2 = _interopRequireDefault(_macro);
var _PolyData = __webpack_require__(33);
var _PolyData2 = _interopRequireDefault(_PolyData);
var _MatrixBuilder = __webpack_require__(182);
var _MatrixBuilder2 = _interopRequireDefault(_MatrixBuilder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(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); } }
// ----------------------------------------------------------------------------
// vtkConeSource methods
// ----------------------------------------------------------------------------
function vtkConeSource(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkConeSource');
function requestData(inData, outData) {
var _vtkMatrixBuilder$bui;
if (model.deleted) {
return;
}
var dataset = outData[0];
var angle = 2 * Math.PI / model.resolution;
var xbot = -model.height / 2.0;
var numberOfPoints = model.resolution + 1;
var cellArraySize = 4 * model.resolution + 1 + model.resolution;
// Points
var pointIdx = 0;
var points = new window[model.pointType](numberOfPoints * 3);
// Cells
var cellLocation = 0;
var polys = new Uint32Array(cellArraySize);
// Add summit point
points[0] = model.height / 2.0;
points[1] = 0.0;
points[2] = 0.0;
// Create bottom cell
if (model.capping) {
polys[cellLocation++] = model.resolution;
}
// Add all points
for (var i = 0; i < model.resolution; i++) {
pointIdx++;
points[pointIdx * 3 + 0] = xbot;
points[pointIdx * 3 + 1] = model.radius * Math.cos(i * angle);
points[pointIdx * 3 + 2] = model.radius * Math.sin(i * angle);
// Add points to bottom cell in reverse order
if (model.capping) {
polys[model.resolution - cellLocation++ + 1] = pointIdx;
}
}
// Add all triangle cells
for (var _i = 0; _i < model.resolution; _i++) {
polys[cellLocation++] = 3;
polys[cellLocation++] = 0;
polys[cellLocation++] = _i + 1;
polys[cellLocation++] = _i + 2 > model.resolution ? 1 : _i + 2;
}
// Apply tranformation to the points coordinates
(_vtkMatrixBuilder$bui = _MatrixBuilder2.default.buildFromRadian()).translate.apply(_vtkMatrixBuilder$bui, _toConsumableArray(model.center)).rotateFromDirections([1, 0, 0], model.direction).apply(points);
dataset = _PolyData2.default.newInstance();
dataset.getPoints().setData(points, 3);
dataset.getPolys().setData(polys, 1);
// Update output
outData[0] = dataset;
}
// Expose methods
publicAPI.requestData = requestData;
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
var DEFAULT_VALUES = {
height: 1.0,
radius: 0.5,
resolution: 6,
center: [0, 0, 0],
direction: [1.0, 0.0, 0.0],
capping: true,
pointType: 'Float32Array'
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model) {
var initialValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
_macro2.default.obj(publicAPI, model);
_macro2.default.setGet(publicAPI, model, ['height', 'radius', 'resolution', 'capping']);
_macro2.default.setGetArray(publicAPI, model, ['center', 'direction'], 3);
_macro2.default.algo(publicAPI, model, 0, 1);
vtkConeSource(publicAPI, model);
}
// ----------------------------------------------------------------------------
var newInstance = exports.newInstance = _macro2.default.newInstance(extend, 'vtkConeSource');
// ----------------------------------------------------------------------------
exports.default = { newInstance: newInstance, extend: extend };
/***/ }),
/* 314 */,
/* 315 */,
/* 316 */,
/* 317 */,
/* 318 */,
/* 319 */,
/* 320 */,
/* 321 */,
/* 322 */,
/* 323 */,
/* 324 */,
/* 325 */,
/* 326 */,
/* 327 */,
/* 328 */,
/* 329 */,
/* 330 */,
/* 331 */,
/* 332 */,
/* 333 */,
/* 334 */,
/* 335 */,
/* 336 */,
/* 337 */,
/* 338 */,
/* 339 */,
/* 340 */,
/* 341 */,
/* 342 */,
/* 343 */,
/* 344 */,
/* 345 */,
/* 346 */,
/* 347 */,
/* 348 */,
/* 349 */,
/* 350 */,
/* 351 */,
/* 352 */,
/* 353 */,
/* 354 */,
/* 355 */,
/* 356 */,
/* 357 */,
/* 358 */,
/* 359 */,
/* 360 */,
/* 361 */,
/* 362 */,
/* 363 */,
/* 364 */,
/* 365 */,
/* 366 */,
/* 367 */,
/* 368 */,
/* 369 */,
/* 370 */,
/* 371 */,
/* 372 */,
/* 373 */,
/* 374 */,
/* 375 */,
/* 376 */,
/* 377 */,
/* 378 */,
/* 379 */,
/* 380 */,
/* 381 */,
/* 382 */,
/* 383 */,
/* 384 */,
/* 385 */,
/* 386 */,
/* 387 */,
/* 388 */,
/* 389 */,
/* 390 */,
/* 391 */,
/* 392 */,
/* 393 */,
/* 394 */,
/* 395 */,
/* 396 */,
/* 397 */,
/* 398 */,
/* 399 */,
/* 400 */,
/* 401 */,
/* 402 */,
/* 403 */,
/* 404 */,
/* 405 */,
/* 406 */,
/* 407 */,
/* 408 */,
/* 409 */,
/* 410 */,
/* 411 */,
/* 412 */,
/* 413 */,
/* 414 */,
/* 415 */,
/* 416 */,
/* 417 */,
/* 418 */,
/* 419 */,
/* 420 */,
/* 421 */,
/* 422 */,
/* 423 */,
/* 424 */,
/* 425 */,
/* 426 */,
/* 427 */,
/* 428 */,
/* 429 */,
/* 430 */,
/* 431 */,
/* 432 */,
/* 433 */,
/* 434 */,
/* 435 */,
/* 436 */,
/* 437 */,
/* 438 */,
/* 439 */,
/* 440 */,
/* 441 */,
/* 442 */,
/* 443 */,
/* 444 */,
/* 445 */,
/* 446 */,
/* 447 */,
/* 448 */,
/* 449 */,
/* 450 */,
/* 451 */,
/* 452 */,
/* 453 */,
/* 454 */,
/* 455 */,
/* 456 */,
/* 457 */,
/* 458 */,
/* 459 */,
/* 460 */,
/* 461 */,
/* 462 */,
/* 463 */,
/* 464 */,
/* 465 */,
/* 466 */,
/* 467 */,
/* 468 */,
/* 469 */,
/* 470 */,
/* 471 */,
/* 472 */,
/* 473 */,
/* 474 */,
/* 475 */,
/* 476 */,
/* 477 */,
/* 478 */,
/* 479 */,
/* 480 */,
/* 481 */,
/* 482 */,
/* 483 */,
/* 484 */,
/* 485 */,
/* 486 */,
/* 487 */,
/* 488 */,
/* 489 */,
/* 490 */,
/* 491 */,
/* 492 */,
/* 493 */,
/* 494 */,
/* 495 */,
/* 496 */,
/* 497 */,
/* 498 */,
/* 499 */,
/* 500 */,
/* 501 */,
/* 502 */,
/* 503 */,
/* 504 */,
/* 505 */,
/* 506 */,
/* 507 */,
/* 508 */,
/* 509 */,
/* 510 */,
/* 511 */,
/* 512 */,
/* 513 */,
/* 514 */,
/* 515 */,
/* 516 */,
/* 517 */,
/* 518 */,
/* 519 */,
/* 520 */,
/* 521 */,
/* 522 */,
/* 523 */,
/* 524 */,
/* 525 */,
/* 526 */,
/* 527 */,
/* 528 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, $) {/*
* Management application for showing isosurfaces of the local universe
* and interactivity with several datasets.
*
* Copyright(C) 2017-2018 Guilhem Lavaux. Inspired from VTK Examples.
*/
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _ajax = __webpack_require__(128);
var _params = __webpack_require__(78);
var _error = __webpack_require__(77);
var error = _interopRequireWildcard(_error);
var _knockout = __webpack_require__(71);
var ko = _interopRequireWildcard(_knockout);
var _DataArray = __webpack_require__(16);
var _DataArray2 = _interopRequireDefault(_DataArray);
var _Actor = __webpack_require__(166);
var _Actor2 = _interopRequireDefault(_Actor);
var _FullScreenRenderWindow = __webpack_require__(546);
var _FullScreenRenderWindow2 = _interopRequireDefault(_FullScreenRenderWindow);
var _HttpDataSetReader = __webpack_require__(603);
var _HttpDataSetReader2 = _interopRequireDefault(_HttpDataSetReader);
var _ImageMarchingCubes = __webpack_require__(659);
var _ImageMarchingCubes2 = _interopRequireDefault(_ImageMarchingCubes);
var _Mapper = __webpack_require__(68);
var _Mapper2 = _interopRequireDefault(_Mapper);
var _Glyph3DMapper = __webpack_require__(661);
var _Glyph3DMapper2 = _interopRequireDefault(_Glyph3DMapper);
var _CubeSource = __webpack_require__(312);
var _CubeSource2 = _interopRequireDefault(_CubeSource);
var _ConeSource = __webpack_require__(313);
var _ConeSource2 = _interopRequireDefault(_ConeSource);
var _ArrowSource = __webpack_require__(663);
var _ArrowSource2 = _interopRequireDefault(_ArrowSource);
var _PixelSpaceCallbackMapper = __webpack_require__(666);
var _PixelSpaceCallbackMapper2 = _interopRequireDefault(_PixelSpaceCallbackMapper);
var _OrientationMarkerWidget = __webpack_require__(667);
var _OrientationMarkerWidget2 = _interopRequireDefault(_OrientationMarkerWidget);
var _AnnotatedCubeActor = __webpack_require__(669);
var _AnnotatedCubeActor2 = _interopRequireDefault(_AnnotatedCubeActor);
var _Constants = __webpack_require__(66);
var _lss = __webpack_require__(672);
var _RandomSources = __webpack_require__(673);
var _RandomSources2 = _interopRequireDefault(_RandomSources);
var _InterpolationFilter = __webpack_require__(674);
var _InterpolationFilter2 = _interopRequireDefault(_InterpolationFilter);
var _ImageStreamline = __webpack_require__(675);
var _ImageStreamline2 = _interopRequireDefault(_ImageStreamline);
var _style = __webpack_require__(676);
var _style2 = _interopRequireDefault(_style);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
__webpack_require__(678);
/*require.resolve*/(679);
/*
* This function sets up a cube to show the current scale. The cube
* is 400 Mpc/h wide, centered on the observer.
*/
function setupCube(renderer) {
var actor = _Actor2.default.newInstance();
var mapper = _Mapper2.default.newInstance();
var cubeSource = _CubeSource2.default.newInstance({
xLength: 1,
yLength: 1,
zLength: 1,
center: [0, 0, 0]
});
var actor_property = actor.getProperty();
actor_property.setRepresentationToWireframe();
actor_property.setColor(1, 1, 1);
actor_property.setAmbientColor(1, 1, 1);
actor_property.setInterpolationToFlat();
actor_property.setLighting(false);
actor_property.setAmbient(1);
actor_property.setDiffuse(0);
actor_property.setOpacity(0.5);
actor.setScale([400, 400, 400]);
actor.setMapper(mapper);
mapper.setInputConnection(cubeSource.getOutputPort());
renderer.addActor(actor);
}
/*
* This functions sets up the auxiliary actor to show the orientation
* of the camera, each side has a different color and label.
*/
function setupOrientationActor() {
var axes = _AnnotatedCubeActor2.default.newInstance();
axes.setDefaultStyle({
text: '+X',
fontStyle: 'bold',
fontFamily: 'Arial',
fontColor: 'black',
fontSizeScale: function fontSizeScale(res) {
return res / 2;
},
faceColor: '#0000ff',
edgeThickness: 0.1,
edgeColor: 'black',
resolution: 400
});
// axes.setXPlusFaceProperty({ text: '+X' });
axes.setXMinusFaceProperty({
text: '-X',
faceColor: '#ffff00',
fontStyle: 'italic'
});
axes.setYPlusFaceProperty({
text: '+Y',
faceColor: '#00ff00',
fontSizeScale: function fontSizeScale(res) {
return res / 4;
}
});
axes.setYMinusFaceProperty({
text: '-Y',
faceColor: '#00ffff',
fontColor: 'white'
});
axes.setZPlusFaceProperty({ text: '+Z', edgeColor: 'yellow' });
axes.setZMinusFaceProperty({ text: '-Z', edgeThickness: 0 });
return axes;
}
/*
* This function is the constructor the view object used
* by knockout to answer to change in the state of buttons/text inputs...
*/
function ControlView() {
var self = this;
// First initialize the render window and attach it to the
// adequate DOM entry.
var fullScreenRenderWindow = _FullScreenRenderWindow2.default.newInstance({
background: [0, 0, 0],
rootContainer: document.getElementById('placeholder'),
containerStyle: {
margin: '0',
display: 'inline-block',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
width: '100%',
height: '100%',
overflow: 'hidden'
}
});
var renderWindow = fullScreenRenderWindow.getRenderWindow();
var renderer = fullScreenRenderWindow.getRenderer();
global.renderer = renderer;
// -----------------------------------------------------------------
// Iso-surface setup
// Create the iso-surface generator.
var _setupIsoSurface = setupIsoSurface(),
_setupIsoSurface2 = _slicedToArray(_setupIsoSurface, 2),
isoActor = _setupIsoSurface2[0],
marchingCube = _setupIsoSurface2[1];
var reader = _HttpDataSetReader2.default.newInstance({
fetchGzip: true,
progressCallback: function progressCallback(ev) {
loadIndicator(0, ev);
}
});
marchingCube.setInputConnection(reader.getOutputPort());
// -----------------------------------------------------------------
// -----------------------------------------------------------------
// Now prepare the streamline part
//const streamline = setupStreamline();
// Arrow vector part
/* slineActor.getProperty().set({
representation: Representation.POINTS,
pointSize: 1
});*/
// -----------------------------------------------------------------
// Create the small orientation actor to show what is the status
// of the camera.
var orientationWidget = _OrientationMarkerWidget2.default.newInstance({
actor: setupOrientationActor(),
interactor: renderWindow.getInteractor()
});
// Add the empty cube
setupCube(renderer);
// -----------------------------------------------------------------
// Manage the names on top of the 3d representation
// Create a canvas
var textCanvas = document.createElement('canvas');
// Add adequate class style
textCanvas.classList.add(_style2.default.container, 'textCanvas');
// Add the DOM element.
fullScreenRenderWindow.getContainer().appendChild(textCanvas);
var textCtx = textCanvas.getContext('2d');
var dims = null;
var textActor = _Actor2.default.newInstance();
var psMapper = _PixelSpaceCallbackMapper2.default.newInstance();
(0, _lss.setupLSS)().then(function (args) {
var names = args.names;
var polyData = args.poly;
var centerPos = args.center;
psMapper.setInputConnection(polyData.getOutputPort());
psMapper.setCallback(function (coordsList) {
if (textCtx && dims) {
// textCtx.strokeStyle = "#fff";
textCtx.font = '12px serif';
textCtx.textAlign = 'center';
textCtx.textBaseline = 'middle';
textCtx.setTransform(1, 0, 0, 1, 0, 0);
textCtx.clearRect(0, 0, dims.width, dims.height);
var mw = coordsList[centerPos];
coordsList.forEach(function (xy, idx) {
if (idx == centerPos) {
return;
}
var name = names[idx];
var x = xy[0];
var y = dims.height - xy[1];
textCtx.setTransform(1.2 - 1 * (xy[2] - mw[2]), 0, 0, 1.2 - 1 * (xy[2] - mw[2]), x, y);
var width_txt = textCtx.measureText(name).width;
textCtx.fillStyle = 'rgba(10,0,60,0.3)';
textCtx.fillRect(-0.6 * width_txt, -10, 1.2 * width_txt, 20);
textCtx.fillStyle = '#f00';
textCtx.fillText(name, 0, 0);
});
}
});
textActor.setMapper(psMapper);
renderer.addActor(textActor);
// -----------------------------------------------------------------
});
// Handle window resize
fullScreenRenderWindow.setResizeCallback(function (newDims) {
dims = newDims;
textCanvas.setAttribute('width', dims.width);
textCanvas.setAttribute('height', dims.height);
});
self.progressBar = ko.observable(false);
global.test_control = self;
self.progressPct = ko.observable(0);
self.minDataRange = ko.observable(-1);
self.maxDataRange = ko.observable(1);
self.isoValue = ko.observable(1);
self.specBright = ko.observable(0.5);
self.useNormals = ko.observable(true);
self.baseColor = ko.observable('#ff0000');
self.addSpecular = ko.observable(true);
self.dataset = ko.observable();
self.autoRefresh = ko.observable(false);
// Delay the trigger of the loading to the moment the whole page is ready.
$(document).ready(function () {
self.dataset('twompp_10.vtp');
// Construction of arrows too.
console.log("Go arrows");
setupArrows();
});
self.firstTime = true;
self.dataset.subscribe(function () {
var name = self.dataset();
self.progressPct(0);
self.progressBar(true);
self.autoRefresh(false);
reader.setUrl('/data/' + name, { loadData: true }).then(function () {
var data = reader.getOutputData();
var pointData = data.getPointData();
var scalars = pointData.getScalars();
var dataRange = scalars.getRange();
self.minDataRange(-1); //dataRange[0]);
self.maxDataRange(2); //dataRange[1]);
self.progressBar(false);
marchingCube.setContourValue(self.isoValue());
if (self.firstTime) {
renderer.addActor(isoActor);
renderer.getActiveCamera().set({ position: [1, 1, 1], viewUp: [0, 0, 1] });
orientationWidget.setEnabled(true);
orientationWidget.setViewportCorner(_OrientationMarkerWidget2.default.Corners.BOTTOM_LEFT);
orientationWidget.setViewportSize(0.15);
renderer.resetCamera();
self.firstTime = false;
}
renderWindow.render();
self.autoRefresh(true);
});
});
self.isoValue.subscribe(function (value) {
marchingCube.setContourValue(Number(value));
renderWindow.render();
});
self.specBright.subscribe(function (value) {
var specBright = Number(value);
isoActor.getProperty().setSpecularPower(value);
renderWindow.render();
});
self.useNormals.subscribe(function (activeNormals) {
marchingCube.setComputeNormals(activeNormals);
renderWindow.render();
});
self.addSpecular.subscribe(function (value) {
isoActor.getProperty().setSpecular(value);
renderWindow.render();
});
self.baseColor.subscribe(function (color) {
var c = hexToRgb(color);
isoActor.getProperty().setDiffuseColor(c.r / 255.0, c.g / 255.0, c.b / 255.0);
renderWindow.render();
});
$(function () {
$('.surface_color').colorpicker();
});
return self;
function setupIsoSurface() {
var actor = _Actor2.default.newInstance();
var mapper = _Mapper2.default.newInstance();
var marchingCube = _ImageMarchingCubes2.default.newInstance({
contourValue: 0.0,
mergePoints: true,
computeNormals: true
});
var actor_property = actor.getProperty();
actor_property.setColor(1, 1, 1);
actor_property.setDiffuseColor(1, 0, 1);
actor_property.setAmbientColor(0.1, 0.1, 0.1);
actor_property.setSpecularColor(1, 1, 1);
actor_property.setSpecular(true);
// actor.setScale([1,1,1]);
// actor.setPosition([-200, -200, -200]);
actor.setMapper(mapper);
mapper.setInputConnection(marchingCube.getOutputPort());
return [actor, marchingCube];
}
function setupArrows() {
var mapper = _Glyph3DMapper2.default.newInstance();
var actor = _Actor2.default.newInstance();
var coneSource = _ArrowSource2.default.newInstance({ tipRadius: 0.2, shaftRadius: 0.02, tipLength: 0.4 });
var vecSource = _HttpDataSetReader2.default.newInstance({
fetchGzip: true
});
var interpolationFilter = _InterpolationFilter2.default.newInstance();
var randPoints = _RandomSources2.default.newInstance();
randPoints.setMinBox(0.);
randPoints.setMaxBox(32.);
randPoints.setNumPoints(6000);
interpolationFilter.setInputConnection(randPoints.getOutputPort(), 0);
mapper.setInputConnection(interpolationFilter.getOutputPort(), 0);
mapper.setInputConnection(coneSource.getOutputPort(), 1);
mapper.setScaleModeToScaleByComponents();
mapper.setOrientationModeToRotation();
mapper.setScalarRange(0.0, 3000.0);
mapper.setScaleFactor(3e-3);
//coneSource.setResolution(12);
actor.setScale([400 / 31, 400 / 31, 400 / 31]);
actor.setPosition([-200, -200, -200]);
// actor.getProperty().setOpacity(0.3);
actor.setMapper(mapper);
console.log("Set callbacks for arrows.");
vecSource.setUrl('/data_vec/vfield.vtp', { loadData: true }).then(function () {
console.log("Got data");
var arrays = vecSource.getArrays().filter(function (a) {
return a.name == "vectors";
});
vecSource.getOutputData().getPointData().setVectors(_DataArray2.default.newInstance(arrays[0].array));
interpolationFilter.setInputConnection(vecSource.getOutputPort(), 1);
// actor.setScale([10,10,10]);
console.log("Actor added");
renderer.addActor(actor);
renderWindow.render();
var counter = 0;
var arrowRefreshActive = false,
arrowRefresh = null;
self.autoRefresh.subscribe(function () {
var refresh = self.autoRefresh();
console.log("Refresh state change to ", refresh);
if (refresh) {
if (arrowRefreshActive) clearInterval(arrowRefresh);
arrowRefresh = setInterval(function () {
mapper.setScaleFactor(3e-3 * counter / 40);
counter = (counter + 1) % 40;
renderWindow.render();
}, 100);
arrowRefreshActive = true;
} else if (arrowRefreshActive) clearInterval(arrowRefresh);
});
});
}
function setupStreamline() {
var sline = _ImageStreamline2.default.newInstance();
var vecSource = _HttpDataSetReader2.default.newInstance({
fetchGzip: true
});
var randPoints = _RandomSources2.default.newInstance();
randPoints.setMinBox(0.);
randPoints.setMaxBox(32.);
randPoints.setNumPoints(600);
sline.setInputConnection(randPoints.getOutputPort(), 1);
sline.setIntegrationStep(0.001);
sline.setMaximumNumberOfSteps(20);
vecSource.setUrl('/data_vec/vfield.vtp', { loadData: true }).then(function () {
var arrays = vecSource.getArrays().filter(function (a) {
return a.name == "vectors";
});
vecSource.getOutputData().getPointData().setVectors(_DataArray2.default.newInstance(arrays[0].array));
sline.setInputConnection(vecSource.getOutputPort());
var slineMapper = _Mapper2.default.newInstance();
var slineActor = _Actor2.default.newInstance();
slineMapper.setInputConnection(sline.getOutputPort());
slineActor.setMapper(slineMapper);
slineActor.setScale([400 / 31, 400 / 31, 400 / 31]);
slineActor.setPosition([-200, -200, -200]);
renderer.addActor(slineActor);
renderWindow.render();
});
return sline;
}
function loadIndicator(fid, pe) {
if (pe.lengthComputable) {
if (pe.total > 0) {
self.progressPct(parseInt(pe.loaded * 100 / pe.total));
} else self.progressPct(0);
}
}
function hexToRgb(h) {
var r = parseInt(cutHex(h).substring(0, 2), 16),
g = parseInt(cutHex(h).substring(2, 4), 16),
b = parseInt(cutHex(h).substring(4, 6), 16);
return { r: r, g: g, b: b };
}
function cutHex(h) {
return h.charAt(0) == '#' ? h.substring(1, 7) : h;
}
}
ko.applyBindings(new ControlView());
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25), __webpack_require__(6)))
/***/ }),
/* 529 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function(handle) {
process.nextTick(function () { runIfPresent(handle); });
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function(handle) {
// Create a